当前位置: 首页 > 面试题库 >

Get Parameter Encoding

闻人和泽
2023-03-14
问题内容

我在GET请求中使用spring mvc和特殊字符时遇到问题。请考虑以下方法:

@RequestMapping("/update")
public Object testMethod(@RequestParam String name) throws IOException {
    }

例如,我向其发送名称包含“ä”(德语为umlaut)的GET请求。由于浏览器将“ä”映射到,因此它会在Spring收到“ä” %C3%A4

因此,如何获得控制器的正确编码字符串?

谢谢你的帮助!


问题答案:

在你的web.xml中:

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.example.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <servlet-name>dispatcher</servlet-name>
    </filter-mapping>

com.example.CharacterEncodingFilter:

public class CharacterEncodingFilter implements Filter {

    protected String encoding;

    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        request.setCharacterEncoding(encoding);

        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
        encoding = null;
    }

}


 类似资料:

相关阅读

相关文章

相关问答