posts - 1166, comments - 124, trackbacks - 0, articles - 2
  首页  :: 新随笔  :: 管理

使Struts2与Servlet并存解决办法 Filter转发Servlet

Posted on 2010-08-28 10:55 季枫 阅读(...) 评论(...) 编辑 收藏

解决办法:

在Struts2过滤器前增加一个过滤器,使用过滤器转发到servlet上

 

web.xml配置:

 <filter>
<filter-name>JSONRPCServlet</filter-name>
<filter-class>filters.ReDispatcherFilter</filter-class>
<init-param>
<param-name>includeServlets</param-name>
<param-value>JRPC</param-value>
<!--注:JRPC为下文配置的Servlet JSONRPCServlet过滤的请求配置 -->
</init-param>
</filter>
<filter-mapping>
<filter-name>JSONRPCServlet</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--注:这里同样需要Servlet配置,Filter会转到该Servlet上-->
<servlet>
<servlet-name>JSONRPCServlet</servlet-name>
<servlet-class>
jcore.jsonrpc.servlet.JSONRPCServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JSONRPCServlet</servlet-name>
<url-pattern>/JRPC</url-pattern>
</servlet-mapping>

 

 

过滤器的实现类:

 

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(",")));
}
}

 

Powered by .NET Core 3.0 Preview 8 on Linux

智读 | 成都会领科技有限公司官网 | 智读App下载 | 每天听本书的博客 | |