使用Spring MVC时如何在Freemarker视图中设置内容类型? [英] How to set content-type in Freemarker views when using Spring MVC?
问题描述
我正在将Sping MVC与freemarker视图一起使用.我设置了FreeMarkerViewResolver来解析视图,到目前为止,它仍然有效,但是现在我遇到了编码问题.我所有的视图都是采用UTF-8编码的HTML 5页面,我还向HTML页面添加了<meta charset="UTF-8" />
,但是仍然使用错误的编码来打印字符.我用 curl 检查了HTTP标头,发现了这一点:
I'm using Sping MVC with freemarker views. I set up a FreeMarkerViewResolver to resolve the views and it works so far but now I have encoding problems. All my views are HTML 5 pages in UTF-8 encoding and I also added a <meta charset="UTF-8" />
to the HTML page but characters are still printed in the wrong encoding. I checked the HTTP headers with curl and found this:
k@jules:~$ curl -I http://localhost:8080/testweb/test.view
HTTP/1.1 200 OK
Content-Type: */*;charset=ISO-8859-1
但是当我请求一些不存在的资源(这会生成Tomcat错误)时,我得到了:
But when I request some non-existing resource (Which generates a Tomcat error) then I get this:
k@jules:~$ curl -I http://localhost:8080/testweb/nothere.html
HTTP/1.1 200 OK
Content-Type: text/html;charset=utf-8
因此Tomcat本身返回正确的内容类型,但是Spring MVC Freemarker视图不返回.
So Tomcat itself returns the correct content-type but a Spring MVC Freemarker views don't.
对于JSP,我可以在JSP标头中设置Content-Type,但是在哪里可以为freemarker模板设置它呢?我想我必须在Spring bean配置中的某个位置执行此操作,但是找不到正确的位置.
For a JSP I can set the Content-Type in the JSP header but where can I set it for a freemarker template? I guess I have to do this somewhere in the Spring bean configuration but I can't find the right place.
推荐答案
视图解析器(应该在您的dispatcher-servlet.xml
中)具有为此的contentType
属性:
The view resolver (should be in your dispatcher-servlet.xml
) has a contentType
property for that:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="prefix" value=""/>
<property name="suffix" value=".ftl"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
这篇关于使用Spring MVC时如何在Freemarker视图中设置内容类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!