1. resp.setCharacterEncoding("utf-8");
    2. resp.setContentType("application/json; charset=utf-8");
    3. PrintWriter writer = resp.getWriter();
    4. JSONObject o = new JSONObject();
    5. o.put("status", "success");
    6. writer.write(o.toString());

    这点可以与异常处理相配合,当发生异常时,使用上述方法返回给前端指定信息

    1. try {
    2. // 判断该请求是不是受保护的请求
    3. if(isProtectedUrl(request)) {
    4. // Options请求可以不用校验,其他诸如Get、Post等请求都要校验
    5. if(!request.getMethod().equals("OPTIONS"))
    6. // 校验是否带有有效token
    7. request = JwtUtil.validateTokenAndAddUserIdToHeader(request);
    8. }
    9. } catch (CustomException e) {
    10. response.setCharacterEncoding("utf-8");
    11. response.setContentType("application/json; charset=utf-8");
    12. PrintWriter writer =response.getWriter();
    13. JSONObject o = new JSONObject();
    14. o.put("code", e.getId());
    15. o.put("message", e.getMessage());
    16. writer.write(o.toString());
    17. return;
    18. }

    image.png