當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring MVC搭建REST风格网站
生活随笔
收集整理的這篇文章主要介紹了
Spring MVC搭建REST风格网站
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
REST是表述性狀態(tài)轉(zhuǎn)移的意思。REST核心是以資源為中心。
比如,URI是統(tǒng)一資源標(biāo)識符,URL是一種URI,稱為統(tǒng)一資源定位符。現(xiàn)在很多網(wǎng)站設(shè)計的URL,沒有以資源為中心,沒有體現(xiàn)URI的標(biāo)識本質(zhì)。比如,有一個URL:/user?id=1&name=lcl ,其中id參數(shù)是用來定位一個“id=1的用戶”,這就有悖于URI的本質(zhì),既然URI本身可以標(biāo)識一個資源,那么就不應(yīng)該借助額外參數(shù)來標(biāo)識這個資源,所以這是一個非REST風(fēng)格的URL。
REST提倡讓URI回歸資源表述的本質(zhì)。所以上面的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());}}總結(jié)
以上是生活随笔為你收集整理的Spring MVC搭建REST风格网站的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为加持威力巨大 问界M5累计销量破万:
- 下一篇: datagridview 当前上下文中不