首页 > 代码库 > springmvc笔记

springmvc笔记

搭建环境

1.配置前段控制器wen.xml

 

  <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

 

2.配置springmvc.xml

 

2.1配置注解扫描包(注解方式)

 

<context:component-scan base-package="com.fyh.www.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

 

这里配置com.fyh.www.controller包下只扫描@Controller注解

spring.xml的配置方式一包如下,不扫描@Controller注解

<context:component-scan base-package="com.fyh.www" >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

 

2.2配置处理器映射器和处理器适配器

 

<mvc:annotation-driven />

如果配置转换器,这里要注册转换器(可选)

    <mvc:annotation-driven conversion-service="conversionService"/>

<!-- 设置Converter转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <!-- 设置多个转换器 --> <property name="converters"> <list> <bean class="com.fyh.www.common.mvcConverter.CustomTrimConverter"></bean><!-- 去除前后空格 --> </list> </property> </bean>

去除前后空格转换器代码实现如下

package com.fyh.www.common.mvcConverter;

import org.springframework.core.convert.converter.Converter;

public class CustomTrimConverter implements Converter<String, String> {
    
    
    //转换过程 
    public String convert(String source) {
        // TODO Auto-generated method stub
        try {
            if(null != source){
                source = source.trim();  // ""
                if(!"".equals(source)){
                    return source;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

}

 

2.3配置视图解析器

 

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="prefix" value="/WEB-INF/jsp/" />
   <property name="suffix" value=".jsp" />
</bean>

 

2.4配置上传(可选)

 

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="1048576"/>
</bean>

 

 

2.5配置拦截器(可选)

 

<!-- Springmvc拦截器     -->
        <mvc:interceptors>
            <!-- 配置多个 -->
            <mvc:interceptor>
                <mvc:mapping path="/*/**"/>
                <bean class="com.fyh.www.common.interceptor.MvcInterceptor"></bean>
            </mvc:interceptor>
        </mvc:interceptors>

 

springmvc笔记