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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值