簡體   English   中英

Spring MVC攔截器請求范圍

[英]spring mvc interceptor request scope

我正在用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文檔-

攔截處理程序的執行。 在HandlerMapping確定適當的處理程序對象之后但在HandlerAdapter調用handler之前調用 DispatcherServlet處理執行鏈中的處理程序,該處理程序由任意數量的攔截器組成,處理程序本身位於末尾。 使用此方法,每個攔截器可以決定中止執行鏈,通常是發送HTTP錯誤或編寫自定義響應。

參數:
request- 當前的 HTTP請求
響應- 當前的 HTTP響應
handler-選擇執行的處理程序,用於類型和/或實例評估

此外,正如Olesksii正確指出的那樣,您需要在此避免會話/事務管理的反模式。

而是看看@Transactional 建議閱讀-> thisthisthis

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM