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


    使用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过滤器的前面,不然不生效,

  • 相关阅读:
    18.10.29 考试总结
    【BZOJ】2730: [HNOI2012]矿场搭建
    BZOJ [ZJOI2007]仓库建设
    18.10.24 考试总结
    ZOJ 3740 Water Level
    洛谷 P2474 [SCOI2008]天平
    洛谷 P4180 【模板】严格次小生成树[BJWC2010]
    CF961E Tufurama
    18.10.22 考试总结
    18.10.19 考试总结
  • 原文地址:https://www.cnblogs.com/llynic/p/6613540.html
Copyright © 2020-2023  润新知