NOTE:1.当用户登录时可以选择自动登录时长
2.登陆失败(账号/密码错误)要返回登录页且在登录页显示(账号或密码错误)
3.登陆成功后若关闭浏览器再打开该页面仍保持已登录状态
4.当用户选择退出登录(注销)时,退出用户登录

新建类User

package Bean;

public class User {
    private String name;
    private String password;

    public User (String name, String password){
        this.name = name;
        this.password = password;
    }

    public User(){

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

登录页”login.jsp”

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/4/13
  Time: 14:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head></head>
<center><h3>用户登录</h3></center>
<body style="text-align: center;">
<form action="/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" /></td>
        </tr>
        <%
            //获取LoginServlet中32行error的值并赋值给变量"a".
            String a=(String) session.getAttribute("error");

            //实现消除主页面一直提示为"null"情况:
            //判断变量"a"返回值是否为空[如果为空则证明登陆成功,不为空则登陆失败].
            if (a!=null){ //如果不为空
                out.print(a); //输出变量"a"的值.
            }
            else{ //反之输出"",[即为空,什么都没有]
                out.print("");
            }
        %>
        <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>

编写首页(登陆成功页)index.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/4/13
  Time: 15:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <c:choose>
    <c:when test="${user==null}">
      <a href="/login.jsp">请登录</a>
    </c:when>
    <c:otherwise>
      ${user.name}欢迎您!
      <a href="/LogOutServlet">注销</a>
    </c:otherwise>
  </c:choose>

  </body>
</html>

创建登录处理服务器:LoginServlet

package Servlet;

import Bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");//设置编码格式,否则输出为乱码或"???"
        PrintWriter out=response.getWriter();
        request.setCharacterEncoding("utf-8");
        //获取参数值
        String name=request.getParameter("username");
        String password=request.getParameter("password");
        //验证信息是否正确,admin 123
        //信息正确,将数据存入域中,跳转至后台页面index.jsp
        if (name.equals("admin")&&password.equals("123")){
            User user=new User(name,password);
            request.getSession().setAttribute("user",user);
            String logintime=request.getParameter("autologin");//获取自动登录时间
            //创建cookie,存储自动登录的状态
            Cookie cookie=new Cookie("autolog",name+"-"+password);//admin-123
            cookie.setMaxAge(Integer.parseInt(logintime));//设置cookie生存时长,将自动登录的时间的字符串表示转换成int
            cookie.setPath("/");//设置cookie路径
            response.addCookie(cookie);//将cookie带回浏览器
            //重定向至后台页面
            response.sendRedirect("/index.jsp");
        }
        //信息不正确,将错误提示存入域中,跳转回登录页面login.jsp
        else{
            HttpSession session=request.getSession();

//            request.getSession().setAttribute("error","用户名或密码错误!");
            session.setAttribute("error","用户名或密码错误!");
            Cookie c=new Cookie("JSESSIONID",session.getId());
            c.setPath(request.getContextPath());
            c.setMaxAge(3);//生存时间,以秒为单位.
            response.addCookie(c);//将变量"c"添加到浏览器请求头
            response.sendRedirect("http://localhost:8080/login.jsp");//重定向至URL:"http://localhost:8080"
        }
    }

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

    }
}

创建登录过滤器:LoginFilter

package Filter;

import Bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
//拦截所有请求响应
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //是否能获取存储自动登录状态的cookie-----name:autolog
        HttpServletRequest request=(HttpServletRequest)req;
        Cookie cookies[]=request.getCookies();
        String value=null;
        for (int i=0;cookies!=null&&i<cookies.length;i++){
           if (cookies[i].getName().equals("autolog")){//如果找到名为"autolog"的cookie
               value=cookies[i].getValue();//获取该cookie的值(name-passowrd)
               break;
           }
        }
        if (value!=null){
            String str[]= value.split("-");//{name,password}
            String username=str[0];
            String password=str[1];
            if (username.equals("admin")&&password.equals("123")){
                User user=new User(username,password);
                request.getSession().setAttribute("user",user);
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

注意事项

NOTE:该项目有需待优化项(所属密码错误时登录页显示信息代码块),待优化完毕后会重新上传,已购买用户无需再次付费!
NOTE:该项目需要jar包,如有需要请在前几篇文章中查找,或在专属板块:Admin生态圈->专业类Software中查找”JavaWeb-Jar包”
资源下载此资源下载价格为5摩拉,请先
博主Qq:2807306273