Getting question mark instead accented letter using spring MVC 3

我与影子孤独终老i 提交于 2019-12-18 15:50:09

问题


I tried lots of thing and could not understand why i am getting ? instead accented character.

I'm using on my html:

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

and my controller has the following code

@RequestParam ("name") String name
name = name.trim();
system.out.println(name);
//response t?ata
//expected tábata

how do I fix that?

Thanks


回答1:


I could fix this issue by adding the following code on my master template:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>



回答2:


Accented letter and other languages like Mandarin and Arabic are tricky.
I guess you have not seen the last of this issue.
You should make sure that you keep your text encoded correctly in any link in the chain.

E.g.

  • database ->java ->response->browser
  • properties file ->jav-> response->browser
  • request (param/form) ->response->browser
  • java -> logger-> console

I suggest following this great answer How to get UTF-8 working in Java webapps?

To adjust it to spring use spring’s CharacterEncodingFilter.

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>
      org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
         </init-param>
        <init-param>
             <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
         </init-param>
 </filter>

If you are using i18n make sure to define the default Encoding for your ResourceBundleMessageSource e.g.

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
    >
        <property name="basename" value="classpath:messages"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="useCodeAsDefaultMessage" value="false"/>
</bean>

Make sure your properties files are encoded correctly using Java’s native2ascii.
Or better if you use eclipse I recommend Property Editor plugin.
Sometime third-party framework break something and you need to do the “magical”

new String(yourstring, "UTF8")

For more information see here

Note that some view resolvers need to defined encoding as well.



来源:https://stackoverflow.com/questions/14949351/getting-question-mark-instead-accented-letter-using-spring-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!