我有一个spring singleton bean
,我需要访问该bean中的请求对象。我尝试在单例bean中自动装配HttpServletRequest
:
@Autowired
private HttpServletRequest request;
...
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getRequest() {
return request;
}
但是我意识到它不会工作,因为该类充当单例bean(每个bean容器将创建一次Object)
然后我搜索了替代方案,并找到了代码snipet
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
应该有效,但没有成功。
还有其他方法可以解决这个问题吗?
答案 0 :(得分:0)
要访问HttpServeletRequest
中的Singleton Bean
对象:
首先编写一个如下所示的简单过滤器,然后在web.xml中进行配置 您可以将您选择的截取网址配置为/ *,这将过滤为所有网址模式。
创建一个类Context
public class Context {
private static ThreadLocal<Context> instance = new ThreadLocal<Context>();
private HttpServletRequest request;
private Context(HttpServletRequest request) {
this.request = request;
}
public static Context getCurrentInstance() {
return instance.get();
}
public static Context newInstance(HttpServletRequest request) {
Context context = new Context(request);
instance.set(context);
return context;
}
public void release() {
instance.remove();
}
public HttpServletRequest getRequest() {
return request;
}
}
创建过滤器“RequestAccessFilter.java”
public class RequestAccessFilter implements Filter {
@Override
public void destroy() {
// Nothing Needed
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
Context context = Context.newInstance((HttpServletRequest) request);
try {
chain.doFilter(request, response);
} finally {
context.release();
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// Nothing Needed
}
}
在“web.xml”中配置过滤器
<filter>
<filter-name>requestAccessFilter</filter-name>
<filter-class>com.myapp.web.filter.RequestAccessFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestAccessFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在您的Bean类中,您可以访问
HttpServletRequest request = Context.getCurrentInstance().getRequest();