使用Spring MVC技术后,可以实现一个基类的Controller类来分装一些MVC常用的方法,其他的Controller都继承自这个BaseController,这样在使用常用的方法时将会变得非常轻松。

下面给出这个BaseController和涉及到的工具类的源码。

BaseController类

 import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
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.apache.commons.lang3.StringUtils;
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.pbm.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;
HttpServletRequest request = getRequest();
String ip = request.getHeader("X-Forwarded-For");
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = ip.indexOf(",");
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
return ip;
}
return request.getRemoteAddr();
} /** * 获取服务器ip地址 * @return */
public String getServerIpAddress() {
InetAddress address;
String serverIpAddress = null;
try {
address = InetAddress.getLocalHost(); // 获取的是本地的IP地址
// PC-20140317PXKX/192.168.0.121
serverIpAddress = address.getHostAddress();// 192.168.0.121
} catch (UnknownHostException e) {
e.printStackTrace();
}
return serverIpAddress;
} /** * 获取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

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类中,这样不仅使用方便,提高开发效率,更重要达到了代码复用的目的,这是面向对象思想编程所推荐的。

原文地址:

https://www.cnblogs.com/poterliu/p/9268024.html

使用Spring MVC后实现一个BaseController的更多相关文章

  1. Spring MVC 原理探秘 - 一个请求的旅行过程

    1.简介 在前面的文章中,我较为详细的分析了 Spring IOC 和 AOP 部分的源码,并写成了文章.为了让我的 Spring 源码分析系列文章更为丰富一些,所以从本篇文章开始,我将来向大家介绍一 ...

  2. 使用Maven创建一个Spring MVC Web 项目

    使用Maven创建java web 项目(Spring MVC)用到如下工具: 1.Maven 3.2 2.IntelliJ IDEA 13 3.JDK 1.7 4.Spring 4.1.1 rele ...

  3. Spring学习之第一个Spring MVC程序(IDEA开发环境)

    回顾Java平台上Web开发历程来看,从Servlet出现开始,到JSP繁盛一时,然后是Servlet+JSP时代,最后演化为现在Web开发框架盛行的时代.一般接触到一个新的Web框架,都会想问这个框 ...

  4. 编写第一个spring MVC程序

    一.下载和安装spring框架 进入http://repo.springsource.org/libs-release-local/org/springframework/spring/4.2.0.R ...

  5. Spring MVC基础入门

    Spring MVC简介 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱 ...

  6. Spring学习笔记之五----Spring MVC

    Spring MVC通常的执行流程是:当一个Web请求被发送给Spring MVC Application,Dispatcher Servlet接收到这个请求,通过HandlerMapping找到Co ...

  7. spring mvc拦截器

    Java里的拦截器是动态拦截Action调用的对象.它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取act ...

  8. Spring MVC 入门示例讲解

    在本例中,我们将使用Spring MVC框架构建一个入门级web应用程序.Spring MVC 是Spring框架最重要的的模块之一.它以强大的Spring IoC容器为基础,并充分利用容器的特性来简 ...

  9. spring mvc 基于注解的使用总结

    本文转自http://blog.csdn.net/lufeng20/article/details/7598801 概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Sprin ...

随机推荐

  1. A Simple Math Problem (矩阵快速幂)

    Lele now is thinking about a simple function f(x).  If x < 10 f(x) = x.  If x >= 10 f(x) = a0 ...

  2. build spark

    Error : Failed to find Spark jars directory (/home/pl62716/spark-2.2.0-SNAPSHOT/assembly/target/scal ...

  3. 去掉word文档两边的空白

    1.设置-页面布局-页边距,把左边距和右边距的数据设置到最小就好,一般为0.43CM 2.把WORD页面顶部标尺,左右拉到最底,如图: 3.在打印预览里,设置页边距,操作方法同 上述 1,如图:

  4. HTTP状态码完整版

    HTTP 状态代码的完整列表   1xx(临时响应) 用于表示临时响应并需要请求者执行操作才能继续的状态代码. 代码 说明 100(继续) 请求者应当继续提出请求.服务器返回此代码则意味着,服务器已收 ...

  5. 利用Vagrant and VirtualBox搭建core os环境

    利用Vagrant and VirtualBox搭建core os环境 系统环境 ubuntu 14.04 x64 vagrant 1.7.4 virtualbox 4.3.10 git 1.9.1 ...

  6. vue-cli3脚手架的配置以及使用

    Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统,提供: 通过 @vue/cli 搭建交互式的项目脚手架. 通过 @vue/cli + @vue/cli-service-global  ...

  7. mitmweb的使用

    安装mitmproxy时带有mitmweb,可直接在命令行输入命令:mitmweb 此时可打开web界面.

  8. Outlook 客户端无法通过 MAPI over HTTP协议 连接

    随着Exchange 版本更新升级,是否进行验证客户端建立MapiHttp连接所需的服务器设置已正确配置.即使服务器,负载均衡器和反向代理的所有设置都正确,您可能会遇到连接到Exchange Serv ...

  9. Protocol Buffer学习教程之开篇概述(一)

    1. Protocol Buffer是什么 Protocol Buffer是google旗下的产品,用于序列化与反序列化数据结构,但是比xml更小.更快.更简单,而且能跨语言.跨平台.你可以把你的数据 ...

  10. SQL_关联映射

    关联映射:一对多/多对一 存在最普遍的映射关系,简单来讲就如球员与球队的关系: 一对多:从球队角度来说一个球队拥有多个球员 即为一对多 多对一:从球员角度来说多个球员属于一个球队 即为多对一 数据表间 ...