使用Spring MVC写RESTFUL API

来源:互联网 发布:高松好玩吗 知乎 编辑:程序博客网 时间:2024/06/05 07:52

在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方法调用。

0 0
原创粉丝点击