简体   繁体   English

Spring MVC UTF-8 编码

[英]Spring MVC UTF-8 Encoding

At the moment I'm trying to get started with Spring MVC.目前我正在尝试开始使用 Spring MVC。 While trying things out I ran into an encoding issue.在尝试时,我遇到了编码问题。

I want to display UTF-8 characters on my JSP-Pages so I added a String with UTF-8 characters to my ModelAndView.我想在我的 JSP 页面上显示 UTF-8 字符,所以我向我的 ModelAndView 添加了一个带有 UTF-8 字符的字符串。 It looks like this:它看起来像这样:

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @RequestMapping(value="/", method=RequestMethod.GET)
    public ModelAndView home() {
        logger.info("Welcome home!");
        return new ModelAndView("home", "utftest", "ölm");
    }

}

On the JSP page I just want to display the String with UTF-8 characters like this:在 JSP 页面上,我只想显示带有 UTF-8 字符的字符串,如下所示:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Home</title>
</head>
<body>
    <h1>Hello world!</h1>
    <p><c:out value="ö" /></p>
    <p><c:out value="${utftest}"></c:out></p>
</body>
</html>

As result I get following:结果我得到以下信息:

Hello world!

ö

ölm

Note that following code <c:out value="ö" /> was displayed without encoding error.请注意,显示以下代码<c:out value="ö" />没有编码错误。 I also set the default encoding to UTF-8 in Springsource Tool Suite but I'm still getting wrong characters.我还在 Springsource Tool Suite 中将默认编码设置为 UTF-8,但我仍然收到错误的字符。

Edit:编辑:

Maybe I should have mentioned that I'm using a Mac with OS X 10.6.也许我应该提到我使用的是装有 OS X 10.6 的 Mac。 For Spring development I use the Springsource Tool Suite from Spring (http://www.springsource.com/developer/sts).对于 Spring 开发,我使用 Spring (http://www.springsource.com/developer/sts) 的 Springsource Tool Suite。 Hope this helps to find out what is wrong with my setting.希望这有助于找出我的设置有什么问题。

Edit 2:编辑2:

Thanks to McDwell, I just tried out using "\ölm" instead of "ölm" in my controller and the encoding issue on the JSP page is gone.感谢 McDwell,我刚刚尝试在控制器中使用"\ölm"而不是"ölm" ,并且 JSP 页面上的编码问题消失了。

Does that mean my .java files are encoded with wrong character set?这是否意味着我的 .java 文件使用错误的字符集编码? Where can I change this in Eclipse?我在哪里可以在 Eclipse 中更改它?

Thank you.谢谢你。

Make sure you register Spring's CharacterEncodingFilter in your web.xml (must be the first filter in that file).确保在web.xml注册 Spring 的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>  
<filter-mapping>  
    <filter-name>encodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping> 

If you are on Tomcat you might not have set the URIEncoding in your server.xml .如果您使用 Tomcat,您可能没有在server.xml设置URIEncoding If you don't set it to UTF-8 it won't work.如果您不将其设置为 UTF-8,它将无法工作。 Definitely keep the CharacterEncodingFilter .一定要保留CharacterEncodingFilter Nevertheless, here's a concise checklist to follow.不过,这里有一个简明的清单要遵循。 It will definitely guide you to make this work.它肯定会指导您完成这项工作。

Ok guys I found the reason for my encoding issue.好的,我找到了编码问题的原因。

The fault was in my build process.错误出在我的构建过程中。 I didn't tell Maven in my pom.xml file to build the project with the UTF-8 encoding.我没有在我的pom.xml文件中告诉 Maven 使用 UTF-8 编码构建项目。 Therefor Maven just took the default encoding from my system which is MacRoman and build it with the MacRoman encoding.因此,Maven 只是从我的系统中获取默认编码,即 MacRoman,并使用 MacRoman 编码构建它。

Luckily Maven is warning you about this when building your project (BUT there is a good chance that the warning disappears to fast from your screen because of all the other messages).幸运的是,Maven 在构建项目时会警告您这一点(但由于所有其他消息,警告很有可能会从您的屏幕上快速消失)。

Here is the property you need to set in the pom.xml file:这是您需要在pom.xml文件中设置的属性:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    ...
</properties>

Thank you guys for all your help.谢谢你们的帮助。 Without you guys I wouldn't be able to figure this out!没有你们,我无法弄清楚这一点!

In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).除了 Benjamin 的回答(我只是略读过)之外,您还需要确保您的文件实际上是使用正确的编码存储的(对于源代码、JSP 等将是 UTF-8,但请注意 Java 属性文件根据定义必须编码为 ISO 8859-1)。

