filter过滤器的使用
在jsp开发中,我们经常使用过滤器(filter)来过滤权限,我做了一个简单的过滤器,代码如下:
(1)web.xml中加入:
<filter>
<filter-name>adminfilter</filter-name>
<filter-class>org.frank.filter.AdminFilter</filter-class>
<init-param>
<param-name>jspDirectAccess</param-name>
<param-value>login,/img/</param-value>
</init-param>
<init-param>
<param-name>forwardPage</param-name>
<param-value>/login.do</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>adminfilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
注意:jspDirectAccess,是定义不登录的时候允许访问的地址,比如登录页面、登录页面用到的图片等等,多个地址使用逗号分开。
forwardPage是定义跳转的页面。
<filter-mapping> 一般是声明在其他过滤器的前面,避免引起过滤器失效等其他异常。
(2)定义过滤器AdminFilter类:
package org.frank.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;
import javax.servlet.http.HttpSession;
import org.seasar.struts.util.RequestUtil;
public class AdminFilter implements Filter {
private String access = "login";
private String forward = "/login";
private static final String[] SESSIONS = {"userInfoSessionDto"};
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)arg0;
HttpServletResponse res = (HttpServletResponse) arg1;
HttpSession session = req.getSession(true);
String path = RequestUtil.getPath(req);
if(processDirectAccess(path)){
arg2.doFilter(arg0, arg1);
}else{
if(session==null || session.getAttribute(SESSIONS[0])==null || "".equals(session.getAttribute(SESSIONS[0]))){
req.getRequestDispatcher(forward).forward(arg0, arg1);
res.setHeader("Cache-Control","no-store");
res.setDateHeader("Expires",1000);
res.setHeader("Pragma","no-cache");
return;
}else{
arg2.doFilter(arg0, arg1);
}
}
}
public boolean processDirectAccess(String path){
if(path==null && "".equals(path)){
return false;
}
if(access!=null){
String[] accs = access.split(",");
for(String acc:accs){
if(path.lastIndexOf(acc + ".do") >=0 || path.lastIndexOf(acc) >=0){
return true;
}
}
}
return false;
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.access = arg0.getInitParameter("jspDirectAccess");
this.forward = arg0.getInitParameter("forwardPage");
}
}
(3)登录成功保存session
session.setAttribute("userInfoSessionDto", userInfoSessionDto);
注意:
session中存入的userInfoSessionDto要和AdminFilter类中的SESSIONS[0]的值对应。