【任务案例】实现用户自动登录
任务目标
通过前面的学习,我们了解到Cookie可以实现用户自动登录的功能。当用户第1次访问服务器时,服务器会发送一个包含用户信息的Cookie。之后,当客户端再次访问服务器时,会向服务器回送Cookie。这样,服务器就可以从Cookie中获取用户信息,从而实现用户的自动登录功能。
使用Cooke实现用户自动登录后,当客户端访问服务器的Servlet时,所有的Servlet都需要对用户的Cookie信息进行校验,这样势必会导致在Servlet程序中书写大量的重复代码。
为了解决上面的问题,可以在Filter程序中实现Cookie的校验。由于Filter可以对服务器的所有请求进行拦截,因此,一旦请求通过Filter程序,就相当于用户信息校验通过,Servlet程序根据获取到的用户信息,就可以实现自动登录了。通过本任务的学习,同学将会学会使用Filter实现用户的自动登录功能
实现步骤
1.创建实体类user
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2.创建登录页面login.jsp
<html>
<head></head>
<center><h3>用户登录</h3></center>
<body style="text-align: center;">
<form action="${pageContext.request.contextPath}/LoginServlet"
method="post">
<table border="1" width="600px" cellpadding="0"
cellspacing="0"align="center">
<tr>
<td height="30" align="center">用户名:</td>
<td><input type="text" name="username" />${errerMsg }</td>
</tr>
<tr>
<td height="30" align="center">密 码:</td>
<td> <input type="password" name="password" /></td>
</tr>
<tr>
<td height="35" align="center">自动登录时间</td>
<td><input type="radio" name="autologin"
value="${60*60*24*31 }" />一个月
<input type="radio" name="autologin"
value="${60*60*24*31*3 }" />三个月
<input type="radio" name="autologin"
value="${60*60*24*31*6 }" />半年
<input type="radio" name="autologin"
value="${60*60*24*31*12 }" />一年
</td>
</tr>
<tr>
<td height="30" colspan="2" align="center">
<input type="submit" value="登录" />
<input type="reset" value="重置" />
</td>
</tr>
</table>
</form>
</body>
<html>
3.创建LoginServlet
@WebServlet("/LoginServlett")
public class LoginServlett extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获得用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 检查用户名和密码
if ("itcast".equals(username) && "123456".equals(password)) {
// 登录成功
// 将用户状态 user 对象存入 session域
User user = new User();
user.setUsername(username);
user.setPassword(password);
request.getSession().setAttribute("user", user);
// 发送自动登录的cookie
String autoLogin = request.getParameter("autologin");
if (autoLogin != null) {
// 注意 cookie 中的密码要加密 itcast-123456
Cookie cookie = new Cookie("autologin", username + "-" +password);
cookie.setMaxAge(Integer.parseInt(autoLogin));
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}
// 跳转至首页
response.sendRedirect(request.getContextPath()+ "/index.jsp");
}else {
request.setAttribute("errerMsg", "用户名或密码错");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}
4.创建登录成功后的首页index.jsp
<html>
<head>
<title>显示登录的用户信息</title>
</head>
<body>
<br>
<center>
<h3>欢迎光临</h3>
</center>
<br>
<c:choose>
<c:when test="${sessionScope.user==null}">
<a href="${pageContext.request.contextPath}/login.jsp">
用户登录</a>
</c:when>
<c:otherwise>
欢迎你,${sessionScope.user.username }!
<a href="${pageContext.request.contextPath }/LogoutServlet">注销</a>
</c:otherwise>
</c:choose>
<hr>
</body>
</html>
5.创建过滤器AutoLoginFilter
@WebFilter("/*")
public class AutoLoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
// 获得一个名为 autologin的cookie
Cookie[] cookies = request.getCookies();
String autologin = null;
for (int i = 0; cookies != null && i < cookies.length; i++) {
if ("autologin".equals(cookies[i].getName())) {
// 找到了指定的cookie itcast-123456
autologin= cookies[i].getValue();
break;
}
}
if (autologin != null) {
// 做自动登录
String[] parts = autologin.split("-");
String username = parts[0];
String password = parts[1];
// 检查用户名和密码
if ("itcast".equals(username)&& ("123456").equals(password)) {
// 登录成功,将用户状态 user 对象存入 session域
User user = new User();
user.setUsername(username);
user.setPassword(password);
request.getSession().setAttribute("user", user);
}
}
// 放行
chain.doFilter(request,resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
6.创建注销的LogoutServlet
@WebServlet("/LogoutServlett")
public class LogoutServlett extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//删除session中的值
request.getSession().removeAttribute("user");
//删除客户端保存的登录cookie
Cookie cookie=new Cookie("autologin","msg");
cookie.setPath(request.getContextPath());
cookie.setMaxAge(0);
response.addCookie(cookie);
response.sendRedirect(request.getContextPath()+"/index.jsp");
out.flush();
out.close();
}
}
运行http://localhost:8080/login.jsp 输入用户名称密码进入 后台
关闭浏览器后,下次直接输入后台地址:http://localhost:8080/index.jsp
也能显示用户登录信息。