UTF-8 encoding in Spring MVC/JSP

Posted on 16-03-2013 16:58 by graham
If you're building an app for users other than English, you're likely to need to add some UTF-8 characters. This tutorial shows how to properly implement this in your Web application.

Source file encoding


This first step might not be necessary, but it's worth making sure you're JSP and Java source files are in UTF-8.

JSP page charset


The second step is to make JSP use the UTF-8 charset:
MyPage.jsp
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
...


Use the CharsetEncodingFilter


You also need to include the CharsetEncodingFilter in the filter chain. To do this, in your web.xml put the following filter at the beginning:
web.xml
<filter>
<filter-name>encoding-filter</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>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

That's it. Now all values passed in the app, e.g. during form submission, will be encoded in UTF-8.
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems