后端servlet代码
package test;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public loginServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置post请求乱码问题
request.setCharacterEncoding("utf-8");
//1.接用户的请求与数据
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
String ck=request.getParameter("ck");
//判断是否勾选记住用户名与密码
if("on".equals(ck)){//被选中的状态是on 没有被选中的状态下是null
//创建cookie对象
//Cookie c = new Cookie("user", name+"-"+pwd);
Cookie c=new Cookie("user", URLEncoder.encode(name+"-"+pwd, "utf-8"));
//设置有效期
c.setMaxAge(30);
//存储cookie
response.addCookie(c);
}
}
}
前端jsp页面
<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URL"%>
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//声明一个变量存记住的用户名与密码
String name="";
String pwd="";
Cookie[] c=request.getCookies();
if(c!=null){
for(int i=0;i<c.length;i++){
if(c[i].getName().equals("user")){
name=c[i].getValue().split("-")[0];
pwd=c[i].getValue().split("-")[0];
//处理中文乱码问题
//name=URLDecoder.decode(c[i].getValue().split("-")[0], "utf-8");
//pwd=URLDecoder.decode(c[i].getValue().split("-")[1], "utf-8");
break;
}
}
}
%>
<form method="post" action="loginServlet">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="name" id="name" value="<%= name %>"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="pwd" id="pwd" value="<%= pwd %>"/></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name="ck"/>记住用户名与密码</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登录"/></td>
</tr>
</table>
</form>
</body>
</html>
效果:登录时页面
重新访问登录页面,效果如下: