21.【任务案例:实现用户自动登录】

任务目标

通过前面的学习,我们了解到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">密   &nbsp;码:</td>

        <td>&nbsp;&nbsp;<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="登录" />&nbsp;&nbsp;&nbsp;&nbsp;

            <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
也能显示用户登录信息。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
近年来,随着互联网技术的迅猛发展,越来越多的企业开始实施办公自动化系统来管理日常工作流程。本文重点介绍基于PHP技术的办公自动化系统的设计与实现。 一、需求分析 首先,我们需要了解用户的需求,明确系统的功能和特点。一个办公自动化系统应该具备以下特点: 1. 功能齐全:能够满足企业各类任务处理需求,包括文件管理、流程审批、任务分配等等。 2. 易于使用:界面简单直观、操作便捷,方便用户进行数据查询、修改等操作。 3. 数据安全性高:采用安全的身份验证和数据传输加密等措施,保证业务数据的安全性。 二、系统设计 基于需求分析的结果,我们可以设计出一种较为简单的系统架构。 1. 前端展示层:采用HTML、CSS和JavaScript等前端技术搭建图形用户界面,用户可以通过此界面进行操作; 2. 后端应用层:采用PHP技术作为后端应用开发语言,接收和处理用户请求,以及查询、修改和删除数据; 3. 数据库层:采用MySQL等关系型数据库管理系统,存储企业信息、文件、流程、任务等业务数据。 在系统设计方面,我们还可以考虑引入一些流行的组件和框架来辅助开发。例如: 1. layui:一个前端UI框架,可用于快速构建美观的后台界面; 2. ThinkPHP:一个基于MVC模式的PHP框架,可用于快速搭建后端应用程序,并提供一些便捷的数据库操作方法; 3. PHPMailer:一个PHP邮件发送库,可用于发送邮件提醒用户任务进度等。 三、系统实现 根据系统设计方案,我们可以开始实现整个系统。在实际开发中,需要分模块进行实现,严格按照需求分析和系统设计的要求开发各个功能模块,最后进行集成测试,确保系统稳定可靠。关于具体实现过程,在此不再赘述。 四、总结 基于PHP技术的办公自动化系统是一种高效的工作流程管理模式,可以提高企业工作效率,简化工作流程。本文简单介绍了基于PHP技术的办公自动化系统设计与实现,提供了一个快速上手的案例,希望有助于大家的实际开发工作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

聊城云在天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值