【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】03、创建RESTful API,并统一处理返回值
时间:2022-03-15 08:50
1、POM文件引入fastJson依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.38</version> </dependency>
2、添加几个关于HTTP和JSON的工具类
package com.ltsolution.framework.util; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LTHttpUtil { /** * 判断请求是否Ajax请求 * * @param request * @return */ public static boolean isAjax(ServletRequest request) { String header = ((HttpServletRequest) request).getHeader("x-requested-with"); if (header != null && header.equalsIgnoreCase("XMLHttpRequest")) { return true; } return false; } public static HttpServletRequest getRequest(ServletRequest request) { return new XssSqlHttpServletRequestWrapper((HttpServletRequest) request); } public static Map<String, String> getRequestHeaders(ServletRequest request) { Map<String, String> headerMap = new HashMap<>(); @SuppressWarnings("rawtypes") Enumeration enums = LTHttpUtil.getRequest(request).getHeaderNames(); while (enums.hasMoreElements()) { String name = (String) enums.nextElement(); String value = LTHttpUtil.getRequest(request).getHeader(name); if (null != value && !"".equals(value)) { headerMap.put(name, value); } } return headerMap; } /** * 读取ServletRequest请求的正文 * * @param request * @return */ @SuppressWarnings("unchecked") public static Map<String, String> getRequestBodyMap(ServletRequest request) { // 通过ServletRequest.getInputStream()可以获取到请求的正文 // 然后放置到请求的body变量中,方便在该请求的生命周期中使用,也避免多次读取 Map<String, String> dataMap = new HashMap<>(); try { if (request.getAttribute("body") != null) { dataMap = (Map<String, String>) request.getAttribute("body"); } else { // 原因https://www.cnblogs.com/wtstengshen/p/3186530.html // 因为ServletRequest的InputStream只能读取一次,所以登录的时候,这里读取了,登录方法就不能使用@RequestBody了 ServletInputStream steam = request.getInputStream(); Map<String, String> maps = LTJSON.parseObject(steam, Map.class); dataMap.putAll(maps); System.out.println(dataMap); request.setAttribute("body", dataMap); } } catch (Exception e) { System.out.println(e.getMessage()); } return dataMap; } /** * 如果是POST请求,且URL地址结尾是/login(不分大小写),则返回true * * @param request * @return */ public static boolean isLoginPost(ServletRequest request) { // 然后放置到请求的isLoginPost变量中,方便在该请求的生命周期中使用,也避免多次读取 boolean isLoginPost = false; if (request.getAttribute("isLoginPost") != null) { isLoginPost = (boolean) request.getAttribute("isLoginPost"); } else { HttpServletRequest httpRequest = (HttpServletRequest) request; String url = httpRequest.getRequestURL().toString(); url = url.substring(url.lastIndexOf("/") + 1, url.length()).toUpperCase(); String method = httpRequest.getMethod().toUpperCase(); if (url.equals("LOGIN") && method.equals("POST")) isLoginPost = true; request.setAttribute("isLoginPost", isLoginPost); } return isLoginPost; } /** * 将过滤器中产生的异常以Json的形式返回给客户端 * * @param response * @param obj */ public static void ResponseWrite(ServletResponse response, Object obj) { PrintWriter out = null; try { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setStatus(401); httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType("application/json"); out = httpResponse.getWriter(); out.println(LTJSON.toJSONString(obj)); } catch (Exception e) { System.out.println(e); } finally { if (null != out) { out.flush(); out.close(); } } } }View Code
package com.ltsolution.framework.util; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; /** * @author Yang * @description 用于对JSON操作做一个封装,方便以后更换修改 */ public class LTJSON { /** * 对象转换为JSON * * @param object * @return */ public static final String toJSONString(Object object) { /* * QuoteFieldNames———-输出key时是否使用双引号,默认为true * WriteMapNullValue——–是否输出值为null的字段,默认为false * WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null * WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null * WriteNullStringAsEmpty—字符类型字段如果为null,输出为"",而非null * WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null */ return JSONObject.toJSONString(object, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullBooleanAsFalse); } /** * 输入流转换为对象 * * @param is * @param type * @param features * @return * @throws IOException */ @SuppressWarnings("unchecked") public static <T> T parseObject(InputStream is, // Type type, // Feature... features) throws IOException { T parseObject = (T) JSON.parseObject(is, type, features); return parseObject; } }View Code View Code View Code
3、创建一个数据对象,用来统一RESTful API的返回格式
package com.ltsolution.framework.common.msgmodel; import java.util.HashMap; import java.util.Map; public class AppResult { private String status; private String error; private String message; private Map<String, Object> data = new HashMap<String, Object>(); public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> data) { this.data = data; } public AppResult ok(String statusMsg) { this.status="200"; this.message=statusMsg; return this; } public AppResult error(String statusMsg) { this.status="500"; this.message=statusMsg; return this; } public AppResult addData(String key,Object object) { this.data.put(key,object); return this; } }View Code
4、创建RESTful控制器
@RestController @RequestMapping(value = "/") public class UserController { @PostMapping("/login") public AppResult login(HttpServletRequest request, HttpServletResponse response) throws Exception { return new AppResult().ok("登录成功!").addData("token", 1234); } @PostMapping("/test") public AppResult test(HttpServletRequest request, HttpServletResponse response) throws Exception { return new AppResult().ok("测试!"); } }
5、测试API