因为spring是依赖jackson来生成json,需要添加jar包。

pom.xml文件添加依赖。

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>

web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="2.2">
<display-name>mybatis</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-application.xml</param-value>
</context-param>
<filter>
<description>字符集过滤器</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description>字符集编码</description>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- spring mvc servlet -->
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>spring mvc 配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置session超时时间,单位分钟 -->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

其中是注意设置spring mvc servlet中拦截请求路径。

spring-application.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
"> <!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config.properties" /> <!-- 自动扫描(自动注入) -->
<context:component-scan base-package="sy.service" /> <import resource="spring-mybatis.xml"/>
<!-- <import resource="spring-redis.xml"/> -->
<!-- <import resource="spring-memcached.xml"/>
<import resource="spring-mongodb.xml"/>
<import resource="spring-security.xml"/> -->
</beans>

spring-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="sy.controller" /> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的互相转换映射 输出对象转JSON的支持 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean> </beans>

这个文件中对restful的支持主要是HttpMessageConverter的配置。

HttpMessageConverter接口,需要开启<mvc:annotation-driven  />。

测试Controller编写

pojo类

package sy.model;

import java.util.Date;

public class Myuser {
private Integer id; private String name; private String sex; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
} @Override
public String toString() {
return "Myuser [id=" + id + ", name=" + name + ", sex=" + sex
+ ", province=" + province + ", createdate=" + createdate
+ ", updatedate=" + updatedate + "]";
} }

Controller类

package sy.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import sy.model.Myuser; @Controller
public class RestfulController { @RequestMapping(value="/hello",produces = "text/plain;charset=UTF-8")
public @ResponseBody
String hello1(){
return "index";
} @RequestMapping(value="/hello")
String hello2(){
return "index";
} @RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
public @ResponseBody
String say(@PathVariable(value = "msg") String msg) {
return "{\"msg\":\"you say:'" + msg + "'\"}";
}
@RequestMapping(value = "/user/{id:\\d+}", method = RequestMethod.GET)
public @ResponseBody
Myuser getuser(@PathVariable("id") int id) throws UnsupportedEncodingException {
Myuser myuser = new Myuser(); myuser.setName("张三");
myuser.setSex("男");
myuser.setId(id);
return myuser;
} @RequestMapping(value = "/user/{id:\\d+}", method = RequestMethod.DELETE)
public @ResponseBody
Object deleteuser(@PathVariable("id") int id) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "删除人员信息成功");
return jsonObject;
} @RequestMapping(value = "/user", method = RequestMethod.POST)
public @ResponseBody
Object adduser(Myuser user) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "注册人员信息成功");
return jsonObject;
} @RequestMapping(value = "/user", method = RequestMethod.PUT)
public @ResponseBody
Object updateuser(Myuser user) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "更新人员信息成功");
return jsonObject;
} @RequestMapping(value = "/user", method = RequestMethod.PATCH)
public @ResponseBody
List<Myuser> listuser(@RequestParam(value = "name", required = false, defaultValue = "") String name) { List<Myuser> lstusers = new ArrayList<Myuser>(); Myuser myuser = new Myuser();
myuser.setName("张三");
myuser.setSex("男");
myuser.setId(101);
lstusers.add(myuser); Myuser myuser2 = new Myuser();
myuser2.setName("李四");
myuser2.setSex("女");
myuser2.setId(102);
lstusers.add(myuser2); Myuser myuser3 = new Myuser();
myuser3.setName("王五");
myuser3.setSex("男");
myuser3.setId(103);
lstusers.add(myuser3); return lstusers;
} }

restful的实现主要是依赖@ResponseBody、@RequestBody注解和HttpMessageConverter来实现pojo对象和对应协议的转换。

Spring 3.X系列增加了新注解@ResponseBody,@RequestBody

  • @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
  • @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并通过Adapter调用合适的HttpMessageConverter来转换对象,写入HttpResponse输出流,返回给浏览器。

HttpMessageConverter接口,需要开启<mvc:annotation-driven  />。 
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter的getMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>

引用
ByteArrayHttpMessageConverter 
StringHttpMessageConverter 
ResourceHttpMessageConverter 
SourceHttpMessageConverter 
XmlAwareFormHttpMessageConverter 
Jaxb2RootElementHttpMessageConverter 
MappingJacksonHttpMessageConverter
有关@ResponseBody,@RequestBody,@PathVariable 的详细信息,参考《@ResponseBody,@RequestBody,@PathVariable 》
比如上述controller中的hello1和hello2方法,其中hello1使用了注解@ResponseBody,那么会将string通过httpMsessageConverter直接转换,写入response;而hello2方法没有使用注解,那么就会根据spring-mvc.xml中配置的解析器,寻找jsp页面,并写入response,返回给浏览器。
 
