對於ajax請求,後端不能直接返回頁面的處理方式
阿新 • • 發佈:2019-01-24
對於前後端分離的情況下,ajax請求在過濾器和攔截器中,都不能直接返回頁面,那麼應該怎麼處理呢?
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
ObjectMapper mapper = new ObjectMapper();
ajaxJson ajaxJson = new AjaxJson();
ajaxJson .setSuccess(false);
ajaxJson .setMessage(code);
String errorMsg = mapper.writeValueAsString(ajaxJson);
writer.write(errorMsg);
writer.flush();
} catch (Exception ex) {
LOGGER.error("輸出錯誤響應資訊異常:" + ex.getMessage());
throw new RuntimeException("輸出錯誤響應資訊異常:" + ex.getMessage(), ex);
} finally {
if (writer != null) {
writer.close();
}
}
}