struts2过滤器拦截servlet处理问题
问题:
报表服务器部和客户应用做集成时,客户的应用中通常会用到struts2,并且由于安全上的考虑会加上自带的过滤器,拦截执行的servlet,如下:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这样对导致润乾的reportServlet在访问时会被拦截,打印、导出或做参数表单查询时出现异常。
解决方案:
同样可以定义过滤器,然后在过滤器中增加配置,允许配置的servlet执行。
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() {
}
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);
if (this.includes.contains(target)) {
RequestDispatcher rdsp = request.getRequestDispatcher(target);
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(“,”)));
}
}
将该java程序编译后放到类路径下,并且要在web.xml中增加配置:
<filter>
<filter-name>redisp</filter-name>
<filter-class>filters.ReDispatcherFilter</filter-class>
<init-param>
<param-name>includeServlets</param-name>
<param-value>reportServlet </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>redisp</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
其中 includeServlets 对应的值为允许执行的servlet,将润乾的reportServlet在这里边配置即可,如果要允许多个servlet,此处用逗号隔开即可