使用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. 服务是如何加载并运行的, Kestrel、配置与环境

    服务是如何加载并运行的, Kestrel.配置与环境 "跨平台"后的ASP.Net Core是如何接收并处理请求的呢? 它的运行和处理机制和之前有什么不同? 本章从"宏观 ...

  2. 健康检查NET Core之跨平台的实时性能监控

    ASP.NET Core之跨平台的实时性能监控(2.健康检查)   前言 上篇我们讲了如何使用App Metrics 做一个简单的APM监控,最后提到过健康检查这个东西. 这篇主要就是讲解健康检查的内 ...

  3. 转Keil 中使用 STM32F4xx 硬件浮点单元

    Keil 中使用 STM32F4xx 硬件浮点单元一.前言有工程师反应说 Keil 下无法使用 STM32F4xx 硬件浮点单元, 导致当运算浮点时运算时间过长,还有 一些人反应不知如何使用芯片芯片内 ...

  4. 1550: Simple String 最大流解法

    http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1550 很久以前做的一题,当时队友用最大流做,现在我也是 这个转化为二分图多重匹配,就是一样的意 ...

  5. tyvj P4879骰子游戏-美国70分

    需要FFT优化... #include<iostream> #include<cstdio> #include<queue> #include<vector& ...

  6. Angular2中实现基于TypeScript的对象合并方法:extend()

    TypeScript里面没有现成的合并对象的方法,这里借鉴jQuery里的$.extend()方法.写了一个TypeScript的对象合并方法,使用方法和jQuery一样. 部分代码和jQuery代码 ...

  7. CSS grid layout demo 网格布局实例

    直接 上代码,里面我加注释,相当的简单, 也可以去我的github上直接下载代码,顺手给个星:https://github.com/yurizhang/micro-finance-admin-syst ...

  8. android应用开发全程实录-你有多熟悉listview?

    今天给大家带来<android应用开发全程实录>中关于listview和adatper中的部分.包括listview的基本使用,listview的优化等. 我们经常会在应用程序中使用列表的 ...

  9. 使用history.replaceState 修改url 不跳转

    history.replaceState(null,null,this.urlR);  //关键代码 history.replaceState是将指定的URL替换当前的URL 注意:用于替换掉的URL ...

  10. 微信小程序中的target和currentTarget区别

    最近在学习微信小程序相关知识,其中提到了两个属性target和currentTarget,其中target是指向触发事件的元素(常见于事件委托中),而currentTarget是指向捕获事件的元素(即 ...