package com.spider.reader.common.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecurityFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//Session属于HTTP范畴,所以ServletRequest对象需要先转换成HttpServletRequest对象
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse res=(HttpServletResponse)response;
//取得请求的URL
String url = req.getRequestURL().toString();
if(url.indexOf("login.action")!=-1 || url.indexOf("loginOut.action")!=-1 ){
//过滤器放行ation
}else{
if(req.getSession() == null || req.getSession().getAttribute("loginname") == null){
res.sendRedirect(req.getContextPath()+"/login.action"); //跳回登录页
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
web.xml配置
<filter>
<filter-name>sercurity</filter-name>
<filter-class>
com.spider.reader.common.filter.SecurityFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>sercurity</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>