Home > Net >  What's the best way to encode and decode parameter in springboot?
What's the best way to encode and decode parameter in springboot?

Time:07-20

I use @RequestParam to get the parameter value,but I find the if I pass the value like 'name=abc&def&id=123',I will get the name value 'abc' instead of 'abc&def'. I find the encode and decode the parameter value can solve my problem.But I have to write the encode and decode mehtod in every controller method,Do spring have the global mehtod that decode every @RequestParam value?When using @RequestParam, is it necessary to encode and decode every value?

Here is my code:

@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;
}

SomeOne say the the Spring will have already done this,but I have try,the result is not right.

@PostMapping(value = "/example")
public String handleUrlDecode1(@RequestParam String param) { 
    //print ello&test
    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&test";
    System.out.println(url);
    RestTemplate restTemplate = new RestTemplate();
    return restTemplate.postForObject(url, null, String.class);
}

CodePudding user response:

As you can read here, the escape character for & is &.

So you should use the following

name=abc&def&id=123

If you don't use an escape character according to URL standards, Spring will try to use what follows & and try to match it as a new query parameter.

CodePudding user response:

No need to manually use URLDecoder, SpringBoot controllers will handle it for you.

@RestController
public class UrlDecodeController {

    @GetMapping(value = "/example")
    public String handleUrlDecode(@RequestParam String param) {
    
        System.out.println("/example?param received: "   param);
    
        return "success";
    }
}

Call with GET /example?param=hello&test and the System.out.println outputs:

/example?param received: hello&test

  • Related