Filter实现自动登录的Demo

Filter实现自动登录的Demo

1.需求:

第一次登陆时:获取登录信息,校验失败就停留在登录界面;校验成功,跳转到index.jsp,然后存储账号密码到cookie,发送cookie给客户端,使用session储存用户信息。

第二次登陆时:获取cookie,如果没有cookie表明没有登录,放行;有cookie,找出曾经存放的用户名和密码,如果能找到就执行登录的操作,然后使用session存起来这个用户,并放行。

2.搭建数据库

创建一个名为t_user的表:

3.所需jar包

4.搭建页面

  • login.jsp
<body>
  <form method="post" action="LoginServlet">
	账号:<input type="text" name="username"><br>
	密码:<input type="password" name="password"><br>
		<input type="checkbox" name="auto_login"> 自动登录<br>
		<input type="submit" value="登录">
  </form>
</body>
  • index.jsp
<body>
	这是首页 , 
	<c:if test="${not empty  userBean}">
		欢迎您, ${userBean.username }!
	</c:if>
	
	<c:if test="${ empty  userBean}">
		您好,请登录!
	</c:if>\
</body>

5.pojo类

public class UserBean {

	private int id ; 
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

6.Dao层

  • 接口:
public interface UserDao {

	/**
	 * 执行登录,并且返回该用户的所有信息
	 * @param user 执行登录的用户信息
	 * @return 
	 */
	UserBean login(UserBean user) throws SQLException;
}
  • 实现类:
public class UserDaoImpl implements UserDao {

	@Override
	public UserBean login(UserBean user) throws SQLException {
		
		QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
		String sql = "select * from t_user where username = ? and password = ?";
		UserBean query = runner.query(sql, new BeanHandler<UserBean>(UserBean.class) , user.getUsername() , user.getPassword());
		return query;
	}

}

7.c3p0连接数据库配置

  • JDBCUtil:
public class JDBCUtil02 {
	
	static ComboPooledDataSource dataSource = null;
	static{
		dataSource = new ComboPooledDataSource();
	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	/**
	 * 获取连接对象
	 * @return
	 * @throws SQLException 
	 */
	public static Connection getConn() throws SQLException{
		return dataSource.getConnection();
	}
	
	/**
	 * 释放资源
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void release(Connection conn , Statement st , ResultSet rs){
		closeRs(rs);
		closeSt(st);
		closeConn(conn);
	}
	public static void release(Connection conn , Statement st){
		closeSt(st);
		closeConn(conn);
	}

	
	private static void closeRs(ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			rs = null;
		}
	}
	
	private static void closeSt(Statement st){
		try {
			if(st != null){
				st.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			st = null;
		}
	}
	
	private static void closeConn(Connection conn){
		try {
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			conn = null;
		}
	}
}
  • c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

	<!-- default-config 默认的配置,  -->
  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost/user</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
    <property name="maxStatements">200</property>
  </default-config>
  
   <!-- This app is massive! -->
  <named-config name="oracle"> 
    <property name="acquireIncrement">50</property>
    <property name="initialPoolSize">100</property>
    <property name="minPoolSize">50</property>
    <property name="maxPoolSize">1000</property>

    <!-- intergalactoApp adopts a different approach to configuring statement caching -->
    <property name="maxStatements">0</property> 
    <property name="maxStatementsPerConnection">5</property>

    <!-- he's important, but there's only one of him -->
    <user-overrides user="master-of-the-universe"> 
      <property name="acquireIncrement">1</property>
      <property name="initialPoolSize">1</property>
      <property name="minPoolSize">1</property>
      <property name="maxPoolSize">5</property>
      <property name="maxStatementsPerConnection">50</property>
    </user-overrides>
  </named-config>

 
</c3p0-config>

8.登录servlet

public class LoginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			String userName = request.getParameter("username");
			String password = request.getParameter("password");
			String autoLogin = request.getParameter("auto_login");
			UserBean user = new UserBean();
			user.setUsername(userName);
			user.setPassword(password);
			
			UserDao dao = new UserDaoImpl();
			UserBean userBean = dao.login(user);
			
			if(userBean != null){
				
				//判断页面提交上来的时候,是否选择了自动登录
				if("on".equals(autoLogin)){
					
					//发送cookie给客户端
					
					Cookie cookie = new Cookie("auto_login", userName+"||"+password);
					cookie.setMaxAge(60*60*24*7);//7天有效期
					cookie.setPath("/AutoLoginDemo");
					response.addCookie(cookie);
					
				}
				
				
				//登录成功,进入首页
				request.getSession().setAttribute("userBean", userBean);
				response.sendRedirect("index.jsp");
			}else{
				//登录不成功,停留在登录界面
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

9.过滤器代码

  • 思路:
  1. 先判断session是否有效, 如果有效,就不用取cookie了,直接放行。

  2. 如果session失效了,那么就取 cookie。

    1. 没有cookie 放行

    2. 有cookie

      1. 取出来cookie的值,然后完成登录

        1. 把这个用户的值存储到session中

        2. 放行。

  • 代码:
public class AutoLoginFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	    try {
	        HttpServletRequest request = (HttpServletRequest) req;
			
	            //先判断,现在session中还有没有那个userBean.
                UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
		    //还有,有效。
		if(userBean != null){
				chain.doFilter(request, response);
		}else{
			//代表session失效了。
				
			//2. 看cookie。
				
			//1. 来请求的时候,先从请求里面取出cookie , 但是cookie有很多的key-value
			Cookie[] cookies = request.getCookies();
			//2. 从一堆的cookie里面找出我们以前给浏览器发的那个cookie
			Cookie cookie = CookieUtil.findCookie(cookies, "auto_login");
				
			//第一次来
			if(cookie  == null){
				chain.doFilter(request, response);
			}else{
				
				//不是第一次。
				
				String value = cookie.getValue();
				String username = value.split("||")[0];
				String password = value.split("||")[1];
				//完成登录
				UserBean user = new UserBean();
				user.setUsername(username);
				user.setPassword(password);

				UserDao dao = new UserDaoImpl();
				userBean = dao.login(user);
					
				//使用session存这个值到域中,方便下一次未过期前还可以用。
				request.getSession().setAttribute("userBean", userBean);
					
				chain.doFilter(request, response);
			}
	          	}
		} catch (Exception e) {
			e.printStackTrace();
			chain.doFilter(req, response);
		}
	}


	public void init(FilterConfig fConfig) throws ServletException {
	}

}

10.cookie util

public class CookieUtil {

	public static Cookie findCookie(Cookie [] cookies , String name){
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if(name.equals(cookie.getName())){
					return cookie;
				}
			}
		}
		return null;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值