1、建了一个简易的spring mvc服务,访问正常。只是调用页面中含有中文字符时,打开为乱码。
(1)、服务代码
package cn.com.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/mvc")
public class mvcController {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
(2)、hello.html代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>哎</title>
</head>
<body>
乱码
</body>
</html>
(3)、浏览器访问显示乱码
2、检查过程
(1)、hello.html里面已说明是UTF-8格式显示,<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">;
(2)、hello.html的文件格式UTF-8;
(3)、项目的格式默认也是UTF-8;
(4)、直接用浏览器打开hello.html,正常显示。
3、解决方法
(1)、修改hello.html文件,添加lang="zh-CN",刷新页面后,中文显示正常。
(2)、网上还有说是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>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>