struts2和servlet同时用(访问servlet时被struts2过滤器拦截问题的解决)
在同一个项目中间,如果既用到servlet有用了struts2的框架,运行项目时可能无法正常使用servlet,原因是在配置struts2的核心控制器时<url-pattern>/*</url-pattern>所致,需要定义一个过滤器,将servlet过滤,使struts2的核心控制器对servlet不起作用。注意:在xml文件中定义的servlet过滤器要写在struts2核心控制器前面,否则还是不能使用。举例来说,定义的过滤器文件是ReDispatcherFilter.java,只需按照该文件中注释内容做以下配置,即可。
package filters;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;public class ReDispatcherFilter implements Filter {public void destroy() { // TODO Auto-generated method stub}public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; String target = request.getRequestURI(); target = target.lastIndexOf("?")>0 ?target.substring(target.lastIndexOf("/")+1,target.lastIndexOf("?")-target.lastIndexOf("/")) :target.substring(target.lastIndexOf("/")+1); System.out.println(target); if(this.includes.contains(target)) { RequestDispatcher rdsp = request.getRequestDispatcher(target); System.out.println("go..............."+rdsp); rdsp.forward(req, resp); } else chain.doFilter(req, resp);}private ArrayList<String> includes = new ArrayList<String>();public void init(FilterConfig config) throws ServletException { this.includes.addAll( Arrays.asList(config.getInitParameter("includeServlets").split(",")));}}
/*该类是定义了一个过滤器,当既用到struts2有用到servlet时,* 必须用该过滤器对所有的servlet做一次过滤,否则servlet将无法正常运行。* 同时在web.xml中,在定义struts的核心控制器前面添加该过滤器,添加代码如下:*/ <filter> <filter-name>redisp</filter-name> <filter-class>filters.ReDispatcherFilter(该过滤器的类名)</filter-class> <init-param> <param-name>includeServlets</param-name> <param-value>所有配置的servlet名字</param-value> </init-param> </filter> <filter-mapping> <filter-name>redisp</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>