How to handle special characters in @RequestParam for Java 17 backend?

I’m working on an app with an Angular frontend and Java 17 backend. I need to send a query parameter with a pipe character to my backend endpoint. It worked fine in Java 8 but now it’s causing issues.

Here’s what I’m trying to do:

@GetMapping("/api/{id}")
public ResponseEntity<?> getData(@PathVariable Long id, 
                                 @RequestParam(required = false) String query) {
    // ...
}

The frontend tries to call it like this:

http://myapp.com/api/123?query=someValue|otherValue

But the backend can’t find the endpoint when the pipe is included. It works if I remove the pipe.

I can’t change the pipe character and I need to use Java 17. Any ideas on how to make this work? Is there a way to encode or escape the pipe so the backend can handle it correctly?

This issue likely stems from how Java 17 handles special characters in URL parameters. One solution is to URL encode the query parameter on the frontend before sending it. In Angular, you can use the encodeURIComponent() function:

const encodedQuery = encodeURIComponent('someValue|otherValue');

On the backend, Spring should automatically decode the parameter. If not, you can manually decode it:

String decodedQuery = URLDecoder.decode(query, StandardCharsets.UTF_8);

Another approach is to configure your web server (e.g., Tomcat) to allow unencoded special characters. However, URL encoding is generally the safer and more standard approach. Remember to handle potential encoding/decoding exceptions in your code.

hey, u could try using @RequestParam(value = “query”, required = false) String query in ur endpoint. also, make sure ur server config allows special chars in URLs. if all else fails, maybe switch to POST and send the query in the body? that’d bypass URL encoding probs.

have u tried using a different character instead of the pipe? maybe a semicolon or something? cuz that might be an easy workaround. what about passing it as a json object instead of a query param? that could potentially sidestep the whole issue. what do you think?