验证用户是否已经登录和自动登录
首先再来巩固一下cookie
a. cookie有4大属性:
1.Name,value – 声明时 new Cookie(key,value);
2.Path - 默认值,即为当前保存cookie的这个serlvet所在的路径。
如果Cookie在这样的路径:http://loclhost:8080/project/abc/AServlet
则Cookie的路径为: http://loclhost/project/abc
则说明:所在在http://loclhost/project/abc目录下的servlet才可以读取这个cookie的值。
如果: 保存Cookie类:http://loclhost:8080/project/a/b/AServlet
则Cookie的默认path为:http://loclhost/project/a/b
对于path这个值可以手工设置,如果设置为: http://loclhost/project/ 即到项目名。
则所有这个项目中的所有Serlvet|jsp都可以读取到这个 cookie.
Cookie.setPath(requst.getContextPath());
如果将path设置为 / 即:cookie.setpath(“/”); - http://localhost/
则所有在tomcat中运行的项目都可以读取这个到cookie.如果path设置为/必须要与domain共同使用才有意义。
3.Age - 默认值-1,在浏览器中存在。 0:删除文件中的cookie和浏览器中的cookie
4.Domain - 域 -
www.sina.com - login
www.bbs.sina.com 子域名
www.news.sina.com
b. 删除时cookie,必须要设置的与之前设置的信息完全一样:
- Name
- Age = 0(文件和缓存),-1(只删除文件)
- Path 一样。
- Domain :null
下一次用户再打开这个网页时,应该读取cookie中的信息,实现自动登录。
使用过滤器对请求过滤,不用像昨天那样用java代码对每个jsp页面都要进行用户是否登录判断
public class LoginFilter implements Filter{
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//将request强转成HttpServletRequest
HttpServletRequest req = (HttpServletRequest) request;
//获取session
HttpSession ss = req.getSession();
//从session中获取user
if(ss.getAttribute("user")==null){
System.err.println("你还没有登录");
req.getSession().setAttribute("msg", "请你先登录");
//重定向到登录
HttpServletResponse resp = (HttpServletResponse) response;
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}else{
//放行
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
自动登录,用到了标签库,jsp页面最好不要出现java代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
This is my JSP page. <br>
<c:choose>
<c:when test="${empty sessionScope.name}">
<form name="x" method="post" action="<c:url value='/LoginServlet'/>">
Name:<input type="text" name="name"/><br/>
auto:
<br/>
<input type="radio" name="auto" checked="checked" value="-1">不自动登录
<br/>
<input type="radio" name="auto" value="1">1天<br/>
<input type="radio" name="auto" value="7">1周<br/>
<input type="submit"/>
</form>
</c:when>
<c:otherwise>
你已经登录了:${name}<br/>
<a href="<c:url value='/LoginServlet'/>">退出</a>
</c:otherwise>
</c:choose>
</body>
</html>
保存cookie
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //超链接走的是get方式
System.err.println("用户退出");
//删除整个session
request.getSession().invalidate();
//删除cookie
Cookie c = new Cookie("autoLogin", "ddd");
c.setMaxAge(0);
c.setPath(request.getContextPath());
response.addCookie(c);
// request.getSession().removeAttribute("name");
request.getSession().setAttribute("exit",true);
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//接收用户姓名
String name = request.getParameter("name");
String auto = request.getParameter("auto");
//将用户信息放到session
request.getSession().setAttribute("name",name);
//判断auto是否是-1,默认不是自动登录
if(!auto.equals("-1")){
int day = Integer.parseInt(auto);//1天或7
int seconds = 60*60*24*day;
//声明cookie
name = URLEncoder.encode(name,"UTF-8");//对中文进行处理,cookie默认中文乱码
Cookie c = new Cookie("autoLogin",name);
c.setMaxAge(seconds);
c.setPath(request.getContextPath());
//保存cookie
response.addCookie(c);
}
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
}
过滤器进行拦截
public class AutoFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 在这儿读取cookie
HttpServletRequest req = (HttpServletRequest) request;
// 获取用户请求的uri
String uri = req.getRequestURI();// 就是/LoginServlet
if (req.getSession().getAttribute("exit") == null) {
if (req.getSession().getAttribute("name") == null) {
if (!uri.contains("/LoginServlet")) {
// 获取所的有cookie
Cookie[] cs = req.getCookies();
if (cs != null) {
for (Cookie c : cs) {
if (c.getName().equals("autoLogin")) {// 如果存在自动登录的cookie
String value = c.getValue();// 用户名称
value = URLDecoder.decode(value, "UTF-8");//中文解码
req.getSession().setAttribute("name", value);
break;
}
}
}
}
}
}else{
req.getSession().removeAttribute("exit");
}
chain.doFilter(request, response);
}
public void destroy() {
}
}
ps:最后web.xml中也可以对jsp文件进行映射
<servlet>
<servlet-name>c</servlet-name>
<jsp-file>/WEB-INF/secu/c.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>c</servlet-name>
<url-pattern>/cc.html</url-pattern>
</servlet-mapping>

浙公网安备 33010602011771号