request.getAttribute从HTML返回null

时间:2017-08-21 04:21:56

标签: jsp servlets

我写了一个登录HTML并将用户名,密码提交给servlet

@WebServlet(name = "loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post");
        Enumeration enumeration = request.getAttributeNames();
        while (enumeration.hasMoreElements()) {
            System.out.println(enumeration.nextElement());
        }
        String username = (String) request.getAttribute("username");
        String password = (String) request.getAttribute("password");
        System.out.println(username);
        System.out.println(password);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

我的HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>

<h1>Login</h1>


<form action="/loginServlet" method="post">
    User Name: <input required name="username" value="name">
    Password: <input required type="password" name="password" value="pw">
    <input type="submit" value="Submit">
</form>

</body>
</html>

servlet的输出是: 岗位 空值 空

我检查了request.getAttribute returning null in servlet 但这种情况是JSP,而不是HTML。

有什么不对吗?或者我可以使用HTML而不是JSP来获取用户名和密码吗?

4 个答案:

答案 0 :(得分:1)

对于登录页面,请使用以下代码:

<form action="servlet1" method="post">
Name:<input type="text" name="username"/><br/><br/>
Password:<input type="password" name="userpass"/><br/><br/>
<input type="submit" value="login"/>
</form>

并获取该表单的属性创建一个类并编写以下代码:

public class FirstServlet extends HttpServlet {  
public void doPost(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  

response.setContentType("text/html");  
PrintWriter out = response.getWriter();  

String n=request.getParameter("username");  
String p=request.getParameter("userpass");  


}  
}  

答案 1 :(得分:0)

从表单传递的值“username”和“password”是参数而不是属性。

Difference between getAttribute() and getParameter()

答案 2 :(得分:0)

使用getParameter而不是getAttribute,如下面的代码所示;

String username = request.getParameter(“username”); String password = request.getParameter(“password”);

答案 3 :(得分:0)

@HAO,request.getAttribute()仅用于服务器端。请改用request.getParameter()。这是我们应该使用的方法来从客户端到服务器端获取值。有关详细信息,请参阅此谢谢Momus&amp; Braj Ankit

Difference between getAttribute() and getParameter()