JavaEE(Session与Filter)

Session (会话)

  • 访问这个用户的全部菜单都可以访问到 跨越了多个请求

  • request.setCharacterEncoding("utf-8");  // 数据库中接收到中文 这里处理乱码
// 1.创建会话
HttpSession session = request.getSession();
//2.将用户信息放到会话中
session.setAttribute("username", inputUsername);
  • 会话的保存机制

Filter(过滤器)

  • 上一个环节完成后,要交互到下一个环节。

 

//配置路径
@WebFilter("/*")
public class SecurityFilter implements Filter{
@Override
  public void doFilter(ServletRequest servletRequest ,ServletRespons servletRepone,FilterChain filterChain){
  HttpServletRequest request = (HttpServletRequest)ServletRequest;
  HttpServletResponse response = (HttpServletResponse)ServletResponse
  if(isLoginRequest(request) || LoginAlready(request) || isHomeRequest(request)){
  //放行
  filterChain.doFilter(ServletRequest,ServletResponse)
  }else{
  //重定向登录页
  response.sendRedirect(request.getContextPath()) //request.getContextPath() 拿到登录页
  }
}
 
//判断当前的请求是否是登录请求,登录请求的Servlet地址:/login,判断当前的请求uri是否是/login,如果是login就放行。
private boolean isLoginRequest(HttpServletRequest reqeust){
System.out.println(reqeust.getContextPath());
String uri = request.getRuquestURI(); //uri虚拟地址
if(uri.equals(request.getContextPath) + "/login"){
return turn;
}
return false;
}
//判读用户是否登录
private boolean LoginAlready(HttpServletRequest reqeust){
//得到session 因为登录成功后 我们在session里放了一个值
HttpSession session = request.getSession();
Object username = session.getAttribute("username");
}
if(username != null{
  return ture;
}
return flase;
}
// 判断当前请求是否是请求的项目首页,如果是项目首页,就放行
private boolean isHomeRequest(HttpServletRequest request){
  String contextPath = request.getContextPath();
  String uri = request.getRequestURI();
 
  contextPath = contextPath.replaceAll)("/","");
  uri = uri.replaceAll("/","");
  if(contextPath.equals(uri)){
  return true;
  }
  return flase;
}

 

上一篇:红帽解决mail追加filter问题


下一篇:nutch核心代码分析——crawl.link.db