日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Spring MVC搭建REST风格网站

發(fā)布時(shí)間:2023/12/10 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring MVC搭建REST风格网站 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

REST是表述性狀態(tài)轉(zhuǎn)移的意思。REST核心是以資源為中心。

比如,URI是統(tǒng)一資源標(biāo)識(shí)符,URL是一種URI,稱為統(tǒng)一資源定位符。現(xiàn)在很多網(wǎng)站設(shè)計(jì)的URL,沒(méi)有以資源為中心,沒(méi)有體現(xiàn)URI的標(biāo)識(shí)本質(zhì)。比如,有一個(gè)URL:/user?id=1&name=lcl ,其中id參數(shù)是用來(lái)定位一個(gè)“id=1的用戶”,這就有悖于URI的本質(zhì),既然URI本身可以標(biāo)識(shí)一個(gè)資源,那么就不應(yīng)該借助額外參數(shù)來(lái)標(biāo)識(shí)這個(gè)資源,所以這是一個(gè)非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());}}
  • 參考《spring 實(shí)戰(zhàn)》 278頁(yè)
  • 總結(jié)

    以上是生活随笔為你收集整理的Spring MVC搭建REST风格网站的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。