javascript
Spring Web MVC 随笔
1.ContextLoaderListener
對于使用Spring的Web應用,無需手動創建Spring容器,而是通過配置文件聲明式地創建Spring容器。可以直接在web.xml文件中配置創建Spring容器。
Spring提供了一個ContextLoaderListener,該監聽器類實現了ServletContextListener接口,它會在創建時自動查找WEB-INF/下的applicationContext.xml文件。因此,如果只有一個配置文件,且文件名為applicationContext.xml,則只需在web.xml文件中增加如下配置片段即可。
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>如果有多個配置文件需要載入,則考慮使用<context-param…/>元素來確定配置文件的文件名。
ContextLoaderListener加載時會查找名為contextConfigLocation的初始化參數,如下:
<!--指定多個配置文件--> <context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring-context.xml,/WEB-INF/applicationContext.xml</param-value> </context-param> <!--使用ContextLoaderListener初始化Spring容器--> <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>如果沒有使用contextConfigLocation指定配置文件,則Spring會自動查找WEB-INF/下的applicationContext.xml文件。
如果有contextConfigLocation,則使用該參數確定的配置文件。
如果無法找到合適的配置文件,Spring將無法正常初始化。
2.可能遇到的異常
在配置Spring MVC時,可能會遇到這樣的錯誤:
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessioorg.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current threadnContext.java:134)那么在web.xml文件中添加如下配置即可:
<filter><filter-name>openSessionInViewFilter</filter-name><filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping><filter-name>openSessionInViewFilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping>OpenSessionInViewFilter的主要功能是用來把一個Hibernate Session和一次完整的請求過程對應的線程相綁定。
Open Session In View在request把session綁定到當前thread期間一直保持hibernate session在open狀態,使session在request的整個期間都可以使用。當View 層邏輯完成后,才會通過Filter的doFilter方法或Interceptor的postHandle方法自動關閉session。
轉載于:https://www.cnblogs.com/weilunhui/p/5230037.html
總結
以上是生活随笔為你收集整理的Spring Web MVC 随笔的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VC++更改程序图标
- 下一篇: gradle idea java ssm