Spring MVC根据请求后缀返回不同数据格式

来源:互联网 发布:网络搏彩 编辑:程序博客网 时间:2024/06/10 03:49
Spring MVC通过ContentNegotiatingViewResolver实现了根据不同请求后缀返回不同的数据格式,本文以velocity视图解析器为例。配置信息如下:(具体配置说明直接在配置文件注释中体现)
    <!-- 自动扫描@Controller注入为bean -->    <context:component-scan base-package="com.demo.controller"/>    <!-- 模板信息设置 -->    <bean id="velocityConfigurer"  class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">        <property name="resourceLoaderPath" value="/WEB-INF/views/" /> <!-- 配置模板路径 -->        <property name="velocityProperties">            <props>                <prop key="input.encoding">UTF-8</prop><!-- 指定模板引擎进行模板处理的编码 -->                <prop key="output.encoding">UTF-8</prop><!-- 指定输出流的编码 -->            </props>        </property>    </bean>    <!-- 设置视图解析器 -->    <!-- 这里配置的是velocity视图解析器,其他解析器配置都类似,这里不做过多补充 -->    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">        <property name="viewClass" value="org.springframework.web.servlet.view.velocity.VelocityView" />        <property name="contentType" value="text/html;charset=UTF-8" />        <property name="dateToolAttribute" value="dateTool" />        <property name="numberToolAttribute" value="numberTool" />        <property name="exposeRequestAttributes" value="true" />        <property name="exposeSessionAttributes" value="true" />    </bean>    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">       <!-- 配置请求类型 -->        <property name="mediaTypes">            <value>                html=text/html                json=application/json            </value>        </property>        <property name="defaultContentType" value="text/html"/>    </bean>    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">        <property name="order" value="0"/>        <property name="contentNegotiationManager" ref="contentNegotiationManager"/>        <!-- 解析器配置直接引用上面配置好的解析器ID -->        <property name="viewResolvers" ref="viewResolver" />        <!-- 提供fastJson 视图 -->        <property name="defaultViews">            <list>                <bean class="com.alibaba.fastjson.support.spring.FastJsonJsonView">                    <property name="charset" value="UTF-8"/>                </bean>            </list>        </property>    </bean>    <!-- 添加注解驱动 -->    <mvc:annotation-driven  content-negotiation-manager="contentNegotiationManager"/>    <!-- 设置转换器 -->    <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>
以上即为解析器的核心配置,关于SpringMVC的其他配置不在本文讨论范畴,暂不做详细说明。通过如上配置,我们就可以在控制器中对同意个RequestMapping进行不同数据格式返回的定义,具体代码如下:
    @RequestMapping({"/test.html","/test.json"})    public String test(Model model){        model.addAttribute("test","测试数据");        return "index";    }

通过在RequestMapping中定义不同的请求路径就能够实现不同数据返回。

0 0
原创粉丝点击