关闭

黑马day14 过滤器之自动登录小案例

标签: 过滤器
602人阅读 评论(1) 收藏 举报
分类:

自动登录分析:

如果是第一次登陆就把user放到session域中,同时建立一个cookie把用户名和密码保存到cookie中,然后写一个过滤器,

如果是未登录的状态就把cookie中把用户名和密码拿出来和数据库中查询的作比较,如果一致就把user设置到session域中。

1.登陆页面login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
	<meta http-equiv=" pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <body>
    <h1>登录页面</h1><hr>
    <form action="${pageContext.request.contextPath }/servlet/LoginServlet" method="post">
    	用户名:<input type="text" name="name"/><br>
    	密码:<input type="password" name="password"/><br>
    	<input type="checkbox" name="autologin" value="true"/>30天内自动登录<br>
    	<input type="submit" value="提交"/>
    </form>
  </body>
</html>


2.loginServlet如果登陆成功就添加cookie

package cn.itheima.web;

import java.io.IOException
;
import java.sql.SQLException;
import java.util.HashMap;

import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.itheima.domain.User;

import com.itheima.util.DataSourceUtil;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//1.获取请求参数
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		//2.验证密码和数据库中的是否一致
		User user=null;
		try {
			QueryRunner runner=new QueryRunner(DataSourceUtil.getSource());
			String sql="select * from user where name=? and password=?";
			user=runner.query(sql, new BeanHandler<User>(User.class),name,password);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		//3.检验
		if(user==null){
			response.getWriter().write("用户名不存在!");
		}else{
			request.getSession().setAttribute("user", user);
			if("true".equals(request.getParameter("autologin"))){
				Cookie c=new Cookie("autologin", user.getName()+":"+user.getPassword());
				c.setMaxAge(60*60*12*30);
				c.setPath(request.getContextPath());
				response.addCookie(c);
			}
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
3.一个过滤器:完成了自动登录功能

package cn.itheima.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.itheima.domain.User;

import com.itheima.util.DataSourceUtil;

public class AutoLoginFilter implements Filter{

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse res=(HttpServletResponse) response;
		Cookie findC=null;
		//1.只有未登录的用户才可以自动登录
		if(req.getSession().getAttribute("user")==null||req.getSession(false)==null){
			//1.获取cookies遍历所有的cookie
			Cookie[] cs = req.getCookies();
			if(cs!=null){
				for(Cookie c:cs){
					if(c.getName().equals("autologin")){
						findC=c;
						break;//找到了就跳出循环
					}
				}
			}
			if(findC!=null){
				//判断cookie中的用户名和密码跟数据库的是否一致
				String cName = findC.getValue();
				String[] values = cName.split(":");
				String name=values[0];
				String password=values[1];
				//2.验证密码和数据库中的是否一致
				User user=null;
				try {
					QueryRunner runner=new QueryRunner(DataSourceUtil.getSource());
					String sql="select * from user where name=? and password=?";
					user=runner.query(sql, new BeanHandler<User>(User.class),name,password);
				} catch (SQLException e) {
					e.printStackTrace();
					throw new RuntimeException();
				}
				req.getSession().setAttribute("user", user);
			}
		}
		chain.doFilter(req, res);
		
	}

	public void destroy() {
		
	}

}
4.注销功能:不仅要杀死session还要把cookie清除否则注销不成功。

package cn.itheima.web;

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;

public class LogoutServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if(request.getSession(false)!=null){
			request.getSession().invalidate();
		}
		//删除cookie
		Cookie c=new Cookie("autologin","");
		c.setMaxAge(0);
		c.setPath(request.getContextPath());
		response.addCookie(c);
		//重定向到主页
		response.sendRedirect(request.getContextPath()+"/index.jsp");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:180858次
    • 积分:4202
    • 等级:
    • 排名:第8046名
    • 原创:242篇
    • 转载:4篇
    • 译文:0篇
    • 评论:36条
    友情链接