java - 在 JSP 页面中收到的变量值为 null

标签 java jsp servlets

<分区>

我做了一个简单的登录应用程序。但是每当发送表单时,servlet 都会收到空数据。

下面是登录页面

<body>
<form action="login">
    Enter login Name : <input type="text" name="userName"/><br/>
    Enter password   : <input type="password" name="userPassword"/><br/>
    <input type="submit" value="Log In"/>
</form>

下面是检查输入变量值的servlet代码

@WebServlet("/login")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public loginServlet() {
    super();
    // TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = (String)request.getAttribute("userName");
    String password = (String)request.getAttribute("userPassword");

    System.out.print("in doGet method");
    System.out.print(name+" "+password+" are these");


    if(name!=null && password!=null){
        System.out.print("in null method");
        if(name=="admin" && password=="admin"){
//              Cookie cookie = new Cookie("userName", name);
//              response.addCookie(cookie);
//              RequestDispatcher dispatch = request.getRequestDispatcher("success.jsp");
//              dispatch.forward(request, response);

            response.sendRedirect("success.jsp");
        }
        else{
            System.out.print("in error method");
            response.sendRedirect("error.jsp");
        }
    }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

我正在使用 System.out.print 方法在 Tomcat 控制台中打印值。

最佳答案

这些对 Request.getAttribute(String) 的调用

String name = (String)request.getAttribute("userName");
String password = (String)request.getAttribute("userPassword");

应该调用 Request.getParameter(String) (根据 Javadoc,将请求参数的值作为 String 返回)。喜欢

String name = request.getParameter("userName");
String password = request.getParameter("userPassword");

此外,

if(name=="admin" && password=="admin"){

应该是这样的

if (name.equals("admin") && password.equals("admin")) {

因为 String 是一个 Object,而您需要等效值(不是相同的引用)。

关于java - 在 JSP 页面中收到的变量值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32261281/

相关文章:

java - jsp:include 运行时给出 404

java - 解码 PKCS-7 请求

java - 如何通过ArrayList获取所有同名的html输入值到servlet

java - 缓存流处理大文件

hibernate - 空闲事务 Hibernate/PostgreSQL

java - 使用 Runtime.getRuntime().totalMemory() 和 freeMemory() 计算内存的结果令人困惑?

jsp - 如果我通过bean,如何访问jsp中的数组列表

java - Cookie http 仅适用于 spring security 和 servlet 2.5?

java - Sonar 管 5.6 : violations reported for an outer class by findbugs is not reported as a sonar violation

java - commit() 后 SharedPreference 未更新