在基于CXF的webservice中访问HttpServletRequest的方法

基于CXF开发webservice,想在webservice实现类中获得HttpServletRequest对象,用了几种方式,用@Resources标签或者@Context标签都不行。@Context标签下对象为null,@Resource标签虽然注入了org.apache.cxf.jaxws.context.WebServiceContextImplWebServiceContext 对象,但是该对象内部值为null,什么也取不到。

后面用了个笨办法,在web.xml中增加一个filter

	<filter>
		<filter-name>ContextServlet</filter-name>
		<filter-class>xxx.filter.ContextServlet</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>ContextServlet</filter-name>
		<url-pattern>/services/*</url-pattern>
	</filter-mapping>

在filter中访问HttpServletRequest,将需要获得的值保存在ThreadLocal中

public static ThreadLocal<String> path = new ThreadLocal<String>();
	@Override
	public void destroy() {
		path.remove();		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)arg0; 		
		String path = request.getContextPath();
		basePath.set(path);
		arg2.doFilter(arg0, arg1);
	}

 

这样,在webservice的实现类中只要用 ContextServlet.path.get()就可以获得当前HttpServletRequest对中的变量。 

猜你喜欢

转载自javavsnet.iteye.com/blog/1963831
今日推荐