标题:
如何让struts2和servlet的共存(3)
[打印本页]
作者:
look_w
时间:
2019-4-20 14:26
标题:
如何让struts2和servlet的共存(3)
方法4-写一个过滤器区分sturst2和servlet
自定义filter对servlet进行过滤:
##############################################
# 该类是定义了一个过滤器(随便你放在哪个包下面),当既用到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,注意是那url-pattern</param-value>
* </init-param>
* </filter>
* <filter-mapping>
* <filter-name>redisp</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
*该类也可以直接继承StrutsPrepareAndExecuteFilter的
###########################################################
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(",")));
}
}
怕大家还是配置错误,给一个web.xml的配置实例。
<filter>
<filter-name>redisp</filter-name>
<filter-class>
com.xheditor.servlet.ReDispatcherFilter</filter-class>
<init-param>
<param-name>includeServlets</param-name>
<param-value>UploadFileServlet</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>redisp</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 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>
<!-- servlet的配置 -->
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.servlets.ImageServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/myImageServlet/*</url-pattern>
</servlet-mapping>
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0