使Struts2与Servlet并存解决办法
时间:2010-08-28 来源:季枫
解决办法:
在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(","))); } }
相关阅读 更多 +