我正在使用Spring MVC和Thymeleaf使用Java配置开发webapp。在html
页面的模板中,语言通过以下代码设置为瑞典语:
<html lang="sv">
通过此元标记将编码设置为UTF-8:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
但出于某种原因,这不会显示瑞典字母。
我尝试将<html>
标记更改为XHTML版本xml:lang="en"
,但没有任何区别。
由于我还不熟悉Spring和Thymeleaf,我不知道哪里可能出错,或者语言/字符集应该在哪里陈述/设定所以我给予了你是百万美元的配置代码和页面控制器:
@Configuration
public class ThymeleafConfig {
@Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
resolver.setCacheable(false);
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
return engine;
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
return resolver;
}
}
控制器:
@Controller
public class IndexController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
ModelAndView model = new ModelAndView();
model.setViewName("index");
return model;
}
}
答案 0 :(得分:2)
只有在characterEncoding
和ServletContextTemplateResolver
添加了属性ThymeleafViewResolver
时才能获得正确的编码。
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
...
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
...
<property name="characterEncoding" value="UTF-8"/>
</bean>
答案 1 :(得分:1)
将以下行添加到templateResolver
中的ThymeleafConfig
:
resolver.setCharacterEncoding("UTF-8");
正如docs setCharacterEncoding
中所述:
指定要在响应中设置的字符编码 视图已呈现。