REST是表述性状态转移的意思。REST核心是以资源为中心。
比如,URI是统一资源标识符,URL是一种URI,称为统一资源定位符。现在很多网站设计的URL,没有以资源为中心,没有体现URI的标识本质。比如,有一个URL:/user?id=1&name=lcl
,其中id参数是用来定位一个“id=1的用户”,这就有悖于URI的本质,既然URI本身可以标识一个资源,那么就不应该借助额外参数来标识这个资源,所以这是一个非REST风格的URL。
REST提倡让URI回归资源表述的本质。所以上面的URL可以改成:/user/1?name=lcl
。
Controller:
package com.huanle.controller;import java.net.BindException;import javax.servlet.http.HttpServletResponse;import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;import com.huanle.model.User;@Controller
@RequestMapping("/user")
public class UserController {@RequestMapping( path= "/{id}" , method = RequestMethod.GET)public String getUser(@PathVariable long id){return "user";}@RequestMapping( path= "/{id}" , method = RequestMethod.PUT)@ResponseStatus( HttpStatus.NO_CONTENT )public void putUser(@PathVariable long id){//TODO:save user}@RequestMapping( path= "/{id}" , method = RequestMethod.DELETE)@ResponseStatus( HttpStatus.NO_CONTENT )public void deleteUser(@PathVariable long id){//TODO:delete user}@RequestMapping(method = RequestMethod.POST)@ResponseStatus( HttpStatus.CREATED )public void addUser(@Validated User user,BindingResult result,HttpServletResponse response) throws BindException{if(result.hasErrors()){throw new BindException();}//TODO: saveuser.setName("lcl");response.setHeader("Location", "/user/"+user.getId());}}
- 参考《spring 实战》 278页