springmvc RESTful 实现

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值