Spring mvc字符编码错误

时间:2014-07-05 22:50:16

标签: spring spring-mvc encoding utf-8 character-encoding

将dispachetServlet配置为:

@Override
protected Filter[] getServletFilters()
{
    return new Filter[] { new HiddenHttpMethodFilter(), characterEncodingFilter() };
}

private static final String CHARACTER_ENCODING = "UTF-8";

private CharacterEncodingFilter characterEncodingFilter()
{
    final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding( CHARACTER_ENCODING );
    characterEncodingFilter.setForceEncoding( true );
    return characterEncodingFilter;
}

和html上的meta一样:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

为什么当我提交带有文字字符的表单时:ç,ñ...我遇到了控制器错误的字符,如:çaça

我该如何解决?

已更新

我正在使用thymeleaf而不是jsp,我正在获取参数:

@RequestMapping( value = REGISTRATION, method = POST )
public String processRegistration( @ModelAttribute("userForm") User user, Model model )
{
    if( userService.existEmail(user)  )
    {
        model.addAttribute("duplicatedMail", true);
        return REGISTRATION_VIEW;
    }
    if( userService.existUsername(user)  )
    {
        model.addAttribute("duplicatedUsername", true);
        return REGISTRATION_VIEW;
    }
    userService.register( user );
    return REGISTRATION_SUCCESS_VIEW;
}

1 个答案:

答案 0 :(得分:1)

请尝试以下操作:

return new Filter[] { characterEncodingFilter(), new HiddenHttpMethodFilter() };

注意:您需要在HiddenHttpMethodFilter之前添加CharacterEncodingFilter,因为后者在内部调用ServletRequest.getParameter方法。

希望这有帮助。