gpt4 book ai didi

java - spring mvc 拦截器请求范围

转载 作者:行者123 更新时间:2023-12-01 06:12:50 26 4
gpt4 key购买 nike

我正在使用 Spring 4.1.7 和 Hibernate 4.3.10 开发一个 Web 应用程序。我需要创建一个拦截器来管理事务,如下所示:

public class ControllerInterceptor extends HandlerInterceptorAdapter
{

@Autowired
private SessionFactory sessionFactory;

private Session session;

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception
{
super.preHandle(request, response, handler);
ControllerInterceptor ci = this;
session = sessionFactory.getCurrentSession();
//Transaction management....
return true;
}

@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception
{
//Transaction commit/rollback
if (null != session && session.isOpen())
{
try
{
session.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}

}
}

在applicationContext.xml中,我以这种方式定义了拦截器:

<mvc:interceptors>
<bean class="com.interceptor.ControllerInterceptor" />
</mvc:interceptors>

我的 ControllerInterceptor 是单例的,但我在请求范围内需要它。我尝试以这种方式定义拦截器:

<mvc:interceptors>
<bean class="com.interceptor.ControllerInterceptor" scope="request" />
</mvc:interceptors>

但是我遇到了这个错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Initialization of bean failed; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

有什么建议吗?谢谢

最佳答案

MVC 拦截器不需要具有请求范围,因为它们仅针对当前请求执行。

引用HandlerInterceptor.preHandle的java文档-

Intercept the execution of a handler. Called after HandlerMapping determined an appropriate handler object, but before HandlerAdapter invokes the handler. DispatcherServlet processes a handler in an execution chain, consisting of any number of interceptors, with the handler itself at the end. With this method, each interceptor can decide to abort the execution chain, typically sending a HTTP error or writing a custom response.

Parameters:
request - current HTTP request
response - current HTTP response
handler - chosen handler to execute, for type and/or instance evaluation

此外,正如 Olesksii 正确指出的那样,您需要避免此处的 session /事务管理的反模式。

看看 @Transactional 。建议阅读 -> this , this & this

关于java - spring mvc 拦截器请求范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31648012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com