【302天】每日項目總結系列040(2017.12.04)

叨叨兩句

  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);
    }

}
相關文章
相關標籤/搜索