使用Spring MVC后实现一个BaseController
使用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的更多相关文章
- Spring MVC 原理探秘 - 一个请求的旅行过程
1.简介 在前面的文章中,我较为详细的分析了 Spring IOC 和 AOP 部分的源码,并写成了文章.为了让我的 Spring 源码分析系列文章更为丰富一些,所以从本篇文章开始,我将来向大家介绍一 ...
- 使用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 ...
- Spring学习之第一个Spring MVC程序(IDEA开发环境)
回顾Java平台上Web开发历程来看,从Servlet出现开始,到JSP繁盛一时,然后是Servlet+JSP时代,最后演化为现在Web开发框架盛行的时代.一般接触到一个新的Web框架,都会想问这个框 ...
- 编写第一个spring MVC程序
一.下载和安装spring框架 进入http://repo.springsource.org/libs-release-local/org/springframework/spring/4.2.0.R ...
- Spring MVC基础入门
Spring MVC简介 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱 ...
- Spring学习笔记之五----Spring MVC
Spring MVC通常的执行流程是:当一个Web请求被发送给Spring MVC Application,Dispatcher Servlet接收到这个请求,通过HandlerMapping找到Co ...
- spring mvc拦截器
Java里的拦截器是动态拦截Action调用的对象.它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取act ...
- Spring MVC 入门示例讲解
在本例中,我们将使用Spring MVC框架构建一个入门级web应用程序.Spring MVC 是Spring框架最重要的的模块之一.它以强大的Spring IoC容器为基础,并充分利用容器的特性来简 ...
- spring mvc 基于注解的使用总结
本文转自http://blog.csdn.net/lufeng20/article/details/7598801 概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Sprin ...
随机推荐
- 实验一 用户界面与Shell命令
一.实验课时:2学时 二.实验目的 v 熟悉redhat_linux的用户界面,会进行常用的系统设置. v 掌握常用的shell命令. 三.实验环境 v 运行Windows xp\2000\20 ...
- Django模板语言,标签整理
Django模板语言 标签 内置标签引用 1. autoescape 控制自动转义是否可用. 这种标签带有任何 on 或 off 作为参数的话,他将决定转义块内效果. 该标签会以一个endautoes ...
- HDU-1150-MachineSchedule(二分图匹配)
链接:https://vjudge.net/problem/HDU-1150#author=0 题意: 在一个工厂,有两台机器A,B生产产品.A机器有n种工作模式(模式0,模式1....模式n-1). ...
- build spark
Error : Failed to find Spark jars directory (/home/pl62716/spark-2.2.0-SNAPSHOT/assembly/target/scal ...
- (转)Linux基础知识学习
Linux基础知识学习 原文:http://blog.csdn.net/ye_wei_yang/article/details/52777499 一.Linux的磁盘分区及目录 Linux的配置是通过 ...
- memcache和iptables开启11211端口
linux下安装完memcached后,netstat -ant | grep LISTEN 看到memcache用的11211端口已在监听状态,但建立php文件连接测试发现没有输出结果,iptabl ...
- 在MasterPage中检验session是否存在~
在母板頁中檢查user是否登入過,這樣就不用在每個頁中去作檢驗.在其Init事件中寫入如下代碼: protected void ContentPlaceHolder1_Init(object ...
- Git、Github和GitLab的区别及与SVN的比较
个人理解: SVN适合领导啊,大家一起在加班,看你进度什么的,git则不必如此,忙完传上来完活. 一.含义: 百度上这样介绍的: Git(读音为/gɪt/.)是一个开源的分布式版本控制系统,可以有效. ...
- 【Linux】Ubuntu配置zshell&oh-my-zsh
zshell:https://archive.codeplex.com/?p=shell oh-my-zsh: https://github.com/robbyrussell/oh-my-zsh 终极 ...
- CSS中的定位机制
CSS3 中有三种定位机制 : 普通文档流 (text)| 浮动(float) | 定位(position) 普通文档流 就是CSS中默认的文本文档 普通流中,元素位置由文档顺序和元素性质决定,块级元 ...