q932942491
「已注销」
2017-09-18 03:34

Spring项目中文乱码,求大神支招

  • spring
  • tomcat
  • 乱码

如题,我设置了request和response字符集,设置了过滤器,设置了Tomcat的字符集,也检查了IDEA的默认编码。可该乱码的还是乱码绝不含糊,求指教。

TestController.java

@Controller
public class TestController {

    @RequestMapping(value = "/encode1", method = RequestMethod.GET)
    @ResponseBody
    public String encode1() throws Exception{
        return "中文";
    }

    @RequestMapping(value = "/encode2", method = RequestMethod.GET)
    @ResponseBody
    public String encode2(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception{
        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        return new String("中文".getBytes("ISO-8859-1"), "UTF-8") + "中文" + request.getCharacterEncoding() + response.getContentType();
    }
}

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>

Tomcat中的web.xml

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               URIEncoding="UTF-8"
               useBodyEncodingForURI="true" />

环境变量

IDEA字符集

结果

图片说明

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐

换一换