工做中遇到這樣的場景:json
在過濾器中對請求中的參數進行一些檢查,若是不合法,直接經過response對象將自定義的異常對象以json格式相應給請求端:app
自定義的異常對象以下:post
ExceptionBody body = new ExceptionBody();
body.setCode(2);
body.setMsg("params is error!")
經過response對象響應:對象
response.setStatus(HttpStatus.OK.value());
response.setContentType("application/json;charset=UTF-8");
response.getOutputStream().write(JSONObject.toJSONBytes(body, SerializerFeature.QuoteFieldNames));
return;
經過如上代碼過濾器就可已將用戶自定義的信息以json格式響應給請求端了……get
在此擴展一下,將post請求的數據解析成jsonObject(com.alibaba.fastjson.JSONObject):it
int length = request.getContentLength(); byte[] bytesBody = new byte[length]; request.getInputStream().read(bytesBody, 0, length); JSONObject jsonObject = JSONObject.parseObject(new String(bytesBody)); String sign = jsonObject.getString("sign");