springboot交互

1.get请求,url路径传参

 

如

http://localhost:4001/api/unit?id=200

@RestController

public class HelloController {

@GetMapping(value="/hello")

public String sayHello(@RequestParam Integer id){

return "id:"+id;

}

}

 

2.get请求,url路径参数

 

如:

http://localhost:4001/hello/id/123

@RestController

public class HelloController {

@GetMapping(value="/hello/{id}/{name}")

public String sayHello(@PathVariable("id") Integer id)

{

return "id:"+id;

}

}

 

Body参数 POST请求

 

较推荐使用json格式传值

 

//map接收

@PostMapping(path = "/demo1")

public void demo1(@RequestBody Map<String, String> person) {

System.out.println(person.get("name"));

}

//或者是实体对象接收

@PostMapping(path = "/demo1")

public void demo1(@RequestBody Person person) {

System.out.println(person.toString());

}

注意;@RequestBody,它是用来处理前台定义发来的数据Content-Type: 而不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;

使用@RequestBody注解接收参数的时候,从名称上来看也就是说要读取的数据在请求体里,前台的Content-Type必须要改为application/json,所以要发post请求,因为Ajax使用的POST,并且发送的是JSON对象。前端必须指定请求json数据的contentType为:application/json,否则会报类型不支持的异常错误“org.springframework.web.HttpMediaTypeNotSupportedException”


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

在这里我们把Content-Type设置为了json格式。

我们还可以在headers里面加入别的参数,比如Token。

后端可以通过HttpServletRequest 获取请求头的内容,如:

request.getHeader(string name)方法:String

request.getHeaders(String name)方法:Enumeration

request.getHeaderNames()方法

@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());

}

}

}

四、HttpServletRequest


@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(HttpServletRequest request){
      System.err.println(request.getParameter("openid"));
      System.err.println(request.getParameter("username"));
      System.err.println(request.getParameter("password"));
}

posted @ 2021-07-27 08:31  踩坑大吏  阅读(117)  评论(0)    收藏  举报