叨叨两句

  1. ~

记住用户名

  1. 在servlet中增加一个判断,如果客户端需要记住用户名,则新建一个cookie,有效期不为0,如果不需要了,则有效期为0
  2. 登录成功,请求转发到登录欢迎页面
  3. 登录失败,请求转发到原登录页面
package com.qq.web.servlet;

import java.io.IOException;
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 com.qq.bean.User;
import com.qq.service.UserService;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //拿到参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remeber = request.getParameter("remeber");
        //调用service层处理登录请求
        UserService userService = new UserService();
        User user = userService.doLogin(username,password);
        Cookie cookie = new Cookie("username", username);
        //检查是否需要记住用户名
        if ("on".equals(remeber)) {
            //设置cookie有效期
            cookie.setMaxAge(24*60*60);
        } else {
            //不需要则清空cookie
            //设置cookie有效期
            cookie.setMaxAge(0);
        }
        
        //设置cookie有效范围
        cookie.setPath(request.getContextPath());
        //添加cookie
        response.addCookie(cookie);
        //根据返回的user决定如何响应
        if(user != null) {
            //登录成功,重定向到欢迎页面
            System.out.println(user);
            request.setAttribute("user", user);
            request.getRequestDispatcher("/success.jsp").forward(request, response);
//            response.sendRedirect(request.getContextPath()+"/success.jsp");
        } else {
            //登录失败,请求转发到登录页面,并输出错误信息
            request.setAttribute("msg", "用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

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

}

Wall_Breaker
2.1k 声望1.2k 粉丝

生死之间,就是我的跃迁之路,全程记录,欢迎见证