在 SSM(三)公共Common模块的抽离(1) 文章中,对COMMON模块已经作了简单配置,下面将介绍如何抽取基础的增删改查模块,以便在各个WEB中复用。
参照前面的文章开始部分新建W3CJAVA-WEB-COMMON模块,可以看到如下图的项目目录结构:
之所以又单独新建一个W3CJAVA-WEB-COMMON模块,是为了将此模块作为WEB开发时使用,当然W3CJAVA-WEB-COMMON中添加了W3CJAVA-COMMON依赖,这样,W3CJAVA-COMMON则可以复用了。
因为此模块主要是提供给WEB使用,所以需要从W3CJAVA-WEB的pom.xml中将对应的Spring、SpringMVC、Mybatis等依赖的jar包都复制到这里,而W3CJAVA-WEB只要依赖这个jar包即可。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<artifactId>W3cJavaSSMartifactId>
<groupId>com.w3cjavagroupId>
<version>0.0.1-SNAPSHOTversion>
parent>
<artifactId>W3CJAVA-WEB-COMMONartifactId>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>com.w3cjavagroupId>
<artifactId>W3CJAVA-COMMONartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<scope>providedscope>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
dependency>
dependencies>
project>
添加W3CJAVA-WEB-COMMON依赖。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.w3cjavagroupId>
<artifactId>W3cJavaSSMartifactId>
<version>0.0.1-SNAPSHOTversion>
<relativePath/>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>W3CJAVA-WEBartifactId>
<packaging>warpackaging>
<dependencies>
<dependency>
<groupId>com.w3cjavagroupId>
<artifactId>W3CJAVA-WEB-COMMONartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
dependencies>
project>
一般这个模块会放一些工具类,Json相关的类,以下工具类不用深究每个方法的用途,这只是博主开发过程中常用的方法,所以都封装到一起了。
com.w3cjava.common.utils包下
package com.w3cjava.common.utils;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
*
* @version TODO
* @author heartma
* @date 2018年4月21日
* @File DateUtils.java
* @URL www.w3cjava.com
* @Desc 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = { "yyyy-MM-dd",
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd",
"yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM" };
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy.MM.dd",
* "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
*
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (24 * 60 * 60 * 1000);
}
/**
* 获取过去的小时
*
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (60 * 60 * 1000);
}
/**
* 获取过去的分钟
*
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (60 * 1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
*
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis) {
long day = timeMillis / (24 * 60 * 60 * 1000);
long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60
* 1000 - min * 60 * 1000 - s * 1000);
return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "."
+ sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
// System.out.println(time/(24*60*60*1000));
}
}
package com.w3cjava.common.utils;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringEscapeUtils;
import com.google.common.collect.Lists;
/**
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
*
* @author jeeplus
* @version 2013-05-22
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 转换为字节数组
*
* @param str
* @return
*/
public static byte[] getBytes(String str) {
if (str != null) {
try {
return str.getBytes(CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return null;
}
} else {
return null;
}
}
/**
* 转换为字节数组
*
* @param str
* @return
*/
public static String toString(byte[] bytes) {
try {
return new String(bytes, CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return EMPTY;
}
}
/**
* 是否包含字符串
*
* @param str
* 验证字符串
* @param strs
* 字符串组
* @return 包含返回true
*/
public static boolean inString(String str, String... strs) {
if (str != null) {
for (String s : strs) {
if (str.equals(trim(s))) {
return true;
}
}
}
return false;
}
/**
* 替换掉HTML标签方法
*/
public static String replaceHtml(String html) {
if (isBlank(html)) {
return "";
}
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param html
* @return
*/
public static String replaceMobileHtml(String html) {
if (html == null) {
return "";
}
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}
/**
* 缩略字符串(不区分中英文字符)
*
* @param str
* 目标字符串
* @param length
* 截取长度
* @return
*/
public static String abbr(String str, int length) {
if (str == null) {
return "";
}
try {
StringBuilder sb = new StringBuilder();
int currentLength = 0;
for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str))
.toCharArray()) {
currentLength += String.valueOf(c).getBytes("GBK").length;
if (currentLength <= length - 3) {
sb.append(c);
} else {
sb.append("...");
break;
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public static String abbr2(String param, int length) {
if (param == null) {
return "";
}
StringBuffer result = new StringBuffer();
int n = 0;
char temp;
boolean isCode = false; // 是不是HTML代码
boolean isHTML = false; // 是不是HTML特殊字符,如
for (int i = 0; i < param.length(); i++) {
temp = param.charAt(i);
if (temp == '<') {
isCode = true;
} else if (temp == '&') {
isHTML = true;
} else if (temp == '>' && isCode) {
n = n - 1;
isCode = false;
} else if (temp == ';' && isHTML) {
isHTML = false;
}
try {
if (!isCode && !isHTML) {
n += String.valueOf(temp).getBytes("GBK").length;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (n <= length - 3) {
result.append(temp);
} else {
result.append("...");
break;
}
}
// 取出截取字符串中的HTML标记
String temp_result = result.toString().replaceAll("(>)[^<>]*()",
"$1$2");
// 去掉不需要结素标记的HTML标记
temp_result = temp_result
.replaceAll(
"?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
"");
// 去掉成对的HTML标记
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)\\1>",
"$2");
// 用正则表达式取出标记
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
Matcher m = p.matcher(temp_result);
List endHTML = Lists.newArrayList();
while (m.find()) {
endHTML.add(m.group(1));
}
// 补全不成对的HTML标记
for (int i = endHTML.size() - 1; i >= 0; i--) {
result.append("");
result.append(endHTML.get(i));
result.append(">");
}
return result.toString();
}
/**
* 转换为Double类型
*/
public static Double toDouble(Object val) {
if (val == null) {
return 0D;
}
try {
return Double.valueOf(trim(val.toString()));
} catch (Exception e) {
return 0D;
}
}
/**
* 转换为Float类型
*/
public static Float toFloat(Object val) {
return toDouble(val).floatValue();
}
/**
* 转换为Long类型
*/
public static Long toLong(Object val) {
return toDouble(val).longValue();
}
/**
* 转换为Integer类型
*/
public static Integer toInteger(Object val) {
return toLong(val).intValue();
}
/**
* 驼峰命名法工具
*
* @return toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 驼峰命名法工具
*
* @return toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
return null;
}
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/**
* 驼峰命名法工具
*
* @return toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toUnderScoreCase(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 如果不为空,则设置值
*
* @param target
* @param source
*/
public static void setValueIfNotBlank(String target, String source) {
if (isNotBlank(source)) {
target = source;
}
}
/**
* 转换为JS获取对象值,生成三目运算返回结果
*
* @param objectString
* 对象串 例如:row.user.id
* 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
*/
public static String jsGetVal(String objectString) {
StringBuilder result = new StringBuilder();
StringBuilder val = new StringBuilder();
String[] vals = split(objectString, ".");
for (int i = 0; i < vals.length; i++) {
val.append("." + vals[i]);
result.append("!" + (val.substring(1)) + "?'':");
}
result.append(val.substring(1));
return result.toString();
}
}
com.w3cjava.common.json包
package com.w3cjava.common.json;
import java.util.LinkedHashMap;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.w3cjava.common.mapper.JsonMapper;
/**
*
* @version v1.0.0
* @author heartma
* @date 2017年12月27日
* @File AjaxJson.java
* @URL www.w3cjava.com
* @Desc $.ajax后需要接受的JSON
*/
public class AjaxJson {
private boolean success = true;// 是否成功
private String errorCode = "-1";// 错误代码
private String msg = "操作成功";// 提示信息
@SuppressWarnings({ "unchecked", "rawtypes" })
private LinkedHashMap body = new LinkedHashMap();// 封装json的map
public LinkedHashMap getBody() {
return body;
}
public void setBody(LinkedHashMap body) {
this.body = body;
}
public void put(String key, Object value) {// 向json中添加属性,在js中访问,请调用data.map.key
body.put(key, value);
}
public void remove(String key) {
body.remove(key);
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {// 向json中添加属性,在js中访问,请调用data.msg
this.msg = msg;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@JsonIgnore
// 返回对象时忽略此属性
public String getJsonStr() {// 返回json字符串数组,将访问msg和key的方式统一化,都使用data.key的方式直接访问。
String json = JsonMapper.getInstance().toJson(this);
return json;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
com.w3cjava.common.mapper包
package com.w3cjava.common.mapper;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
*
* @version TODO
* @author heartma
* @date 2017年12月27日
* @File JsonMapper.java
* @URL www.w3cjava.com
* @Desc 简单封装Jackson,实现JSON String<->Java Object的Mapper. 封装不同的输出风格,
* 使用不同的builder函数创建实例.
*/
public class JsonMapper extends ObjectMapper {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private static JsonMapper mapper;
public JsonMapper() {
// this(Include.NON_EMPTY);
}
public JsonMapper(Include include) {
// 设置输出时包含属性的风格
if (include != null) {
this.setSerializationInclusion(include);
}
// 允许单引号、允许不带引号的字段名称
this.enableSimple();
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 空值处理为空串
this.getSerializerProvider().setNullValueSerializer(
new JsonSerializer
因为在这些工具类中,有涉及到slf4j、guava等,所以在对应的pom.xml里添加了部分jar包依赖,现完整的pom.xml内容如下。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<artifactId>W3cJavaSSMartifactId>
<groupId>com.w3cjavagroupId>
<version>0.0.1-SNAPSHOTversion>
parent>
<artifactId>W3CJAVA-COMMONartifactId>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.modulegroupId>
<artifactId>jackson-module-jaxb-annotationsartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
dependency>
<dependency>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
dependency>
dependencies>
project>
这个模块主要是对增删改查所需要的基础pojo、dao、service、controller进行封装,便于复用。
com.w3cjava.common.base.pojo
package com.w3cjava.common.base.pojo;
import java.io.Serializable;
import org.apache.commons.lang3.StringUtils;
/**
* @version v1.0.0
* @author heartma
* @date 2017年12月27日
* @File BaseEntity.java
* @URL www.w3cjava.com
* @Desc Entity支持类
*/
public abstract class BaseEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 实体编号(唯一标识)
*/
protected String id;
/**
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
*/
protected boolean isNewRecord = false;
public BaseEntity() {
}
public BaseEntity(String id) {
this();
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
*
* @return
*/
public boolean getIsNewRecord() {
return isNewRecord
|| StringUtils.isBlank(getId());
}
/**
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
*/
public void setIsNewRecord(boolean isNewRecord) {
this.isNewRecord = isNewRecord;
}
/**
* 删除标记(0:正常;1:删除;2:审核;)
*/
public static final String DEL_FLAG_NORMAL = "0";
public static final String DEL_FLAG_DELETE = "1";
public static final String DEL_FLAG_AUDIT = "2";
}
package com.w3cjava.common.base.pojo;
import java.util.Date;
/**
* @version v1.0.0
* @author heartma
* @date 2017年12月27日
* @File DataEntity.java
* @URL www.w3cjava.com
* @Desc 数据Entity类
*/
public abstract class DataEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
protected String remarks; // 备注
protected Date createDate; // 创建日期
protected Date updateDate; // 更新日期
protected String delFlag; // 删除标记(0:正常;1:删除;2:审核)
public DataEntity() {
super();
this.delFlag = DEL_FLAG_NORMAL;
}
public DataEntity(String id) {
super(id);
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
}
com.w3cjava.common.base.dao
package com.w3cjava.common.base.dao;
/**
*
* @version v1.0.0
* @author heartma
* @date 2017年12月27日
* @File BaseDao.java
* @URL www.w3cjava.com
* @Desc DAO支持类
*/
public interface BaseDao {
}
package com.w3cjava.common.base.dao;
import java.util.List;
/**
*
* @version v1.0.0
* @author heartma
* @date 2017年12月27日
* @File CrudDao.java
* @URL www.w3cjava.com
* @Desc DAO支持类实现
*/
public interface CrudDao extends BaseDao {
/**
* 获取单条数据
*
* @param id
* @return
*/
public T get(String id);
/**
* 获取单条数据
*
* @param entity
* @return
*/
public T get(T entity);
/**
* 查询数据列表,如果需要分页,请设置分页对象,如:entity.setPage(new Page());
*
* @param entity
* @return
*/
public List findList(T entity);
/**
* 查询所有数据列表
*
* @param entity
* @return
*/
public List findAllList(T entity);
/**
* 查询所有数据列表
*
* @see public List findAllList(T entity)
* @return
*/
@Deprecated
public List findAllList();
/**
* 插入数据
*
* @param entity
* @return
*/
public int insert(T entity);
/**
* 更新数据
*
* @param entity
* @return
*/
public int update(T entity);
/**
* 删除数据(物理删除,从数据库中彻底删除)
*
* @param id
* @see public int delete(T entity)
* @return
*/
@Deprecated
public int delete(String id);
/**
* 删除数据(逻辑删除,更新del_flag字段为1,在表包含字段del_flag时,可以调用此方法,将数据隐藏)
*
* @param id
* @see public int delete(T entity)
* @return
*/
@Deprecated
public int deleteByLogic(String id);
/**
* 删除数据(物理删除,从数据库中彻底删除)
*
* @param entity
* @return
*/
public int delete(T entity);
/**
* 删除数据(逻辑删除,更新del_flag字段为1,在表包含字段del_flag时,可以调用此方法,将数据隐藏)
*
* @param entity
* @return
*/
public int deleteByLogic(T entity);
}
com.w3cjava.common.base.service
package com.w3cjava.common.base.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @projectNam: W3cJava
* @title: BaseService
* @author: HeartMa E-mail:[email protected]
* @url: http://www.w3cjava.com
* @time: 2018-4-22 下午11:42:59
* @description: Service基类
*/
@Transactional(readOnly = true)
public abstract class BaseService {
/**
* 日志对象
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
}
package com.w3cjava.common.base.service;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.w3cjava.common.base.dao.CrudDao;
import com.w3cjava.common.base.pojo.DataEntity;
/**
*
* @projectNam: W3cJava
* @title: CrudService
* @author: HeartMa E-mail:netheartma@gmail.com
* @url: http://www.heartma.net
* @time: 2018-4-22 下午11:47:25
* @description: Service基类
* @param
* @param
*/
@Transactional(readOnly = true)
public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<T>>
extends BaseService {
/**
* 持久层对象
*/
@Autowired
protected D dao;
/**
* 获取单条数据
*
* @param id
* @return
*/
public T get(String id) {
return dao.get(id);
}
/**
* 获取单条数据
*
* @param entity
* @return
*/
public T get(T entity) {
return dao.get(entity);
}
/**
* 查询列表数据
*
* @param entity
* @return
*/
public List findList(T entity) {
return dao.findList(entity);
}
/**
* 保存数据(插入或更新)
*
* @param entity
*/
@Transactional(readOnly = false)
public void save(T entity) {
if (entity.getIsNewRecord()) {
//entity.preInsert();
dao.insert(entity);
} else {
//entity.preUpdate();
dao.update(entity);
}
}
/**
* 删除数据
*
* @param entity
*/
@Transactional(readOnly = false)
public void delete(T entity) {
dao.delete(entity);
}
/**
* 删除全部数据
*
* @param entity
*/
@Transactional(readOnly = false)
public void deleteAll(Collection entitys) {
for (T entity : entitys) {
dao.delete(entity);
}
}
}
com.w3cjava.common.base.controller
package com.w3cjava.common.base.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import com.w3cjava.common.mapper.JsonMapper;
/**
* @version v1.0.0
* @author heartma
* @date 2017年12月27日
* @File BaseController.java
* @URL www.w3cjava.com
* @Desc 控制器支持类
*/
public abstract class BaseController {
/**
* 日志对象
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* 管理基础路径
*/
@Value("${adminPath}")
protected String adminPath;
/**
* 前端基础路径
*/
@Value("${frontPath}")
protected String frontPath;
/**
* 客户端返回JSON字符串
*
* @param response
* @param object
* @return
*/
protected String renderString(HttpServletResponse response, Object object) {
return renderString(response, JsonMapper.toJsonString(object));
}
/**
* 客户端返回字符串
*
* @param response
* @param string
* @return
*/
protected String renderString(HttpServletResponse response, String string) {
try {
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
return null;
} catch (IOException e) {
return null;
}
}
}
这样,W3CJAVA-WEB-COMMON基础的增删改查就实现,下面在W3CJAVA-WEB中只要继承对应的封装类,就可以省去基础的代码。
只要简单依赖的W3CJAVA-WEB-COMMON即可
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.w3cjavagroupId>
<artifactId>W3cJavaSSMartifactId>
<version>0.0.1-SNAPSHOTversion>
<relativePath/>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>W3CJAVA-WEBartifactId>
<packaging>warpackaging>
<dependencies>
<dependency>
<groupId>com.w3cjavagroupId>
<artifactId>W3CJAVA-WEB-COMMONartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
dependencies>
project>
其他xml及jsp文件参照 SSM(一)框架的整合 即可,然后我们对pojo、dao、service、controller层作简单的修改。
package com.w3cjava.pojo;
import com.w3cjava.common.base.pojo.DataEntity;
public class User extends DataEntity{
private static final long serialVersionUID = 1L;
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.w3cjava.dao;
import org.springframework.stereotype.Component;
import com.w3cjava.common.base.dao.CrudDao;
import com.w3cjava.pojo.User;
@Component
public interface UserMapper extends CrudDao{
}
package com.w3cjava.service;
import org.springframework.stereotype.Service;
import com.w3cjava.common.base.service.CrudService;
import com.w3cjava.dao.UserMapper;
import com.w3cjava.pojo.User;
@Service
public class UserService extends CrudService{
}
package com.w3cjava.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.w3cjava.common.base.controller.BaseController;
import com.w3cjava.pojo.User;
import com.w3cjava.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
@Autowired
private UserService userService;
@RequestMapping(value={"list",""})
public String index(Model model){
List allUsers = userService.findList(new User());
model.addAttribute("allUsers", allUsers);
return "user/userList";
}
@RequestMapping(value={"add"})
public String add(){
return "user/userAdd";
}
@RequestMapping(value={"edit"})
public String edit(User user){
User user2 = userService.get(user.getId());
System.out.print(user2);
return "user/userEdit";
}
@RequestMapping(value={"delete"})
public String delete(User user){
userService.get(user.getId());
return "user/userList";
}
}
将W3CJAVA-WEB部署到tomcat中,运行查看,仍然可以看到如下页面
源码地址:https://github.com/heartMa/ssm.git common-1分支