The problem with this is that it's not possible to tell what encoding has been used to store a file.这样做的问题是无法知道使用什么编码来存储文件。 Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense.您唯一的选择是使用特定编码打开文件,并检查内容是否有意义。 You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect.您还可以尝试使用 iconv 将文件从假定的编码转换为所需的编码 - 如果产生错误,则您的假设不正确。 So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.因此,如果您假设 hello.jsp 编码为 UTF-8,请运行“iconv -f UTF-16 -t UTF-8 hello.jsp”并检查错误。

If you should find out that your files are not properly encoded, you need to find out why.如果您发现文件未正确编码,则需要找出原因。 It's probably the editor or IDE you used to create the file.它可能是您用来创建文件的编辑器或 IDE。 In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).对于 Eclipse(和 STS),请确保文本文件编码(首选项/常规/工作区)设置为 UTF-8(不幸的是默认为您系统的平台编码)。

What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.编码问题如此难以调试的原因在于涉及的组件太多(文本编辑器、浏览器,以及中间的每个软件组件,在某些情况下包括数据库),并且每个组件都有可能引入错误。

In addition to Benjamin's answer - in case if you are using Spring Security , placing the CharacterEncodingFilter in web.xml might not always work.除了本杰明的回答 - 如果您使用的是Spring Security ,将 CharacterEncodingFilter 放在 web.xml 中可能并不总是有效。 In this case you need to create a custom filter and add it to the filter chain as the first filter.在这种情况下,您需要创建一个自定义过滤器并将其作为第一个过滤器添加到过滤器链中。 To make sure it's the first filter in the chain, you need to add it before ChannelProcessingFilter, using addFilterBefore in your WebSecurityConfigurerAdapter:为了确保它是链中的第一个过滤器,您需要在 ChannelProcessingFilter 之前添加它,在 WebSecurityConfigurerAdapter 中使用addFilterBefore

@Configuration
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //add your custom encoding filter as the first filter in the chain
        http.addFilterBefore(new EncodingFilter(), ChannelProcessingFilter.class);

        http.authorizeRequests()
            .and()
            // your code here ...
    }
}

The ordering of all filters in Spring Security is available here: HttpSecurityBuilder - addFilter() Spring Security 中所有过滤器的排序可在此处获得: HttpSecurityBuilder - addFilter()

Your custom UTF-8 encoding filter can look like following:您的自定义 UTF-8 编码过滤器可能如下所示:

public class EncodingFilter extends GenericFilterBean {

    @Override
    public void doFilter(
            ServletRequest request, 
            ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        chain.doFilter(request, response);
    }
}

Don't forget to add in your jsp files:不要忘记添加您的jsp文件:

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

And remove the CharacterEncodingFilter from web.xml if it's there.如果存在,则从 web.xml 中删除 CharacterEncodingFilter。

Easiest solution to force UTF-8 encoding in Spring MVC returning String:在返回字符串的 Spring MVC 中强制使用 UTF-8 编码的最简单解决方案:

In @RequestMapping , use:@RequestMapping ,使用:

produces = MediaType.APPLICATION_JSON_VALUE + "; charset=utf-8"

To solve this issue you need below three steps:要解决此问题,您需要以下三个步骤:

  1. Set page encoding to UTF-8 like below:将页面编码设置为 UTF-8,如下所示:

     <%@ page language="java" pageEncoding="UTF-8"%> <%@ page contentType="text/html;charset=UTF-8" %>
  2. Set filter in web.xml file as below:在 web.xml 文件中设置过滤器如下:

     <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
  3. Set resource encoding to UTF-8, in case if you are writing any UTF-8 characters in Java code or JSP directly.将资源编码设置为 UTF-8,以防您直接在 Java 代码或 JSP 中编写任何 UTF-8 字符。

右键单击您的 controller.java 然后属性并检查您的文本文件是否使用 utf-8 编码,如果不是,这是您的错误。

Depending on how you render your view, you may also need:根据您呈现视图的方式,您可能还需要:

@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
    return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}

Worked for me like here Spring MVC Java config像这里一样为我工作Spring MVC Java config

by added to web initializer通过添加到 Web 初始值设定项

 @Override
      protected Filter[] getServletFilters() {

        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        return new Filter[] { characterEncodingFilter};
      }

Starting servlet spec 4.0, you can set the request character encoding in the servlet context without specifying the filter.从 servlet 规范 4.0 开始,您可以在 servlet 上下文中设置请求字符编码,而无需指定过滤器。

Either in web.xml:在 web.xml 中:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">
  <request-character-encoding>UTF-8</request-character-encoding>
  [...]

Or in Java config:或者在 Java 配置中:

servletContext.setRequestCharacterEncoding("UTF-8");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM