首页  ·  知识 ·  编程语言
SpringWebMVC实现RestfulWebService
网友  CSDN博客  JAVA  编辑:俊达   图片来源:网络
现在提到WebService大家马上联想到RESTful,因为RESTfulWebService已经深得人心,得到重用,相比笨重的SOAP越来越流行了

一引言:

以前一说到Web Service大家肯定会联想到SOAP,现在提到Web Service大家马上联想到RESTful,因为RESTful Web Service已经深得人心,得到重用,相比笨重的SOAP越来越流行了,那么什么是RESTful Web Service?REST英文全称为Representational State Transfer,翻译为中文即表征状态转移,是一种软件架构风格,REST关键原则为:

  1. 为所有事物定义ID

  2. 将所有事物链接在一起

  3. 使用标准方法

  4. 资源多重表述

  5. 无状态通信

RESTful Web Service 是一个使用HTTP并遵循REST原则的Web服务。它从三个方面资源进行定义:

  1. URI,比如:http://example.com/resources/

  2. Web Service接受与返回的互联网媒体类型,比如:JSON,XML等。

  3. Web Service在该资源上所支持的一系列请求方法(比如:POST,GET,PUTDELETE)。

HTTP 请求方法在RESTful Web 服务中的典型应用

资源

GET

PUT

POST

DELETE

一组资源的URI,比如http://example.com/resources/

列出 URI,以及该资源组中每个资源的详细信息(后者可选)。

使用给定的一组资源替换当前整组资源。

在本组资源中创建/追加一个新的资源。该操作往往返回新资源的URL

删除整组资源。

单个资源的URI,比如http://example.com/resources/142

获取指定的资源的详细信息,格式可以自选一个合适的网络媒体类型(比如:XMLJSON等)

替换/创建指定的资源。并将其追加到相应的资源组中。

把指定的资源当做一个资源组,并在其下创建/追加一个新的元素,使其隶属于当前资源。

删除指定的元素。

SpringMVCRESTful Web Service的支持:

1.URIHTTP请求方法映射到Java处理方法,并将JAVA方法处理结果返回给HTTP请求者(对应资源定义I和III)。

@RequestMapping

这是最重要的一个注解,用于处理HTTP请求地址映射,可用于类或方法上,用于类上时表示类中的所有响应请求的方法都是以该地址作为父路径,在spring中,一般一个Controller类处理一种资源,所以每个Controller类都会加@RequestMapping注解。

常用属性:

value:指定请求的地址

method:指定请求的method类型, GETPOSTPUTDELETE

params:指定request中必须包含某些参数值是,才让该方法处理

1

2

3

4

5

6

7

8

9

10

11

@Controller

@RequestMapping(value = "/contact")

public class ContactController {

    final Logger logger = LoggerFactory.getLogger(ContactController.class);

    @Autowired

    private ContactService contactService;

    @RequestMapping(value = "/listdata", method = RequestMethod.GET)

    @ResponseBody

    public Contacts listData() {

        return new Contacts(contactService.findAll());

    }

@PathVariable

映射URL路径里面的参数

1

2

3

4

5

@RequestMapping(value = "/{id}", method = RequestMethod.GET)

    @ResponseBody

    public Contact findContactById(@PathVariable Long id) {

        return contactService.findById(id);

    }

2.将接收的数据(如JSON格式数据)转换为JAVA对象和将JAVA对象转换为请求格式(如XML)的数据(对应资源定义II)

@RequestBody

用于读取Request请求的body数据,使用Bean配置中的 HttpMessageConverter 将数据转换为JAVA对象,再把对象绑定到 controller中方法的参数上。

1

2

3

4

5

6

7

8

@RequestMapping(value = "/", method = RequestMethod.POST)

    @ResponseBody

    public Contact create(@RequestBody Contact contact) {

        logger.info("Creating contact: " + contact);

        contactService.save(contact);

        logger.info("Contact created successfully with info: " + contact);

        return contact;

    }

@ResponseBody

用于将Controller中方法返回的对象,使用Bean配置中的 HttpMessageConverter 转换为指定格式数据,再写入到Response对象的body数据区。

1

2

3

4

5

@RequestMapping(value = "/listdata", method = RequestMethod.GET)

    @ResponseBody

    public Contacts listData() {

        return new Contacts(contactService.findAll());

    }

HttpMessageConverter配置示例:

1

2

3

4

5

6

7

8

9

10

<mvc:annotation-driven>

        <mvc:message-converters>

            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

            <bean

                class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">

                <property name="marshaller" ref="castorMarshaller" />

                <property name="unmarshaller" ref="castorMarshaller" />

            </bean>

        </mvc:message-converters>

    </mvc:annotation-driven>

默认情况下Spring已经启用了很多HttpMessageConverter,只要将他们的实现在类路径下即可,无需再配置。

  • ByteArrayHttpMessageConverter – converts byte arrays

  • StringHttpMessageConverter – converts Strings

  • ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream

  • SourceHttpMessageConverter – converts javax.xml.transform.Source

  • FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.

  • Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)

  • MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)

  • MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)

  • AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)

  • RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)


本文作者:网友 来源:CSDN博客
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读
也许感兴趣的
我们推荐的
主题最新
看看其它的