其他 · 2019年12月15日 0

SpringBoot Controller接收参数的几种常用方式

 第一类:请求路径参数


1、@PathVariable

获取路径参数。即url/{id}这种形式。
2、@RequestParam

获取查询参数。即url?name=这种形式
例子

GET
http://localhost:8080/demo/123?name=suki_rong
对应的java代码:

    @GetMapping("/demo/{id}")
    public void demo(@PathVariable(name = "id") String id, @RequestParam(name = "name") String name) {
        System.out.println("id="+id);
        System.out.println("name="+name);
    }

输出结果:
id=123
name=suki_rong

第二类:Body参数

因为是POST请求,这里用Postman的截图结合代码说明

1、@RequestBody

例子:

对应的java代码:

@PostMapping(path = "/demo1")
public void demo1(@RequestBody Person person) {
    System.out.println(person.toString());
}

输出结果:
name:suki_rong;age=18;hobby:programing

也可以是这样

@PostMapping(path = "/demo1")
public void demo1(@RequestBody Map<String, String> person) {
    System.out.println(person.get("name"));
}

输出结果:
suki_rong

2、无注解

例子

对应的java代码:

@PostMapping(path = "/demo2")
public void demo2(Person person) {
    System.out.println(person.toString());
}

输出结果:
name:suki_rong;age=18;hobby:programing

Person类

复制代码
public class Person {
private long id;
private String name;
private int age;
private String hobby;

@Override

public String toString(){

return "name:"+name+";age="+age+";hobby:"+hobby; }

// getters and setters
}

第三类:请求头参数以及Cookie

1、@RequestHeader

2、@CookieValue

例子

java代码:

@GetMapping("/demo3") 

public void demo3(@RequestHeader(name = "myHeader") String myHeader, @CookieValue(name = "myCookie") String myCookie) {
System.out.println("myHeader=" + myHeader);
System.out.println("myCookie=" + myCookie);
}

也可以这样:

@GetMapping("/demo3") public void demo3(HttpServletRequest request) { 
System.out.println(request.getHeader("myHeader"));
for (Cookie cookie : request.getCookies()) {

if ("myCookie".equals(cookie.getName())) {
System.out.println(cookie.getValue());
}
}
}

地址传值
@PathVariable
获取路径参数。即url/{id}这种形式。

? 传值
@RequestParam
获取查询参数。即url?name=这种形式

用注解@RequestParam绑定请求参数到方法入参
当请求参数username不存在时会有异常发生,可以通过设置属性required=false解决,例如: @RequestParam(value=“username”, required=false)

