使用Spring MVC写RESTFUL API

在Java的世界里,MVC设计模式已经深入到各个方面,如果你不会MVC都不好意思给别人打招呼。

MVC框架很多,如STRUTS, STRUTS2, WEB-WORK以及今天的主角SPRING MVC,SPRING MVC以前简单的配置以及和SPRING框架的良好结合使得SPRING MVC极为强大,而其RESTFUL API的设计更上让其它MVC框架难以望其项背,在RESTFUL API的使用中,需要有JACKSON库的支持,具体的可以到JACKSON的官网上去下载,记得请下载1.x的版本,SPRING MVC对2.x的版本还不支持。

第二需要在SPRING MVC的配置文件中做如下配置:

    <!-- 配置JSON支持 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="jsonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name = "supportedMediaTypes">
            <list>
                <bean class="org.springframework.http.MediaType">
                    <constructor-arg index="0" value="text"/>
                    <constructor-arg index="1" value="plain"/>
                    <constructor-arg index="2" value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.MediaType">
                    <constructor-arg index="0" value="*"/>
                    <constructor-arg index="1" value="*"/>
                    <constructor-arg index="2" value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.MediaType">
                    <constructor-arg index="0" value="text"/>
                    <constructor-arg index="1" value="*"/>
                    <constructor-arg index="2" value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.MediaType">
                    <constructor-arg index="0" value="application"/>
                    <constructor-arg index="1" value="json"/>
                    <constructor-arg index="2" value="UTF-8"/>
                </bean>
            </list>
        </property>
    </bean>

以上配置确保在返回JSON数据时不会出现中文乱码!

然后在Controller里如下写RESTFUL API,例如:

    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody
    Response add(Album album) {
        Response res = new Response();
        try {
            album.setCount(0);
            album.setPlayTimes(0);
            album.setCreateTime(new Date(System.currentTimeMillis()));
            albumSvc.add(album);
            res.setSuccess(true);
        } catch (Exception e) {
            res.setSuccess(false);
        }
        return res;
    }

如上面的代码,如果需要返回JSON数据,只需要在返回数据前加上@ResponseBody就可以了,另外在@RequestMapping里最好加上method字段,如method = RequestMethod.POST表示此方法只能通过Post方法调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值