+
80
-

spring boot如何获取get 或post的数据?

spring boot如何获取get 或post的数据?

网友回复

+
0
-

直接写在控制器方法的参数后面,例如username和pwd,代码如下:

    @RequestMapping("/hello2")
    public String Index(String username,String pwd) {
        return username;
    }

如果post的方式是application/x-www-form-urlencoded,上面可以正常接收,但是如果是application/json的话,就要自定义解析,代码如下:

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


@RestController
public class TestController {
  @RequestMapping(value = "/demo",method = RequestMethod.POST)
  public String demo(HttpServletRequest req){
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
      StringBuffer sb=new StringBuffer();
      String s=null;
      while((s=br.readLine())!=null){
        sb.append(s);
      }
      JSONObject jsonObject = JSONObject.parseObject(sb.toString());
      String name = jsonObject.getString("name");
      String age = jsonObject.getString("age");
      System.out.println("name:"+name+" age:"+age);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "server response";
  }
}

或者使用使用@RequestBody注解

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class TestController {
  @RequestMapping(value = "/demo",method = RequestMethod.POST)
  public String demo(@RequestBody Person person){
    System.out.println(person);
    return "server response";
  }
}

Person类

import lombok.*;

@Data
class Person{
	private String name;
	private String age;
}

+
0
-

还可以通过HttpServletRequest.getParamenter("firstName")获取get post参数值,代码如下:

@RequstMapping("/test2")

@ResponseBody

public String test2( HttpServletRequest request )

{

     String firstName = request.getParamenter("firstName");

     String lastName = request.getParameter("lastName");

     return firstName = lastName; 

}

我知道答案,我要回答