當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring MVC搭建REST风格网站
生活随笔
收集整理的這篇文章主要介紹了
Spring MVC搭建REST风格网站
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 MVC搭建REST风格网站的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为加持威力巨大 问界M5累计销量破万:
- 下一篇: 不连蓝牙一样用:森海塞尔推出电视专用无线