Springmvc:前后端传参方式总结

包括:@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 中。

你可能感兴趣的:(Springmvc)