在springboot中编码和解码参数的最佳方法是什么?

Reb*_*cca 10 java spring http-request-parameters spring-boot

我用来@RequestParam获取参数值,但我发现如果我传递像“name=abc&def&id=123”这样的值,我将得到名称值“abc”而不是“abc&def”。我发现对参数值进行编码和解码可以解决我的问题。但是我必须在每个控制器方法中编写编码和解码方法,spring有解码每个 @RequestParam值的全局方法吗?使用时@RequestParam,是否需要编码和解码每个值?

这是我的代码:

@PostMapping("/getStudent")
public Student getStudent(
        @RequestParam String name,
        @RequestParam String id) { 
        name= URLDecoder.decode(name, "UTF-8");  
        //searchStudent
        return Student;
}

@PostMapping("/getTeacher")
public teacher getTeacher(
        @RequestParam String name,
        @RequestParam String teacherNo) { 
        name= URLDecoder.decode(name, "UTF-8");  
        //searchTeacher
        return teacher;
}
Run Code Online (Sandbox Code Playgroud)

有人说Spring已经这样做了,但是我尝试过,结果不对。只使用curl cmd可以,但是java代码不行。

@PostMapping(value = "/example")
public String handleUrlDecode1(@RequestParam String param) { 
    //print ello%26test
    System.out.println("/example?param received: " + param); 
    return "success";
}

@GetMapping(value = "/request")
public String request() {
    String url =  "http://127.0.0.1:8080/example?param=ello%26test";
    System.out.println(url);
    RestTemplate restTemplate = new RestTemplate();
    return restTemplate.postForObject(url, null, String.class);
}
Run Code Online (Sandbox Code Playgroud)

flo*_*wer 2

您必须创建一个 HTTP 实体并在正文中发送标头和参数。

@GetMapping(value = "/request")
public String request()  {
    String url =  "http://127.0.0.1:8080/example";
    System.out.println(url);
    RestTemplate restTemplate = new RestTemplate(); 
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("param","ello&test");
    map.add("id","ab&c=def");
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers); 
    return restTemplate.postForObject(url, request, String.class);
}
Run Code Online (Sandbox Code Playgroud)