2 q932942491 q932942491 于 2017.09.18 11:17 提问

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

为了解决中文乱码问题我几乎翻遍了所有相关资料。检查了过滤器,修改了Tomcat配置,,胡乱加了个不忘了什么作用的环境变量,检查了IDEA的字符集,调整了request和response的字符集,可是结果该乱码还是乱码绝不含糊,我真没招了。

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

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <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的server.xml

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

环境变量

IDEA字符集

结果

1个回答

xszfy0133
xszfy0133   2017.09.18 12:27

看看你JSP或者HTML文件的是不是用的UTF-8保存的

q932942491
q932942491 请仔细看下controller中的代码,我返回的是字符串而不是html文件,应该不关HTML什么事的
2 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片