服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - JavaWeb实现自动登录功能

JavaWeb实现自动登录功能

2021-11-19 14:15Alan_TW Java教程

这篇文章主要为大家详细介绍了JavaWeb实现自动登录功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了JavaWeb实现自动登录功能的具体代码,供大家参考,具体内容如下

自动登录是通过存储cookie值来实现的。

工程目录如下:

JavaWeb实现自动登录功能

login.jsp:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录</title>
</head>
<body>
    <form action="login" method="post">
        用户名:<input name="username" type="text"><br>
        密码:<input name="password" type="password">
        <input type="checkbox" name="autoLogin" value="autoLogin">自动登录
        <input type="submit" value="提交">
    </form>
</body>
</html>

success.jsp(主要用于测试是否储存成功):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    ${sessionScope.username }<br>
    ${sessionScope.password }
</body>
</html>

LoginServlet(用于登录逻辑处理):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package servletLogin;
 
import java.io.IOException;
import java.net.URLEncoder;
 
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
 
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        HttpSession session = request.getSession();
        //登录成功,(在这应该是和数据库的值对比)
        if(username.equals("alan呵呵") && password.equals("123")){
            
            String autoLogin = request.getParameter("autoLogin");
 
            if(autoLogin!=null){
 
                //编码是为了在cookie中存储汉字
                String usernameCode = URLEncoder.encode(username, "utf-8");
                
                Cookie usernameCookie = new Cookie("username",usernameCode);
                Cookie passwordCookie = new Cookie("password",password);
                //设置持久化时间
                usernameCookie.setMaxAge(60*60);
                passwordCookie.setMaxAge(60*60);
                //设置cookie携带路径
                usernameCookie.setPath(request.getContextPath());
                passwordCookie.setPath(request.getContextPath());
                //发送cookie
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }
            
            session.setAttribute("username", username);
            session.setAttribute("password", password);
            response.sendRedirect("success.jsp");
        }else{
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}

LoginFilter(用于自动登录的拦截器):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package filter;
 
import java.io.IOException;
import java.net.URLDecoder;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
 
public class LoginFilter implements Filter {
 
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
 
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
 
        // 获得cookie中用户名和密码 进行登录的操作
        // 定义cookie_username
        String cookie_username = null;
        // 定义cookie_password
        String cookie_password = null;
        // 获得cookie
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 获得名字是cookie_username和cookie_password
                if ("username".equals(cookie.getName())) {
                    cookie_username = cookie.getValue();
                    // 对cookie中的值解码
                    cookie_username = URLDecoder.decode(cookie_username,
                            "UTF-8");
                }
                if ("password".equals(cookie.getName())) {
                    cookie_password = cookie.getValue();
                }
            }
        }
        
        if(cookie_username != null && cookie_password != null){
            if(cookie_username.equals("alan呵呵") && cookie_password.equals("123")){
                session.setAttribute("username", cookie_username);
                session.setAttribute("password", cookie_password);
            }
        }
        chain.doFilter(request, response);
    }
    public void destroy() {
    }
    public void init(FilterConfig fConfig) throws ServletException {
    }
}

web.xml配置文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
version="2.5">
  <display-name>WEB24</display-name>
 
 
  <!-- 自动登录的filter -->
 <filter>
      <filter-name>AutoLoginFilter</filter-name>
      <filter-class>filter.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>AutoLoginFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
 
 
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
 
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>servletLogin.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
 
 
</web-app>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Alan_TW/article/details/80535844

延伸 · 阅读

精彩推荐