javaweb过滤器filter-判断用户是否登录
1.首先在web.xml文件添加filter
<filter>
<filter-name>wxloginfilter</filter-name>
<filter-class>com.src.mian.filter.WXLoginFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>wxloginfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.添加class类继承Filter
public class WXLoginFilter implements Filter {
//标示符:表示当前用户未登录
String NO_LOGIN_NO = "NO_LOGIN_NO";
//排除url
//String[]此处的url路径需要登录后,才有权访问
String[] excludeUrls = new String[]{"gift/getgift","gift/userGiftList","gift/giftInfo","game/addComment"};//
public WXLoginFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**过滤器
* 判断url数组String[] excludeUrls中的url访问时是否已登录
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession();
String uri = request.getRequestURI();
//System.out.println("filter url:"+uri);
//System.out.println("sessionid:"+session.getId());
boolean pass = false;
if(excludeUrls != null){
for(String url : excludeUrls){
if (uri.indexOf(url)>-1){
pass = true;
break;
}
}
}
if (!pass) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
if(session.getAttribute("userKey_session") != null){
// System.out.println("userKey_session:"+session.getAttribute("userKey_session"));
filterChain.doFilter(request, response);
}else{
String requestType = request.getHeader("X-Requested-With");
//判断是否是ajax请求
if(requestType!=null && "XMLHttpRequest".equals(requestType)){
response.getWriter().write(this.NO_LOGIN_NO);
}else{
response.sendRedirect(request.getContextPath()+"/user/login");
}
return;
}
}
}
/**初始化
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}