使用Spring MVC技术后,可以实现一个基类的Controller类来分装一些MVC常用的方法,其他的Controller都继承自这个BaseController,这样在使用常用的方法时将会变得非常轻松。
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:
https://www.cnblogs.com/poterliu/p/9142637.html
下面给出这个BaseController和涉及到的工具类的源码。
BaseController类
package com.xxx.yyy.portal.controller; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.xxx.yyy.portal.utils.JsonUtil; public class BaseController { @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); CustomDateEditor dateEditor = new CustomDateEditor(format, true); binder.registerCustomEditor(Date.class, dateEditor); } public Object getAttribute(String attributeName) { return this.getRequest().getAttribute(attributeName); } public void setAttribute(String attributeName, Object object) { this.getRequest().setAttribute(attributeName, object); } public Object getSession(String attributeName) { return this.getRequest().getSession(true).getAttribute(attributeName); } public void setSession(String attributeName, Object object) { this.getRequest().getSession(true).setAttribute(attributeName, object); } public HttpServletRequest getRequest() { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); return ((ServletRequestAttributes) ra).getRequest(); } public HttpServletResponse getResponse(){ RequestAttributes ra = RequestContextHolder.getRequestAttributes(); return ((ServletRequestAttributes) ra).getResponse(); } public HttpSession getSession() { return this.getRequest().getSession(true); } public String getParameter(String paraName) { return this.getRequest().getParameter(paraName); } /** * 获取表单格式数据(或url拼接参数) * @return */ @SuppressWarnings("rawtypes") public Map getParameterMap(){ return this.getRequest().getParameterMap(); } public String getHeader(String headerName) { return this.getRequest().getHeader(headerName); } @SuppressWarnings({ "rawtypes", "unchecked" }) public Map getHeaderMap() { Enumeration headerNames = this.getRequest().getHeaderNames(); Map headerMap = new HashMap<>(); while(headerNames.hasMoreElements()){ String headerName = (String) headerNames.nextElement(); String headerValue = getRequest().getHeader(headerName); headerMap.put(headerName, headerValue); } return headerMap; } public String getIpAddress(){ String ip = this.getRequest().getRemoteAddr(); return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip; } /** * 获取json格式数据 * @return */ @SuppressWarnings("unchecked") public Map<String, Object> getRequestMap(){ try { InputStream inStream = this.getRequest().getInputStream(); //默认为json BufferedReader in = new BufferedReader(new InputStreamReader(inStream , "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String buffer = ""; while(null!=(buffer=(in.readLine()))){ stringBuffer.append(buffer); } String reqDoc = stringBuffer.toString(); if(reqDoc==null||reqDoc.equals("")){ return null; } return JsonUtil.toMap(reqDoc) ; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 允许跨域访问 */ public void allowCrossDomainAccess(){ HttpServletResponse servletResponse = getResponse(); servletResponse.setHeader("Access-Control-Allow-Origin", "*"); servletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET"); servletResponse.setHeader("Access-Control-Allow-Headers:x-requested-with", "content-type"); } }
BaseController类使用到了一个json工具类JsonUtil
package com.xxx.yyy.portal.utils; 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")); } 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); } 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类中,这样不仅使用方便,提高开发效率,更重要达到了代码复用的目的,这是面向对象思想编程所推荐的。