Spring MVC一个方法适用多种调用方式

  • web.xml

Spring MVC一个方法适用多种调用方式_第1张图片

 

  • spring-mvc.xml
<mvc:annotation-driven />
    <context:component-scan base-package="com.cnfwsy" />
    <context:annotation-config />
    <!-- 避免IE在ajax请求时,返回json出现下载 <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
        <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> 
        </list> </property> </bean> -->

    <!-- 对模型视图添加前后缀 -->
    <bean id="viewResolver"    class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/jsp/" p:suffix=".jsp" />

    <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="favorParameter" value="false" />
        <property name="ignoreAcceptHeader" value="true" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/jsp/" />
                    <property name="suffix" value=".jsp" />
                </bean>
            </list>
        </property>
        <!-- 默认使用MappingJacksonJsonView生成jsonview -->
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
                    <property name="extractValueFromSingleKeyModel" value="true" />
                </bean>
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <property name="marshaller">
                        <bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
                    </property>
                </bean>
            </list>
        </property>

    </bean>

 

  • 效果

1、这是后台的app和web公用方法:

Spring MVC一个方法适用多种调用方式_第2张图片

 

 2,这是前台ajax请求: 
 
Spring MVC一个方法适用多种调用方式_第3张图片
 
3,这是前台的普通请求:

Spring MVC一个方法适用多种调用方式_第4张图片

 

 

你可能感兴趣的:(spring,mvc)