freemarker乱码问题解决方案

一.spring mvc方面

1.在拦截器中

public class CustomInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		return true;
	}
}


2.在controller的action中return "string".getbyte("utf-8")进行转码。

	@RequestMapping("test")
	@ResponseBody
	public byte[] test(HttpServletResponse response) {
		log.info("hello");
		try {
			return "你好".getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "error".getBytes();
	}

另外,此处返回值byte[]不能写成string,否则也会出现乱码问题。


二.freemarker方面。

	<!-- freemarker的配置 -->
	<bean id="freemarkerConfigurer"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath" value="freemarker" />
		<property name="defaultEncoding" value="UTF-8" />
		<property name="freemarkerSettings">
			<props>
				<prop key="template_update_delay">0</prop>
				<prop key="locale">zh_CN</prop>
				<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
				<prop key="date_format">yyyy-MM-dd</prop>
				<prop key="number_format">#.##</prop>
			</props>
		</property>
	</bean>
	<!-- FreeMarker视图解析 如返回userinfo。。在这里配置后缀名ftl和视图解析器。。 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="viewClass" value="bp.common.CustomFreeMarkerView" />
		<property name="suffix" value=".html" />
		<property name="contentType" value="text/html;charset=UTF-8" />
		<property name="exposeRequestAttributes" value="true" />
		<property name="exposeSessionAttributes" value="true" />
		<property name="exposeSpringMacroHelpers" value="true" />
		<property name="allowSessionOverride" value="true" />
		<property name="redirectHttp10Compatible" value="false" />
	</bean>


OK~

posted on 2013-12-06 18:17  仗帅闯江湖  阅读(176)  评论(0编辑  收藏  举报

导航