使用 Spring MVC 后实现一个 BaseController 和 JsonUtil
使用Spring MVC技术后,可以实现一个基类的Controller类来分装一些MVC常用的方法,其他的Controller都继承自这个BaseController,这样在使用常用的方法时将会变得非常轻松。
需要在 maven 中引入的 依赖包如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.4.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.11</version> </dependency> <!--json--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.11.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.3</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
下面给出这个BaseController和涉及到的工具类的源码。
BaseController类
1 import java.io.BufferedReader; 2 import java.io.InputStream; 3 import java.io.InputStreamReader; 4 import java.net.InetAddress; 5 import java.net.UnknownHostException; 6 import java.text.DateFormat; 7 import java.text.SimpleDateFormat; 8 import java.util.Date; 9 import java.util.Enumeration; 10 import java.util.HashMap; 11 import java.util.Map; 12 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 import javax.servlet.http.HttpSession; 16 17 import org.apache.commons.lang3.StringUtils; 18 import org.springframework.beans.propertyeditors.CustomDateEditor; 19 import org.springframework.web.bind.ServletRequestDataBinder; 20 import org.springframework.web.bind.annotation.InitBinder; 21 import org.springframework.web.context.request.RequestAttributes; 22 import org.springframework.web.context.request.RequestContextHolder; 23 import org.springframework.web.context.request.ServletRequestAttributes; 24 25 import com.xxx.pbm.portal.utils.JsonUtil; 26 27 public class BaseController { 28 @InitBinder 29 protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { 30 DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 31 CustomDateEditor dateEditor = new CustomDateEditor(format, true); 32 binder.registerCustomEditor(Date.class, dateEditor); 33 } 34 35 public Object getAttribute(String attributeName) { 36 return this.getRequest().getAttribute(attributeName); 37 } 38 39 public void setAttribute(String attributeName, Object object) { 40 this.getRequest().setAttribute(attributeName, object); 41 } 42 43 public Object getSession(String attributeName) { 44 return this.getRequest().getSession(true).getAttribute(attributeName); 45 } 46 47 public void setSession(String attributeName, Object object) { 48 this.getRequest().getSession(true).setAttribute(attributeName, object); 49 } 50 51 public HttpServletRequest getRequest() { 52 RequestAttributes ra = RequestContextHolder.getRequestAttributes(); 53 return ((ServletRequestAttributes) ra).getRequest(); 54 } 55 56 public HttpServletResponse getResponse() { 57 RequestAttributes ra = RequestContextHolder.getRequestAttributes(); 58 return ((ServletRequestAttributes) ra).getResponse(); 59 } 60 61 public HttpSession getSession() { 62 return this.getRequest().getSession(true); 63 } 64 65 public String getParameter(String paraName) { 66 return this.getRequest().getParameter(paraName); 67 } 68 69 /** 70 * 获取表单格式数据(或url拼接参数) 71 * 72 * @return 73 */ 74 @SuppressWarnings("rawtypes") 75 public Map getParameterMap() { 76 return this.getRequest().getParameterMap(); 77 } 78 79 public String getHeader(String headerName) { 80 return this.getRequest().getHeader(headerName); 81 } 82 83 @SuppressWarnings({ "rawtypes", "unchecked" }) 84 public Map getHeaderMap() { 85 Enumeration headerNames = this.getRequest().getHeaderNames(); 86 Map headerMap = new HashMap<>(); 87 while (headerNames.hasMoreElements()) { 88 String headerName = (String) headerNames.nextElement(); 89 String headerValue = getRequest().getHeader(headerName); 90 headerMap.put(headerName, headerValue); 91 } 92 return headerMap; 93 } 94 95 public String getIpAddress() { 96 // String ip = this.getRequest().getRemoteAddr(); 97 // return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip; 98 HttpServletRequest request = getRequest(); 99 String ip = request.getHeader("X-Forwarded-For"); 100 if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { 101 // 多次反向代理后会有多个ip值,第一个ip才是真实ip 102 int index = ip.indexOf(","); 103 if (index != -1) { 104 return ip.substring(0, index); 105 } else { 106 return ip; 107 } 108 } 109 ip = request.getHeader("X-Real-IP"); 110 if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { 111 return ip; 112 } 113 return request.getRemoteAddr(); 114 } 115 116 /** * 获取服务器ip地址 * @return */ 117 public String getServerIpAddress() { 118 InetAddress address; 119 String serverIpAddress = null; 120 try { 121 address = InetAddress.getLocalHost(); // 获取的是本地的IP地址 122 // PC-20140317PXKX/192.168.0.121 123 serverIpAddress = address.getHostAddress();// 192.168.0.121 124 } catch (UnknownHostException e) { 125 e.printStackTrace(); 126 } 127 return serverIpAddress; 128 } 129 130 /** * 获取json格式数据 * @return */ 131 @SuppressWarnings("unchecked") 132 public Map<String, Object> getRequestMap(){ 133 try { 134 InputStream inStream = this.getRequest().getInputStream(); //默认为json 135 BufferedReader in = new BufferedReader(new InputStreamReader(inStream , "UTF-8")); 136 StringBuffer stringBuffer = new StringBuffer(); String buffer = ""; 137 while(null!=(buffer=(in.readLine()))){ 138 stringBuffer.append(buffer); 139 } 140 String reqDoc = stringBuffer.toString(); 141 if(reqDoc==null||reqDoc.equals("")){ 142 return null; 143 } 144 return JsonUtil.toMap(reqDoc) ; 145 } catch (Exception e) { e.printStackTrace(); } return null; 146 147 } 148 149 /** * 允许跨域访问 */ 150 public void allowCrossDomainAccess(){ 151 HttpServletResponse servletResponse = getResponse(); 152 servletResponse.setHeader("Access-Control-Allow-Origin", "*"); 153 servletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET"); 154 servletResponse.setHeader("Access-Control-Allow-Headers:x-requested-with", "content-type"); 155 } 156 }
BaseController类使用到了一个json工具类JsonUtil
package com.poterliu.util; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import net.sf.json.JSONObject; public class JsonUtil { private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_EMPTY); mapper.setDateFormat(new SimpleDateFormat("yyyyMMddHHmmss")); } /** * 调用格式示范: * JsonUtil.json2ObjectByTr(jsonStr, new TypeReference<List<Map>>() {}) */ public static <T> T json2ObjectByTr(String str, TypeReference<T> tr) throws JsonParseException, JsonMappingException, IOException { return mapper.readValue(str, tr); } public static String Object2Json(Object obj) throws JsonProcessingException { return mapper.writeValueAsString(obj); } /** * 全部使用 json2ObjectByTr 方法进行转换,此方法已过时,容易造成类型转换错误 */ @Deprecated public static Map toMap(String jsonString) { Map result = new HashMap(); try { String key = null; String value = null; JSONObject jsonObject = JSONObject.fromObject(jsonString); Iterator iterator = jsonObject.keys(); while (iterator.hasNext()) { key = (String) iterator.next(); value = jsonObject.getString(key); result.put(key, value); } } catch (Exception e) { e.printStackTrace(); } return result; } public static Gson getGson(){ Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); return gson; } public static Map fromJson(String json){ return getGson().fromJson(json,new TypeToken<HashMap<String, Object>>(){}.getType()); } public static String toJson(Object object){ return getGson().toJson(object); } }
当然了,BaseController类可以封装的方法还有很多,只要在项目的Controller中用得比较多的方法最好都封装到BaseController类中,这样不仅使用方便,提高开发效率,更重要达到了代码复用的目的,这是面向对象思想编程所推荐的。
原文地址:
https://www.cnblogs.com/poterliu/p/9268024.html