过滤器自动登录

01-数据库
create database day_autologin;
use day_autologin;
create table user(
id int primary key auto_increment,
username varchar(20),
password varchar(20)
);
insert into user values(null,‘tom’,‘123’);

02-JavaBean: User.java

package com.hngy.domain;

import java.io.Serializable;

public class User implements Serializable {
private static final long serialVersionUID = 1L;

private int id;
private String username;
private String password;

// setter和getter方法...

}

03-工具类:DataSourceUtils.java

package com.hngy.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
private static ComboPooledDataSource ds=new ComboPooledDataSource();
private static ThreadLocal tl=new ThreadLocal<>();

/**
 * 获取数据源
 * @return 连接池
 */
public static DataSource getDataSource(){
	return ds;
}

/**
 * 从当前线程上获取连接
 * @return 连接
 * @throws SQLException
 */
public static Connection getConnection() throws SQLException{
	Connection conn = tl.get();
	if(conn==null){
		//第一次获取 创建一个连接 和当前的线程绑定
		 conn=ds.getConnection();
		 
		 //绑定
		 tl.set(conn);
	}
	return conn;
}

/**
 * 释放资源
 * 
 * @param conn
 *            连接
 * @param st
 *            语句执行者
 * @param rs
 *            结果集
 */
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
	closeResource(st, rs);
	closeConn(conn);
}
 
public static void closeResource(Statement st, ResultSet rs) {
		closeResultSet(rs);
		closeStatement(st);
}

/**
 * 释放连接
 * 
 * @param conn
 *            连接
 */
