记一次@ResponseBody注解返回中文乱码的问题

Bug场景

前端AJax

    $.ajax({
        url: '$!{request.getContextPath()}/XX/save.do',
        type: 'post',
        dataType: 'json',
        data: $("#msg-form").serialize(),
        success: function (data) {
            if (data.success == "true" || data.success == true) {
                Toast.show({
                    template: "添加成功",
                    second: 1000,
                    callback: function () {
                        window.parent.location.reload();
                    }
                });
            }else {
                $("#submitButton").removeAttr("disabled");
                Toast.show({
                    template: data.msg,
                });

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $("#submitButton").removeAttr("disabled");
            Toast.show("[服务器异常]" + XMLHttpRequest.status);
        }
    });

后端接口

	@ResponseBody
	@RequestMapping(value = "/save.do")
	public void savePushJob(PushJob pushJob, HttpServletRequest request, HttpServletResponse response){

		String jsonFmt = "{\"success\":%s,\"msg\":\"%s\"}";
		String json = "";

		try{
			//校验落地页有效性
			String msg = this.checkParams(pushJob);
			if(StringUtil.isNotBlank(msg)){
				json = String.format(jsonFmt, false, msg);
				ResponseJsonUtil.writeJson2Response(json, request, response);
				return;
			}

			json = String.format(jsonFmt, true, "");
			ResponseJsonUtil.writeJson2Response(json, request, response);
			return;
		}catch (Exception e){
			e.printStackTrace();
			json = String.format(jsonFmt, false, "系统异常");
			ResponseJsonUtil.writeJson2Response(json, request, response);
			return;
		}

	}
	
	
//code 2
	/**
	 * 将JSON字符串写到输出流
	 * @author zhaoyang	
	 * @date 2015年5月6上午8:28:44 
	 * @param json
	 * @param request
	 * @param response
	 */
	public static void writeJson2Response(String json,HttpServletRequest request,HttpServletResponse response){
		String cb=request.getParameter("jsoncallback");
		if (!StringUtils.isEmpty(cb)) {
		    response.setContentType("text/javascript");
		    json = cb + "(" + json + ");";
		} else {
		    response.setContentType("text/json");
		}
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			log.error("将JSON字符串写到输出流时出错", e);
		}
	}

描叙

-如上图code,接口返回中文的错误提示时,ajax直接报错进入 error ,

之前,接口有直接返回一个String,包含中文则是乱码

	return JsonUtil.toJson("success");

code 片段 2

	 /**
     * 将一个对象编码为json字符串
     * 
     * @param obj ,if null return "null"
     *            要编码的字符串
     * @return json字符串
     * @throws RuntimeException
     *             若对象不能被编码为json串
     */
    public static String toJson(Object obj) {
	if (obj == null) {
	    return null;
	}
	try {
	    return MAPPER.writeValueAsString(obj);
	} catch (Exception e) {
	    throw new RuntimeException("error encode json for " + obj, e);
	}
    }

解决方法

方法1.移除@ResponseBody

方法2 @RequestMapping 添加 produces

@RequestMapping(value = "/save.do",produces = "application/json;charset=utf-8")

其他方法

这里是没有验证的 https://blog.csdn.net/zknxx/article/details/52423608

扩展

1.@ResponseBody 的作用

2.@ResponseBody 为什么未出现中文乱码

posted @ 2018-07-26 20:43  谢幕ゾ华丽  阅读(272)  评论(0编辑  收藏  举报