Spring MVC整理系列(02)————Spring MVC配置解析及整合Spring IOC

本文详细介绍了如何在Web.xml中配置SpringMVC,包括spring-mvc.xml的设置,如自定义异常处理和拦截器。同时,文章讲解了如何整合Spring IOC和SpringMVC,通过配置spring-context.xml实现主容器的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在Web.xml中配置SpringMVC

<!-- Spring主容器配置,加载ApplicationContext容器,如果整合mybatis,此文件包含mybaits配置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
</context-param>

<!-- Spring监听器 --> 
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--Spring MVC Servlet配置,加载WebApplicationContext容器 -->
<servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<!-- 编码过滤器 --> 
<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

2、spring-mvc.xml配置

<!-- 加载配置属性文件-->
<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />

<!-- 使用Annotation自动注册Bean,只扫描@Controller -->
<context:component-scan base-package="com.test.springmvc" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- HandlerMapping无需配置,Spring MVC默认自动注册DefaultAnnotationHandlerMapping的annotation-driven的HandlerMapping和AnnotationMethodHandlerAdapter --> 
<!-- 配置扩充注解驱动,将请求参数绑定到控制器参数上 -->
<mvc:annotation-driven />

<!-- REST中根据URL后缀自动判定Content-Type及相应的View -->
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="mediaTypes" >
    <map> 
    <entry key="xml" value="application/xml"/> 
    <entry key="json" value="application/json"/> 
    </map>
    </property>
<property name="ignoreAcceptHeader" value="false"/>
<property name="favorPathExtension" value="false"/>
</bean>


<!-- 对静态资源文件的访问,避免使用DefaultAnnoationHandlerMapping 和 AnnotationMethodHandlerAdapter处理mapping到Controller的path -->
<mvc:default-servlet-handler />

<!-- 静态资源映射 -->
<mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/>

<!-- 定义视图文件解析 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->  
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
    <!-- 默认编码 -->  
    <property name="defaultEncoding" value="utf-8" />    
    <!-- 文件大小最大值 -->  
    <property name="maxUploadSize" value="10485760000" />    
    <!-- 内存中的最大值 -->  
    <property name="maxInMemorySize" value="40960" />    
</bean>


<!-- 异常处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
    <!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->  
    <property name="defaultErrorView" value="error"></property>  
    <!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->  
    <property name="exceptionAttribute" value="ex"></property>  
    <!-- 定义需要特殊处理的异常,比如自定义异常,用类名或完全路径名作为key,异常页名作为值 -->  
    <property name="exceptionMappings">  
    <props>  
        <prop key="com.test.springmvc.Interceptor.MyException">/error/403</prop>  
    </props>  
    </property>  
</bean>  


<!-- 自定义拦截器interceptor setting -->
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/mvc/**"/>
    <mvc:exclude-mapping path="/static/**"/>
        <bean class="com.test.springmvc.Interceptor.MyInterceptor"></bean>
    </mvc:interceptor>        
</mvc:interceptors>

自定义的异常处理类:

public class MyException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    /** 错误Key,用于唯一标识错误类型 */
    private String errorCode = null;

    /**
     * 构造函数
     */
    public MyException() {
    }

    /**
     * 构造函数
     * @param errorCode 异常编码
     */
    public MyException(String errorCode) {
        this.errorCode = errorCode;
    }

    /**
     * 重载构造函数
     */
    public MyException(String errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
    }

    /**
     * 异常编码
     * @return String
     */
    public String getErrorCode() {
        return this.errorCode;
    }
}

自定义的拦截器:

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        System.out.println("afterCompletion");
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        System.out.println("preHandle");
        return true;
    }

}

3、整合SpringIOC和SpringMVC,配置spring主容器spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
    default-lazy-init="false">

    <!-- 加载配置属性文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />

    <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
    <context:component-scan base-package="com.mdf.sc,com.mdf.sentry"><!-- base-package 如果多个,用“,”分隔 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- MyBatis begin -->

    <!-- MyBatis end -->
</beans>

参照:http://www.admin10000.com/document/6436.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值