问题描述
前端页面使用的是html,服务端使用了springmvc框架,在一个controller中判断用户登录,如果用户名和密码正确则跳转到指定页面,否则还跳转回登录页面,结果发现用户名和密码不正确时跳转回的登录页面中文是乱码。
服务端
@RestController
@RequestMapping("/")
@ResponseBody
public class LoginController {
@PostMapping(value = "login")
public ModelAndView login(String username,String password,HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
if ("admin".equals(username) && "admin".equals(password)) {
request.getSession().setAttribute("user", new User(username,password));
mv.setViewName("index");
return mv;
}
mv.setViewName("login");
return mv;
}
}
springmvc-servlet配置文件
在springmvc的配置文件中配置视图解析器,html视图解析器使用freemarker的配置,需要配置mvc:freemarker和mvc:freemarker-configer
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.sundaysee.controller"/>
<mvc:resources mapping="/static/**" location="/static/" cache-period="31556926" />
<mvc:view-resolvers>
<mvc:freemarker suffix=".html"/>
</mvc:view-resolvers>
<!-- Configure FreeMarker... -->
<mvc:freemarker-configurer>
<mvc:template-loader-path location="/static/"/>
</mvc:freemarker-configurer>
</beans>
前端排查
看到前端显示乱码,F12查看浏览器控制台,发现Response Headers中Content-Type的值是 text/html;charset=iso-8859-1,很显然这个编码格式下中文会显示乱码。
解决方法
解决的方法也很简单,只需要在springmvc的配置文件中增加配置即可,有两种方式,
其一:在mvc:view-resolvers中使用FreeMarkerViewResolver类,对其contentType进行设置。(本来想直接使用mvc:freemarker标签的某个属性配置设置,但是没找到对应标签)
<mvc:view-resolvers>
<!-- <mvc:freemarker suffix=".html"/> -->
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="contentType" value="text/html;charset=UTF-8"></property>
<property name="suffix" value=".html" />
</bean>
</mvc:view-resolvers>
其二,直接使用mvc:freemarker和mvc:freemarker-configer的对应对象即可
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath">
<value>/static/</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="contentType" value="text/html;charset=UTF-8"></property>
<property name="suffix" value=".html" />
</bean>