总结:
  1.和springmvc配置不一样的地方主要是controller中的方法也是用@ResponseBody注解,将Object转成相对应的协议(一般是xml和json)写入到response中,返回给浏览器。
  2.一定要开启<mvc:annotation-driven  />
  3.方法RequestMapping设置一定要遵循Restful规范风格。
 
 

SpringMVC构建Restful。的更多相关文章

  1. SpringMVC 构建Restful风格 及问题处理

    基本的请求URL: /person/{id}  GET  得到id的person /person POST      新增person /person/{id}  PUT  更新id的person / ...

  2. SwaggerUI+SpringMVC——构建RestFul API的可视化界面

    今天给大家介绍一款工具,这个工具眼下可预见的优点是:自己主动维护最新的接口文档. 我们都知道,接口文档是非常重要的,可是随着代码的不断更新,文档却非常难持续跟着更新,今天要介绍的工具,完美的攻克了这个 ...

  3. 用springMVC构建restful程序,接收以及返回json数据格式

    主要参考文章:http://kingxss.iteye.com/blog/1487745和http://blog.csdn.net/greensurfer/article/details/192962 ...

  4. [SpringBoot guides系列翻译]SpringBoot构建RESTful程序入门

    原文地址 构建一个RESTful的WebService 这个指南将带你用Spring创建一个RESTful的helloworld程序. 你将完成 在下面地址上创建一个接收http get请求的服务 h ...

  5. Spring Boot 中 10 行代码构建 RESTful 风格应用

    RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...

  6. Spring Boot2 系列教程(三十一)Spring Boot 构建 RESTful 风格应用

    RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...

  7. 【快学springboot】2.Restful简介,SpringBoot构建Restful接口

    Restful简介 Restful一种软件架构风格.设计风格,而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现 ...

  8. Spring Boot构建 RESTful 风格应用

    Spring Boot构建 RESTful 风格应用 1.Spring Boot构建 RESTful 风格应用 1.1 实战 1.1.1 创建工程 1.1.2 构建实体类 1.1.4 查询定制 1.1 ...

  9. Spring MVC中使用 Swagger2 构建Restful API

    1.Spring MVC配置文件中的配置 [java] view plain copy <!-- 设置使用注解的类所在的jar包,只加载controller类 --> <contex ...

随机推荐

  1. pg_config executable not found

    Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or ...

  2. java做帐户登录失败锁定

    对于连续失败登录应用系统5次的帐号,需锁定该帐号至少30分钟不允许登录. 这里也用简单的map集合进行判定,功能能实现,但并不是很完美,不用更改数据库的表字段 1.首先建立一个用户登陆失败的实体类 p ...

  3. java初学第二章

    这两天学习了基本的数据类型还有运算符. 分享一下学习过程还有写作~ 数据类型分为基本数据类型还有引用数据类型,基本数据类型有4类8种: 整型: byte,short,int,long 浮点型:floa ...

  4. 手机自动化测试:Appium源码之api(1)

    手机自动化测试:Appium源码之api(1)   AppiumDriver getAppStrings() 默认系统语言对应的Strings.xml文件内的数据. driver.getAppStri ...

  5. 玩转 SSH 目录

    在做一个新的项目的时候,需要重新搭建一个项目. 于是趁着这个机会把之前学的几个框架的搭建都写一写,整理一下,同时也可以给大家一些参考.何乐而不为叻. 在这个系列中, 我将使用 IntelJ IDEA ...

  6. Java并发编程:Java线程池

    转载自:http://www.cnblogs.com/dolphin0520/p/3932921.html 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题 ...

  7. windows server 定期备份数据库脚本

    将以下文件保存为.bat脚本,在计划任务中添加定时任务运行此脚本即可.脚本中的备份目录,数据库目录和压缩文件目录请自行修改. @echo off rem 当前路径切换到备份数据库目录 cd D:\wa ...

  8. Masonry适配的简单使用

    一.Masonry是什么: 答:是一个很好的三方,用来做适配的 二.怎么使用Masonry 1.先导入头文件 #define MAS_SHORTHAND #define MAS_SHORTHAND_G ...

  9. Spring+Redis(keyspace notification)实现定时任务(订单过期自动关闭)

    1.起因 最近公司项目要做订单超期未支付需自动关闭,首先想到的是用spring的定时器(@Schedule),结果领导举各种例子说会影响性能,只能作罢.后来想能不能基于redis实现, 学习(baid ...

  10. android studio 2.3 下载地址

      android studio下载:  Windows+SDK:(1.8GB)| Windows(428 MB) | Linux    idea  win.exe  win.zip 序号 名称 中文 ...