目的:当用户登录后,将用户名和密码放置到cookie中,用于下次再登录,将cookie中存放的用户名和密码放置到文本框中,不需要再填写。
(1)页面中:
<tr>
<td width="100"><img border="0" src="${pageContext.request.contextPath}/images/remeber.jpg" width="75" height="20"></td>
<td>
<input type="checkbox" name="remeberMe" id="remeberMe" value="yes" ${requestScope.checked }/>
</td>
</tr>
(2)在Action中调用LogonUtils类
/**记住我*/
public static void rememberMe(HttpServletRequest request,
HttpServletResponse response, String name, String password) {
//创建2个Cookie
//解决中文名称不能放置到cookie中
try {
name = URLEncoder.encode(name, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Cookie nameCookie = new Cookie("name", name);
Cookie passwordCookie = new Cookie("password",password);
//设置Cookie存在的有效路径(绝对路径)
nameCookie.setPath(request.getContextPath()+"/");
passwordCookie.setPath(request.getContextPath()+"/");
//设置Cookie存在的有效时间(周期1周)
String remeberMe = request.getParameter("remeberMe");
//设置有效时间为一周
if(remeberMe!=null && remeberMe.equals("yes")){
nameCookie.setMaxAge(60*60*24*7);
passwordCookie.setMaxAge(60*60*24*7);
}
//取消有效时间
else{
nameCookie.setMaxAge(0);
passwordCookie.setMaxAge(0);
}
//存放cookie
response.addCookie(nameCookie);
response.addCookie(passwordCookie);
}
(3)添加过滤器SystemFilter,完成对Cookie的调用
public class SystemFilter implements Filter {
/**当服务启动的时候初始化*/
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**每次访问URL连接之前,都要访问的方法*/
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//记住我的代码放置到过滤器中
String path = request.getServletPath();
this.forwordIndexPage(request,path);
//放行
chain.doFilter(request, response);
}
/**销毁*/
public void destroy() {
}
//记住我的代码放置到过滤器中,在跳转到index.jsp页面之前
private void forwordIndexPage(HttpServletRequest request, String path) {
if(path.equals("/index.jsp")){
String name = "";
String password = "";
String checked = "";
Cookie [] cookies = request.getCookies();
if(cookies!=null && cookies.length>0){
for(Cookie cookie:cookies){
if(cookie.getName().equals("name")){
name = cookie.getValue();
//处理中文二进制解码问题
try {
name = URLDecoder.decode(name, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
checked = "checked";
}
if(cookie.getName().equals("password")){
password = cookie.getValue();
}
}
}
request.setAttribute("name", name);
request.setAttribute("password", password);
request.setAttribute("checked", checked);
}
}
}
(4)在页面上显示对应值
<input type="text" name="name" style="width: 125 px" size="20" value="${requestScope.name }" maxlength="25">
(5)注意事项:
项目学会使用编码和解码,这样可以处理中文乱码问题
name = URLEncoder.encode(name, "UTF-8");
name = URLDecoder.decode(name, "UTF-8");