编程语言
首页 > 编程语言> > JavaEE(Session与Filter)

JavaEE(Session与Filter)

作者:互联网

Session (会话)

// 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;
}

 

标签:session,HttpServletRequest,return,getContextPath,JavaEE,request,uri,Filter,Sessi
来源: https://www.cnblogs.com/cqhec/p/15617096.html