zoukankan      html  css  js  c++  java
  • 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~

  • 相关阅读:
    新学期随笔——脚踏实地
    买书方案
    课程总结和建议
    梦断代码阅读笔记03
    梦断代码阅读笔记02
    构建之法阅读笔记06
    【洛谷5284】[十二省联考2019] 字符串问题(后缀树优化建边)
    【BZOJ3514】Codechef MARCH14 GERALD07加强版(LCT_主席树)
    【BZOJ1487】[HNOI2009]无归岛(仙人掌 DP)
    【洛谷3239_BZOJ4008】[HNOI2015] 亚瑟王(期望 DP)
  • 原文地址:https://www.cnblogs.com/jrmy/p/14316343.html
Copyright © 2011-2022 走看看