当我在eclipse中启动动态应用程序时,我的Login.html被设置为欢迎文件,并显示出来。在那里,我有一个简单的表格:
Login.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="LoginServlet" method="post">
<table>
<tr><td align="right">Username:</td><td><input type="text" name="userName"/></td></tr>
<tr><td align="right">Password:</td><td><input type="password" name="password"/></td></tr>
<tr><td/><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
<p>
<a href="Register.html">Register</a>
</p>
</body>
</html>
LoginServlet的代码:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
ServletContext context = getServletContext();
Map<String, User> users = (Map<String, User>) context.getAttribute("users");
User user = users.get(userName);
if (user == null) {
response.sendRedirect("./Login.html");
return;
}
if (!user.getUserName().equals(userName)) {
response.sendRedirect("./Login.html");
return;
}
if (!user.getPassword().equals(password)) {
response.sendRedirect("./Login.html");
return;
}
request.getSession().setAttribute("loggedInUser", user);
response.sendRedirect("./WebShopServlet");
}
}
我还有一个InitListener类,我在其中创建了2个用户并将其放在上下文中:
public class InitListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
}
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
Map<String, User> users = new LinkedHashMap<>();
User user = null;
user = new User("a", "a", Role.ADMIN);
users.put(user.getUserName(), user);
user = new User("b", "b", Role.USER);
users.put(user.getUserName(), user);
context.setAttribute("users", users);
Products products = new Products(context.getRealPath(""));
context.setAttribute("products", products);
}
现在,当我在浏览器中单击以制成形式提交时出现错误。在eclipse控制台中,它说这是第34行的空指针异常, 这是LoginServlet中的 User user = users.get(userName); 。