1、通过静态方法获取 HttpServletRequest
/*** 从DispatcherServlet中获取到当前的request* @return*/public static HttpServletRequest getRequest() {// 从当前threadlocal中获取到ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();return servletRequestAttributes.getRequest();}
2、通过静态方法获取 HttpServletResponse
/*** 从DispatcherServlet中获取到当前的response* @return*/public static HttpServletResponse getResponse() {// 从当前threadlocal中获取到ServletWebRequest servletRequestAttributes = (ServletWebRequest)RequestContextHolder.getRequestAttributes();return servletRequestAttributes.getResponse();}
3、response 写出json数据
/*** 写出json数据,任意数据类型* */public static void writeJsonToObj(HttpServletResponse response, Object obj) {response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try {out = response.getWriter(); out.write(JSONObject.toJSONString(obj));out.flush();} catch (IOException e) {e.printStackTrace();throw new IllegalStateException("IO异常,:" + e.getMessage());} finally {if (out != null)out.close();}}