gurmigou
gurmigou

Reputation: 55

Encoding problem in POST method Spring and Thymeleaf

I have made a simple form where a user enters a name and then this name is stored in the database. I'm using Spring MVC and Thymeleaf. My database is MySQL. The problem occurred when I was trying to enter non-latin characters. enter image description here

After storing the non-latin name in the database, I tried to display it on the webpage, but instead of cyrillic characters I got strange characters like this:

ИмÑ

<h1> Заголовок </h1>

I have already tried:

But nothing works. What am I doing wrong?

Upvotes: 0

Views: 840

Answers (2)

Andrew
Andrew

Reputation: 1

I faced a similar problem. Thank you for your answer @gurmigou. You showed me the way to go, and I found an even better solution.

    <filter>
    <filter-name>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>filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

Upvotes: 0

gurmigou
gurmigou

Reputation: 55

I have searched a lot and at last, I have found a solution.

- The first one I would rather call a workaround than a solution:

    @PostMapping
    public String create(@RequestParam("name") String name, @RequestParam("age") int age) {      

        byte[] bytes = name.getBytes(StandardCharsets.ISO_8859_1);
        name = new String(bytes, StandardCharsets.UTF_8); // now "name" contains characters in the correct encoding

        ...
    }

- The second solution looks much better in my opinion:
At first, create a Filter class and set the encoding of the POST request there:

   public class RequestFilter extends HttpFilter {
        @Override
        protected void doFilter(HttpServletRequest request, HttpServletResponse response,
                                FilterChain chain) throws IOException, ServletException
        {
            request.setCharacterEncoding("UTF-8");
            chain.doFilter(request, response);
        }
    }

Then you should register a Filter in web.xml

 <filter>
    <filter-name>filter_nane</filter-name>
    <filter-class>class_path_to_filter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>filter_nane</filter-name>
    <url-pattern>/*</url-pattern> 
  </filter-mapping>

Upvotes: 1

Related Questions