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