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

y53ybaqx  于 5个月前  发布在  Spring
关注(0)|答案(2)|浏览(47)

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

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", required = false) String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

字符串

wqnecbli

wqnecbli1#

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

6jjcrrmo

6jjcrrmo2#

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

public class SimpleFilter implements Filter {

    private final UDecoder urlDecoder = new UDecoder();
    private final Logger logger = LoggerFactory.getLogger(SimpleFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String queryString = httpServletRequest.getQueryString();
        if (queryString != null) {
            ByteChunk byteChunk = new ByteChunk();
            byteChunk.setBytes(queryString.getBytes(), 0, queryString.length());
            try {
                urlDecoder.convert(byteChunk, true);
            } catch (IOException ioException) {
                logger.error("Hazarduos character found in request parameter.");
                httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());
                return;
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}

字符串

相关问题