Body参数
//application/jason
@PostMapping(path = “/demo1”)
public void demo1(@RequestBody Person person) {

无注解(form提交)
//form-data
@PostMapping(path = “/demo1”)
public void demo1(Person person) {

请求头参数以及Cookie
@RequestHeader
2、@CookieValue
例子
java代码:

@GetMapping(“/demo3”)
public void demo3(@RequestHeader(name = “myHeader”) String myHeader,
@CookieValue(name = “myCookie”) String myCookie) {
System.out.println(“myHeader=” + myHeader);
System.out.println(“myCookie=” + myCookie);
也可以这样

@GetMapping(“/demo3”)
public void demo3(HttpServletRequest request) {
System.out.println(request.getHeader(“myHeader”));
for (Cookie cookie : request.getCookies()) {
if (“myCookie”.equals(cookie.getName())) {
System.out.println(cookie.getValue());

//请求头参数以及Cookie
@RequestMapping(“request5”)
public String test5(@RequestHeader(name =”Header”) String Header,
@CookieValue(name =”cookie1″) String cookie1,
@CookieValue(name =”cookie2″) String cookie2){
return “Header:”+Header+”cookie1:”+cookie1+”cookie2″+cookie2;
}

//Cookie
@GetMapping(“/ee”)
public String ee(@RequestHeader(name=”myHeader”) String myHeader,@CookieValue(name=”myCookie”) String myCookie){
System.out.println(“myHeader=” + myHeader);
System.out.println(“myCookie=” + myCookie);
return “———“+myHeader+”=============”+myCookie;
}

表单的参数写在Controller相应的方法的形参中
适用于get方式提交,不适用于post方式提交。
/**

  • 1.直接把表单的参数写在Controller相应的方法的形参中
  • @param username
  • @param password
  • @return
    */
    @RequestMapping(“/addUser1”)
    public String addUser1(String username,String password) {
    System.out.println(“username is:”+username);

@ModelAttribute注解获取POST请求的FORM表单数据
/**

  • 使用@ModelAttribute注解获取POST请求的FORM表单数据
  • @param user
  • @return
    */
    @RequestMapping(value=”/addUser5″,method=RequestMethod.POST)
    public String addUser5(@ModelAttribute(“user”) UserModel user) {
    System.out.println(“username is:”+user.getUsername());
    System.out.println(“password is:”+user.getPassword());
    return “demo/index”;

测试代码
Controller

package com.zz.controller;

import java.util.HashMap;
import java.util.Map;

import com.zz.entity.User;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(“test”)
public class TestController {

//路径传值
@RequestMapping("t1/{p1}")
public Map t1(@PathVariable("p1") String paramter1){
    Map map=new HashMap();
    map.put("rs",paramter1);
    return  map;
}
//? 传值
@RequestMapping("t2")
public Map t2(@RequestParam("p1") String paramter1)
{
    System.out.println(paramter1);
    Map map=new HashMap();
    map.put("rs",paramter1);
    return  map;
}

//Body参数

//application/jason
@RequestMapping(“t3”)
public Map t3(@RequestBody User person){

    Map map=new HashMap();
    map.put("rs",person.getName());
    return  map;
}

// 无注解(form提交)
//form-data
@RequestMapping(“t4”)
public Map t4(User person){

    Map map=new HashMap();
    map.put("rs",person.getName());
    return  map;
}

// 请求头参数以及Cookie
@RequestMapping(“t5”)
public Map t5(@RequestHeader(name =”myHeader”) String myHeader,
@CookieValue(name = “myCookie”) String myCookie){
System.out.println(“myHeader=” + myHeader);
System.out.println(“myCookie=” + myCookie);
Map map=new HashMap();
map.put(“rs”,myHeader);
return map;
}

// 表单的参数写在Controller相应的方法的形参中
// 适用于get方式提交,不适用于post方式提交。
@RequestMapping(“t6”)
public Map t6(String name,String pwd){

    Map map=new HashMap();
    map.put("rs",name);
    return  map;
}



Bootstrap 实例

测试


SpringBoot Form post 提交 跳转失败 解决办法
报错日志:tSupportedException: Request method ‘POST’ not supported
解决: post controller方法里面 通过 return “redirect:/index/toIndex”; 执行get的跳转controller

package com.zz.controller;/**

  • @Description: 描述
  • @Author: Bsea
  • @CreateDate: ${Date}
    */

import com.zz.config.DataValidationException;
import com.zz.entity.Member;
import com.zz.form.MemberForm;
import com.zz.service.MemberService;
import com.zz.util.FormUtil;
import com.zz.util.ResultVOUtil;
import com.zz.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
/**

  • @Description: java类作用描述
  • @Author: Bsea
  • @CreateDate: 2019/10/1621:27
    */
    @Api(value = “会员控制器”)
    @Controller
    @RequestMapping(“index”)
    public class IndexController {
    @Resource
    MemberService memberService; @ApiOperation(value = “添加会员”, notes = “根据名字查找会员”)
    @ApiImplicitParam(name = “name”, value = “会员名字”, required = true, dataType = “String”,paramType = “path”)
    @PostMapping(“add”)
    public String add(@Valid MemberForm member, BindingResult bindingResult){
    System.out.println(member);
    if(bindingResult.hasErrors()){
    throw new DataValidationException(“验证错误”);
    }
    Member member1=new Member();
    BeanUtils.copyProperties(member,member1);
    if(memberService.add(member1)!=null){
    return “redirect:/index/toIndex”;
    }else{
    return “redirect:/index/toIndex”;
    }
    }
    @RequestMapping(“toIndex”)
    public String toIndex(){
    return “/index2.html”;
    }
    }

Share this: