SpringBoot嵌入式tomcat服务器将查询参数中的unicode字符读取为null

y53ybaqx  于 2024-01-08  发布在  Spring
关注(0)|答案(2)|浏览(262)

我在Sping Boot 中设计了一个REST端点,使用Tomcat作为嵌入式服务器,它带有一个查询参数。
1.当我将查询参数作为param1%uFF07传递时,tomcat在内部将参数读取为null
1.当我把查询参数作为param1%FF07传递时,tomcat读取为某个字符。
tomcat只读取后跟两个十六进制数字的“%”字符,如果u放在“%”字符之后tomcat解析参数为null,并带有消息
字符解码失败。值为[param1%uFF07]的参数[name]已被忽略。请注意,由于解码失败,此处引用的名称和值可能已损坏。请使用调试级别日志记录查看原始的未损坏的值。注意:以后出现的参数错误将在调试级别记录。
下面是Sping Boot 控制器代码

  1. @RestController
  2. public class GreetingController {
  3. private static final String template = "Hello, %s!";
  4. private final AtomicLong counter = new AtomicLong();
  5. @RequestMapping("/greeting")
  6. public Greeting greeting(@RequestParam(value = "name", required = false) String name) {
  7. return new Greeting(counter.incrementAndGet(), String.format(template, name));
  8. }
  9. }

字符串

wqnecbli

wqnecbli1#

你在你的url中传递%符号,但是%是url中的符号,要传递%,你必须传递%25,然后它会像你预期的那样工作。
所以,如果你传递%25uFF07,那么它将显示%uFF07作为值。
不需要在application.properties或任何类型的设置中更改任何内容。我已经在我的项目中测试过了。
请随时要求任何澄清。希望它有帮助。

6jjcrrmo

6jjcrrmo2#

我发现了一种使用过滤器的方法。关于过滤器的基本知识可以在here上找到。我们可以在那里拦截请求查询字符串,并使用Tomcat UDecoder类解析查询字符串,如果抛出任何异常,我们可以显示400的响应

  1. public class SimpleFilter implements Filter {
  2. private final UDecoder urlDecoder = new UDecoder();
  3. private final Logger logger = LoggerFactory.getLogger(SimpleFilter.class);
  4. @Override
  5. public void init(FilterConfig filterConfig) throws ServletException {
  6. }
  7. @Override
  8. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  9. throws IOException, ServletException {
  10. HttpServletRequest httpServletRequest = (HttpServletRequest) request;
  11. HttpServletResponse httpServletResponse = (HttpServletResponse) response;
  12. String queryString = httpServletRequest.getQueryString();
  13. if (queryString != null) {
  14. ByteChunk byteChunk = new ByteChunk();
  15. byteChunk.setBytes(queryString.getBytes(), 0, queryString.length());
  16. try {
  17. urlDecoder.convert(byteChunk, true);
  18. } catch (IOException ioException) {
  19. logger.error("Hazarduos character found in request parameter.");
  20. httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());
  21. return;
  22. }
  23. }
  24. chain.doFilter(request, response);
  25. }
  26. @Override
  27. public void destroy() {
  28. }
  29. }

字符串

展开查看全部

相关问题