使用cookie保存用户名和密码

效果图如下

从数据库中随意使用一个账号登录


登陆成功来到人中心

返回登录界面

实现代码如下

package com.test.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.service.UserService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login_do")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		Cookie cookieUsername=new Cookie("username", username);
		Cookie cookiePassword=new Cookie("password", password);
		
		UserService userService=new UserService();
		boolean isSuccess=userService.login(username, password);
		
		if(isSuccess) {
			request.setAttribute("msg", "登陆成功");
			cookieUsername.setMaxAge(60*60*24*30);
			cookiePassword.setMaxAge(60*60*24*30);
			
			response.addCookie(cookieUsername);
			response.addCookie(cookiePassword);
			
			request.getRequestDispatcher("personCenter.jsp").forward(request, response);;
		}else {
			request.setAttribute("msg", "用户名或密码错误");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>???????</title>
</head>
<body>
<%
String username="";
String password="";
Cookie[] cookies=request.getCookies();
if(cookies!=null&&cookies.length>0){
	for(int i=0;i<cookies.length;i++){
		if("username".equals(cookies[i].getName())){
			username=cookies[i].getValue();
		}else if("password".equals(cookies[i].getName())){
			password=cookies[i].getValue();
		}
	}
}
%>
<h1>登录</h1>
${requestScope.msg }
<hr/>
<form action="login_do" method="post">
用户名<input type="text" placeholder="用户名" name="username" value="<%=username%>"><br/><br/>
密码<input type="password" placeholder="密码" name="password" value="<%=password%>"><br/><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
posted @ 2019-04-02 17:38  iiiiiiCode  阅读(3786)  评论(0编辑  收藏  举报