struts2自定义Filter
程序员文章站
2022-07-02 17:53:31
...
在struts2中自定义filter 防止用户通过手动输入网址进行相应操作
SessionFilter.java
SessionFilter.java
public class SessionFilter implements Filter { public FilterConfig config; public void destroy() { // TODO Auto-generated method stub this.config=null; } public static boolean isContains(String container, String[] regx) { boolean result = false; for (int i = 0; i < regx.length; i++) { if (container.indexOf(regx[i]) != -1) { return true; } } return result; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hrequest = (HttpServletRequest)request; HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response); String logonStrings = config.getInitParameter("logonStrings"); String includeStrings = config.getInitParameter("includeStrings"); String redirectPath = hrequest.getContextPath() + config.getInitParameter("redirectPath"); String disabletestfilter = config.getInitParameter("disabletestfilter"); if (disabletestfilter.toUpperCase().equals("Y")) { chain.doFilter(request, response); return; } String[] logonList = logonStrings.split(";"); String[] includeList = includeStrings.split(";"); if (!this.isContains(hrequest.getRequestURI(), includeList)) { chain.doFilter(request, response); return; } if (this.isContains(hrequest.getRequestURI(), logonList)) { chain.doFilter(request, response); return; } String user = ( String ) hrequest.getSession().getAttribute("name"); if (user == null) { wrapper.sendRedirect(redirectPath); return; }else { chain.doFilter(request, response); return; } } public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub config = filterConfig; } }在web.xml中的配置
<filter> <filter-name>SessionFilter</filter-name> <filter-class>filter.SessionFilter</filter-class> <init-param> <param-name>logonStrings</param-name><!-- 对登录页面不进行过滤 --> <param-value>/project/index.jsp;login.action</param-value> </init-param> <init-param> <param-name>includeStrings</param-name><!-- 只对指定过滤参数后缀进行过滤 --> <param-value>.action;.jsp</param-value> </init-param> <init-param> <param-name>redirectPath</param-name><!-- 未通过跳转到登录界面 --> <param-value>/</param-value> </init-param> <init-param> <param-name>disabletestfilter</param-name><!-- Y:过滤无效 --> <param-value>N</param-value> </init-param> </filter> <filter-mapping> <filter-name>SessionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>