SpringMVC:前後端傳值總結

依然didala發表於2016-07-09

前言

文章主要來自:點這裡 。這也是博主的部落格,主要分享了自己接觸過的一些後端技術,有不對的地方希望可以提出。

由於在寫程式碼的時候經常需要前後端進行傳值,那麼總結下前端是如何給後端傳值,以及後端是如何接收的。以下包括:@PathVarible,@PathParam,@RequestParam,@ RequestBody,@RequestHeader 以及 Spring 自動封裝。

@PathVarible

後端:

@RequestMapping(value="/findarticlesbyclassify/{classifyId}",method=RequestMethod.GET)
public String  findArticlesByClassify(@PathVariable String classifyId){
   ...
}

前端:http://localhost:8080/article/findarticlesbyclassify/aaac4e63-da8b-4def-a86c-6543d80a8a1

@PathParam

後端:

@RequestMapping(value = "/findarticlesbyclassify",method=RequestMethod.GET)
public String  findArticlesByClassify(@PathParam("classifyId") String classifyId){
    ...
}

前端:http://localhost:8080/article/findarticlesbyclassify?classifyId=aaac4e63-da8b-4def-a86c-6543d80a8a1

@RequestParam

主要用來處理 Content-Type 為 application/x-www-form-urlencoded編碼 的內容。

後端:

@RequestMapping(value = "/findarticlesbyclassify",method=RequestMethod.GET)
public String  findArticlesByClassify(@RequestParam("classifyId") String classifyId){
    ...
}

前端:http://localhost:8080/article/findarticlesbyclassify?classifyId=aaac4e63-da8b-4def-a86c-6543d80a8a1

@ RequestBody

常用來處理Content-Type不是 application/x-www-form-urlencoded編碼 的內容。例如 json 資料。
當請求方式為 GET、POST 方式時,使用時機:

  • application/x-www-form-urlencoded, 可選(即非必須,因為這種情況的資料@RequestParam, @ModelAttribute也可以處理,當然@ RequestBody也能處理);

  • multipart/form-data, 不能處理(即使用@ RequestBody不能處理這種格式的資料);

  • 其他格式, 必須(其他格式包括application/json, application/xml等。這些格式的資料,必須使用@ RequestBody來處理)

@RequestHeader

自動繫結請求頭到引數

public String testRequestHeader( 
                    @RequestHeader ( "Host" ) String hostAddr, 
                    @RequestHeader String Host, 
                    @RequestHeader String host ) {  
      ...
}

Spring自動封裝

後端,有Article物件:

public class Article extends BaseEntity{
    private String title;
    private String classifyId;
    private String mdData;
    private int readNum = 0;
}

前端傳的引數有:

var data = {
    "title":req.body.title,
    "mdData":req.body.mdData,
    "classifyId":req.body.classifyId,
    "tag1":req.body.tag1,
    "tag2":req.body.tag2,
    "tag3":req.body.tag3
    }

後端接受引數如下:

@RequestMapping(value = "addarticle",method=RequestMethod.POST)
public String addArticle(HttpServletRequest request,Article article){
   ...
}

那麼就會自動封裝到物件 article 中。

以上並沒有涉及任何原理方面的東西,主要是為了方便 coding 時查閱。

寫在最後

  1. 寫出來,說出來才知道對不對,知道不對才能改正,改正了才能成長。

  2. 在技術方面,希望大家眼裡都容不得沙子。如果有不對的地方或者需要改進的地方希望可以指出,萬分感謝。

相關文章