springmvc RESTful 实现

来源:互联网 发布:macbook删除windows 编辑:程序博客网 时间:2024/05/29 19:23

1   什么是RESTful

RESTful架构,就是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。

RESTful(即RepresentationalState Transfer的缩写)其实是一个开发理念,是对http的很好的诠释。

对url进行规范,写RESTful格式的url

 

非REST的url:http://...../queryItems.action?id=001&type=T01

REST的url风格:http://..../items/001

         特点:url简洁,将参数通过url传到服务端

http的方法规范

不管是删除、添加、更新。。使用url是一致的,如果进行删除,需要设置http的方法为delete,同理添加。。。

 

后台controller方法:判断http方法,如果是delete执行删除,如果是post执行添加。

 

对http的contentType规范

请求时指定contentType,要json数据,设置成json格式的type。。


2  REST的例子

查询商品信息,返回json数据。


2.1controller

定义方法,进行url映射使用REST风格的url,将查询商品信息的id传入controller .

 

输出json使用@ResponseBody将java对象输出json。

 @RequestMapping("/viewItems/{id}") public  @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id)  throws Exception { ItemsCustom custom = itemsService.findItemsById(id); return custom;}

2.2    REST方法的前端控制器配置

 

在web.xml配置:


<servlet><servlet-name>springmvc-rest</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <!--contextConfigLocation 配置springmvc价值的配置文件(配置处理器映射器、适配器等等)     如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(dispatcherServlet-servlet.xml)    -->    <init-param>       <param-name>contextConfigLocation</param-name>       <param-value>classpath:spring/springmvc.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>     <servlet-name>springmvc-rest</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping>

  对静态资源的解析

    <!-- springmvc 注解开发   适配器  映射器  -->    <mvc:annotation-driven conversion-service="conversionService" validator="validator">    </mvc:annotation-driven>    <mvc:resources location="/" mapping="/**/*.html"/>  <mvc:resources location="/" mapping="/**/*.js"/>  <mvc:resources location="/" mapping="/**/*.css"/>  <mvc:resources location="/" mapping="/**/*.png"/>  <mvc:resources location="/" mapping="/**/*.gif"/>  


效果图






0 0
原创粉丝点击