[Java] 纯文本查看 复制代码
java
//1、如果session中存在user,直接放行
//2、如果不存在session,到cookie中获取用户名密码
//2.1如果有用户名密码,到数据库查询是否在
//2.1.1如果存在,存在session中,放行
//2.1.2如果不存在,放行。
//2.2如果用户名密码不存在,放行。
HttpServletRequest req = (HttpServletRequest)request;
User user = (User)req.getSession().getAttribute("user");
//1、如果session中存在user,直接放行
if(user!=null){
chain.doFilter(req, response);
}else{
//session中不存在。到cookie中去查找。ctrl+2 l
Cookie[] cookies = req.getCookies();
String userJson = "";
for (Cookie cookie : cookies) {
if("user".equals(cookie.getName())){
userJson = cookie.getValue();
}
}
//cookie中不存在用户信息
if("".equals(userJson)||userJson==null){
chain.doFilter(req, response);
}else{
//cookie中存在用户信息
user = JsonUtils.jsonToPojo(userJson, User.class);
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
String sql = "select * from user where username = ? and password =?";
try {
user = qr.query(sql, new BeanHandler<User>(User.class),user.getUsername(),user.getPassword());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user==null){
chain.doFilter(req, response);
}else{
req.getSession().setAttribute("user", user);
chain.doFilter(req, response);
}
}
}