首页 > Web开发 > 详细

struts2给前台输出json字符串以及出现的中文变成问号的解决方法

时间:2017-03-24 21:43:50      阅读:659      评论:0      收藏:0      [点我收藏+]

使用struts2往前台传输一个json的时候

public String getClientEvents() throws Exception {
        String response_json;
        ActionContext ctx = ActionContext.getContext();
        String json = getRequestBody(ctx);
        System.out.println("Post中的json:"+json);        
        try {
            HttpServletResponse response = ServletActionContext.getResponse(); 
            response.setContentType("application/json;charset=utf-8");//转换成你需要接收字符的编码
            PrintWriter pw = response.getWriter();
            response_json = ipcSynchroService.getClientEventInfo(json);
            pw.print("result:"+response_json);
            pw.write(response_json.toString());
            pw.flush();
            pw.close();
            System.out.println("======================response_json===============================");
            System.out.println(response_json);
            return response_json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return NONE;
    }

如果前台或者另一个action中出现中文变成了?

那么看一下自己项目的web.xml文件

<filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- struts的过滤器(前端控制器) -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

注意!!!!一定要把字符过滤器写在struts过滤器的前面,不然不生效,

struts2给前台输出json字符串以及出现的中文变成问号的解决方法

原文:http://www.cnblogs.com/llynic/p/6613540.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!