摘要:这个题目看着挺荒唐的,200已经请求成功了怎么就给改成其他的失败呢?其实这里只是更好的能认识response而已,指不定哪天你能用到呢。
这个代码是我用来返回response用的,这里写一下设置response,主要是体现设置返回状态码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class ReturnJson {
public static void returnJson(HttpServletResponse response) throws Exception{
CommonResponse commonResponse = CommonResponseUtils.error( CommonResponseEnum.ERROE_USER__NO_LOGIN.getCode(), errorMsg ); String res = JSONUtil.toJsonStr(commonResponse);
PrintWriter writer = null; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Allow-Headers","*"); response.setHeader("Access-Control-Allow-Credentials", "true");
response.setStatus(HttpServletResponse.SC_OK); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); try { writer = response.getWriter(); writer.print(res);
} catch (IOException e) {
} finally { if (writer != null){ writer.flush(); writer.close(); } } }
}
|
response.setStatus(HttpServletResponse.SC_OK);这个方法就是设置返回状态的
其实这个方法是用来在拦截到没有登陆的用户后,返回一段后台定义的错误描述