Search code examples
javahibernatespring-mvcutf-8tomcat7

Webapp with UTF8


I'm working on webapp and I can't set up the encoding correctly. Right now, I have filter in my web.xml

<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>

I also add UTF-8 encoding into maven-resources-plugin and maven-compiler-plugin in my pom.xml. plugin into textarea in jsp file:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page language="java" pageEncoding="UTF-8"%>
...
<form:form method="post">
  <div class="row">
    <form:textarea class="form-control" id="newPost" rows="3" placeholder="Text nového příspěvku..." maxlength="1000" path="content"></form:textarea>
  </div>
  <div class="row contentOnRight">
    <button class="btn btn-primary mt-1">Odeslat</button>
  </div>
</form:form>

But when I send text from this form (for example "ššš"), in my Controller, I get Å¡Å¡Å¡.

Contoller

@RequestMapping(value = "/mainPage", method = RequestMethod.POST)
public String postMainPage(HttpServletRequest req, Authentication authentication, @ModelAttribute("post") Post post, ModelMap modelMap){
    try {
        //this doesn't help too
        req.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    //ModelAndView modelAndView = new ModelAndView("mainPage", "command", new Post());
    try {
            postManager.postNew(post, authentication.getName());
    }
    catch (PostValidationException e) {
        modelMap.addAttribute(ERROR_ATTRIBUTE, e.getMessage());
        //modelAndView.addObject(ERROR_ATTRIBUTE, e.getMessage());
        e.printStackTrace();
    }
    return "redirect:/mainPage";
}

I also tried to deploy war file into Tomcat7 with -Dfile.encoding=UTF8 parameter. But still no change. What I'm doing bad?


Solution

  • By default, the Servlet encoding is ISO-8859-1. Adding this arg to Tomcat can solve your issue:

    -Djavax.servlet.request.encoding=UTF-8