在struts2中使用filter来配置servlet处理业务。。。。
在一个struts2项目中,如果同时用到了servlet和struts2的框架,运行项目时可能无法正常使用servlet,原因是在配置struts2的核心控制器时如下配置所致
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
此时要想请求不经过该FilterDispatcher过滤器而直接响应servlet,可以通过自定义一个过滤器,将servlet过滤,使struts2的核心控制器对servlet不起作用。注意:在xml文件中定义的servlet过滤器要写在struts2核心控制器前面,否则还是不能使用。举例来说,定义的过滤器文件是ReDispatcherFilter.java,只需按照该文件中注释内容做以下配置,即可
<filter>
<filter-name>redisp</filter-name>
<filter-class>filters.ReDispatcherFilter</filter-class>
<init-param>
<param-name>includeServlets</param-name>
<param-value>attachmentUpload.do,aa.do</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>redisp</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>attachmentUpload</servlet-name>
<servlet-class>com.yan.AttachmentUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>attachmentUpload</servlet-name>
<url-pattern>/attachmentUpload.do</url-pattern>
</servlet-mapping>
在filters包下定义ReDispatcherFilter类,如下:
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
{
System.out.println(" filter beginning...........");
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);
for(int i=0;i<this.includes.size();i++)
System.out.println(this.includes.get(i));
if(this.includes.contains(target))
{
System.out.println("includes.contains(target) is true");
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(",")));
}
}