public static void closeConn(Connection conn) {
	if (conn != null) {
		try {
			conn.close();
			//和当前的线程解绑
			tl.remove();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		conn = null;
	}

}

/**
 * 释放语句执行者
 * 
 * @param st
 *            语句执行者
 */
public static void closeStatement(Statement st) {
	if (st != null) {
		try {
			st.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		st = null;
	}

}

/**
 * 释放结果集
 * 
 * @param rs
 *            结果集
 */
public static void closeResultSet(ResultSet rs) {
	if (rs != null) {
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		rs = null;
	}

}

/**
 * 开启事务
 * @throws SQLException
 */
public static void startTransaction() throws SQLException{
	//获取连接//开启事务
	getConnection().setAutoCommit(false);;
}

/**
 * 事务提交
 */
public static void commitAndClose(){
	try {
		//获取连接
		Connection conn = getConnection();
		//提交事务
		conn.commit();
		//释放资源
		conn.close();
		//解除绑定
		tl.remove();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}

/**
 * 事务回滚
 */
public static void rollbackAndClose(){
	try {
		//获取连接
		Connection conn = getConnection();
		//事务回滚
		conn.rollback();
		//释放资源
		conn.close();
		//解除绑定
		tl.remove();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}

}

04-工具类:CookieUtils.java

package com.hngy.utils;

import javax.servlet.http.Cookie;

public class CookieUtils {
/**
* 通过名称在cookie数组获取指定的cookie
* @param name cookie名称
* @param cookies cookie数组
* @return
*/
public static Cookie getCookieByName(String name, Cookie[] cookies) {
if(cookies!=null){
for (Cookie c : cookies) {
//通过名称获取
if(name.equals(c.getName())){
//返回
return c;
}
}
}
return null;
}
}

05-编写C3P0配置文件:c3p0-config.xml

com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1:3306/day_autologin root root
	<!--扩展配置-->
	<property name="checkoutTimeout">30000</property>
	<property name="idleConnectionTestPeriod">30</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> 


<!-- 命名的配置 -->
<named-config name="itcast">
	<property name="driverClass">com.mysql.jdbc.Driver</property>
	<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property>
	<property name="user">root</property>
	<property name="password">1234</property>
	
	
	<!-- 如果池中数据连接不够时一次增长多少个 -->
	<property name="acquireIncrement">5</property>
	<property name="initialPoolSize">20</property>
	<property name="minPoolSize">10</property>
	<property name="maxPoolSize">40</property>
	<property name="maxStatements">20</property>
	<property name="maxStatementsPerConnection">5</property>
</named-config>

06-常量类:Constant.java

package com.hngy.constant;

public interface Constant {

// 勾选了自动登录
String IS_AUTO_LOGIN = "ok";

}

07-编写登录页:login.jsp

<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>

用户名:
密码:
记住用户名:

08-编写LoginServlet.java

package com.hngy.web.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hngy.constant.Constant;
import com.hngy.domain.User;
import com.hngy.service.UserService;
import com.hngy.service.impl.UserServiceImpl;

/**

  • 用户登录
    */
    @WebServlet("/login")
    public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding(“utf-8”);
    response.setContentType(“text/html;charset=utf-8”);

     // 01-接收数据
     String username = request.getParameter("username");
     String password = request.getParameter("password");
     
     // 02-调用service完成操作
     UserService service = new UserServiceImpl();
     User user = null;
     try {
     	user = service.login(username, password);
     } catch (SQLException e) {
     	e.printStackTrace();
     }
     
     // 03-判断数据是否为空
     if (user == null) {
     	request.setAttribute("msg", "用户名与密码不匹配!");
     	request.getRequestDispatcher("/login.jsp").forward(request, response);
     	return;
     } else {
     	// 不为空, 把user放入session中
     	request.getSession().setAttribute("user", user);
     	
     	// 判断是否勾选了自动登录
     	if (Constant.IS_AUTO_LOGIN.equals(request.getParameter("auto_login"))) {
     		// 勾选了,使用cookie,把信息写回浏览器
     		Cookie cookie = new Cookie("autologin", username+"-"+password);
     		cookie.setMaxAge(3600);
     		cookie.setPath(request.getContextPath()+"/");
     		response.addCookie(cookie);
     	}
     
     	// 04-页面重定向
     	response.sendRedirect(request.getContextPath()+"/success.jsp");
     }
    

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding(“utf-8”);
    response.setContentType(“text/html;charset=utf-8”);
    doGet(request, response);
    }

}

09-编写UserService.java

package com.hngy.service;

import java.sql.SQLException;

import com.hngy.domain.User;

public interface UserService {

User login(String username, String password) throws SQLException;

}

10-编写UserServiceImpl.java

package com.hngy.service.impl;

import java.sql.SQLException;

import com.hngy.dao.UserDao;
import com.hngy.dao.impl.UserDaoImpl;
import com.hngy.domain.User;
import com.hngy.service.UserService;

public class UserServiceImpl implements UserService {

@Override
public User login(String username, String password) throws SQLException {
	UserDao dao = new UserDaoImpl();
	return dao.login(username, password);
}

}

11-编写UserDao.java

package com.hngy.dao;

import java.sql.SQLException;

import com.hngy.domain.User;

public interface UserDao {

User login(String username, String password) throws SQLException;

}

12-编写UserDaoImpl.java

package com.hngy.dao.impl;

import java.sql.SQLException;

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

import com.hngy.dao.UserDao;
import com.hngy.domain.User;
import com.hngy.utils.DataSourceUtils;

public class UserDaoImpl implements UserDao {

/**
 * 用户登录
 */
@Override
public User login(String username, String password) throws SQLException {
	QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
	String sql = "select * from user where username=? and password=? limit 1";
	Object[] params = {username,password};
	return qr.query(sql, new BeanHandler<>(User.class), params);
}

}

13-编写success.jsp

<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>

${user.username }, 欢迎登录

14-编写AutoLoginFilter.java

package com.hngy.web.filter;

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

import javax.servlet.Filter;
import javax.servlet.FilterChain;
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 com.hngy.domain.User;
import com.hngy.service.UserService;
import com.hngy.service.impl.UserServiceImpl;
import com.hngy.utils.CookieUtils;

/**

  • 自动登录的过滤器

  •  自动登录只需要登录一次:当session中没有用户的时候
    
  •  访问有些资源是不需要自动登录的(和登录还有注册相关的资源)
    
  • @author Administrator

  • @date 2017年12月16日

  • @version v1.0
    */
    public class AutoLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
    throws IOException, ServletException {
    // 00.强转
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

     // 01-获取指定的session
     User user = (User) request.getSession().getAttribute("user");
     
     // 02-判断session中是否有用户
     if (user == null) {
     	// 03-session中,没有用户,需要用户自动登录
     	
     	// 04-判断访问的资源是否与注册登录相关
     	String path = request.getRequestURI();
     	if (!path.contains("/login")) {
     		// 05-不相关, 自动登录 
     		
     		// 获取指定的cookie
     		Cookie c = CookieUtils.getCookieByName("autologin", request.getCookies());
     		
     		// 判断cookie是否为空
     		if (c != null) {
     			// cookie不为空,则获取里面的值(username, password)
     			String username = c.getValue().split("-")[0];
     			String password = c.getValue().split("-")[1];
     			
     			//调用service, 完成登录操作
     			UserService service = new UserServiceImpl();
     			// user = null;
     			try {
     				user = service.login(username, password);
     			} catch (SQLException e) {
     				e.printStackTrace();
     			}
     			
     			// 判断user是否为空
     			if (user != null) {
     				// 把user放入session中
     				request.getSession().setAttribute("user", user);
     			}
     		}
     	}
     	
     }
     
     // 放行
     chain.doFilter(request, response);
    

    }

}

15-注册Filter

<?xml version="1.0" encoding="UTF-8"?> day20-filter index.html index.htm login.jsp default.html default.htm default.jsp AutoLoginFilter com.hngy.web.filter.AutoLoginFilter AutoLoginFilter /*
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值