MyBatis + spring boot 答辩展示网站
暑假学习了MyBatis和spring boot 就像为工作室写点东西能流传下来,于是就写了这个答辩展示网站,虽然最开始很生疏,但到后面就熟练了。
jar包导依赖
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 分页的依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<!--jpa的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 返回json对象的依赖-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<!-- markdown解析-->
<dependency>
<groupId>org.pegdown</groupId>
<artifactId>pegdown</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.1.7</version>
</dependency>
<!--邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
环境配置
server:
port: 8080
spring:
datasource:
filters: stat
username: root
password: root
url: jdbc:mysql://localhost:3306/task3?serverTimezone=GMT&&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
initial-size: 1
min-idle: 1
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 200
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
mail:
host: smtp.qq.com
username: 798284949@qq.com
password: diowmhxuncctbfah
properties:
smtp:
auth: true
starttls:
enable: true
required: true
ssl:
enable: true
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html
cache: true
servlet:
multipart:
max-file-size: -1
max-request-size: -1
mvc:
static-path-pattern: /**
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: com.example.pojo
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
returnPageInfo: check
devtools:
livereload:
enabled: true
port: 8080
restart:
enabled: true
additional-paths: src/main/java
filepath:
path: D:/FileCenter
#spring.mail:
# host: smtp.exmail.qq.com
# username: 798284949@qq.com
# password: **********
# properties:
# smtp.auth: true
# smtp.starttls.enable: true
# smtp.starttls.required: true
# mail.smtp.ssl.enable: true
前端与后台的交互运用ajax
function adminLogin() {
var username = document.getElementById("username").value; //获取到前端输入的用户名
var password = document.getElementById("password").value; //获取到前端输入的密码
var obj = {
username:username,
password:password,
}
$.ajax({
"url": "/manageLogin/dologin", //reg是注册接口
type:'POST',
dataType:'json',
contentType:'application/json',
data: JSON.stringify(obj),
success: function(result) {
if(result == "1")
{
alert('登录成功');
window.location.href="/manage/listManage";
}
else
{
alert('用户名或密码错误');
window.location.href="/change/login";
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('XMLHttpRequest:');
console.log(XMLHttpRequest);
alert('网络异常!尝试刷新网页解决问题')
}
});
}
普通功能(增删改查)
用的是mysql语句,很简单所以就不加赘述。
文件处理
RequestMapping("dodisplay")
@ResponseBody
public String display(HttpServletRequest request)
{
String result = "0";
MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
List<MultipartFile> files = params.getFiles("file");
List<MultipartFile> files1 = params.getFiles("file1");
Work work = new Work();
work.setTitle(params.getParameter("title"));
work.setDescribe(params.getParameter("describe"));
work.setGitUrl(params.getParameter("git_url"));
work.setMarkdownPath(params.getParameter("markdown_path"));
work.setGroupId(Integer.parseInt(params.getParameter("group_id")));
work.setStudentId(params.getParameter("student_id"));
work.setVideoUrl(params.getParameter("video_url"));
File targetFile = null;
String fileName = null;
String path = "D:\\FileCenter";
if(files != null)
{
fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +
"_" + new Random().nextInt(10000) + ".md";//新文件名
File file = new File(path);
if(!file.exists() && !file.isDirectory()){
file.mkdirs();
}
targetFile = new File(file, fileName);
result = "1";
}try {
files.get(0).transferTo(targetFile);
work.setMarkdownPath(path + "\\" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
if(files1 != null)
{
fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +
"_" + new Random().nextInt(10000) + ".jpg";//新文件名
File file = new File(path);
if(!file.exists() && !file.isDirectory()){
file.mkdirs();
}
targetFile = new File(file, fileName);
result = "1";
}try {
files1.get(0).transferTo(targetFile);
work.setPicturePath(path + "\\" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
if(workLowService.insert(work)) {
Work work1 = workLowService.findBywork(work);
goodLowService.insert(work1.getId());
commentLowService.insert(work1 .getId());
readLowService.insert(work1.getId());
result = "1";
}
else
result = "0";
return result;
}
再就是拦截器的配置
只将manage开头的Controller给拦截,检查session,如果没有登陆或者没有权限则跳转的登陆界面。
package com.example.aspet;
import com.example.exception.SellerAuthoeizeException;
import com.example.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Aspect
@Component
@Slf4j
public class SellerAuthoeizeAspect {
@Pointcut("execution (public * com.example.controller.Manage*.*(..))" + "&& !execution(public * com.example.controller.ManageLoginController.*(..))")
public void verify(){ }
@Before("verify()")
public void doVerify(){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Object object = request.getSession().getAttribute("user");
User user = (User) object;
System.out.println(user);
if(user == null || user.getIdentity() == 2 || user.getIdentity() == 3)
{
throw new SellerAuthoeizeException();
}
}
}
以及
package com.example.exception;
public class SellerAuthoeizeException extends RuntimeException {
}
最后加了个邮箱改密码
Controller
package com.example.controller;
import com.example.dto.BCryptUtil;
import com.example.dto.CommentDTO;
import com.example.dto.RegexUtil;
import com.example.dto.WorkDTO;
import com.example.pojo.*;
import com.example.service.*;
import com.example.service.serviceImpl.MailServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
@Controller
public class MailFindPasswordController {
@Autowired
private UserLowService userLowService;
@Autowired
private MailRetrieveService mailRetrieveService;
@Autowired
private MailServiceImpl mailService;
/**
* 登录页面显示
*
* @return
*/
@GetMapping("/login")
public String login(@RequestParam(value = "action", required = false) String action) {
//登录
if (action == null) {
return "login";
}
//注册
else if ("register".equals(action)) {
return "forward:/register";
}
//忘记密码
else if ("lostpass".equals(action)) {
return "forward:/lostpass";
}
//设置密码
else if ("resetpass".equals(action)) {
return "forward:/resetpass";
}
//退出登录
else if ("logout".equals(action)) {
return "forward:/logout";
}
//其他
else {
return "login";
}
}
/**
* 忘记密码页面显示
*
* @return
*/
@GetMapping(value = "/lostpass")
public ModelAndView forget() {
ModelAndView modelAndView = new ModelAndView("login");
modelAndView.addObject("action", "lostpass");
modelAndView.addObject("message", "请输入您的用户名或电子邮箱地址。您会收到一封包含创建新密码链接的电子邮件。");
return modelAndView;
}
/**
* 忘记密码提交,然后跳转登录页面
*
* @param request
* @param account
* @return
*/
@PostMapping(value = "/lostpass")
public ModelAndView forgetUser(HttpServletRequest request, String account) {
ModelAndView modelAndView = new ModelAndView("login");
String username = "";
//1、获取用户名 username
if (RegexUtil.isEmail(account)) {
User user = userLowService.selectByEmail(account);
if (user != null) {
username = user.getUsername();
}
} else {
//account 是用户名
username = account;
}
User user = userLowService.findByUsername(username);
//2、判断用户是否存在
if(user != null) {
//用户存在
//2.1、生成链接
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
ResultVO resultVO = mailRetrieveService.generateMailUrl(basePath, username);
String mailUrl = resultVO.getData().toString();
//2.2、发送邮件
String receiver = user.getEmail();//接收者
String subject = "[Spring Blog]密码重置";//邮件主题(标题)
StringBuilder content = new StringBuilder();
content.append("有人为以下账号请求了密码重置:<br/><br/>");
content.append("<a href=" + basePath + " target=\"_blank\">" + basePath + "</a><br/><br/>");
content.append("用户名:" + username + "<br/><br/>");
content.append("若这不是您本人要求的,请忽略本邮件,一切如常。<br/><br/>");
content.append("要重置您的密码,请打开下面的链接(如果邮箱对链接拦截,请复制链接在地址栏中打开,30分钟内有效):<br/><br/>");
content.append("<a href=" + mailUrl + " target=\"_blank\">" + mailUrl + "</a><br/><br/>");
mailService.sendHtmlMail(receiver, subject, content.toString());
//2.3、显示登录页面和提示信息
modelAndView.addObject("checkmail", "请在您的电子邮箱中检查确认链接。");
} else {
//用户不存在
//2.1、 显示找回密码页面,和错误信息
modelAndView.addObject("error","用户名或邮箱不存在!");
modelAndView.addObject("action","lostpass");
}
return modelAndView;
}
/**
* 重置密码验证
* 验证通过,显示修改密码页面
*
* @param sid
* @param username
* @return
*/
@GetMapping(value = "/resetpassword")
public ModelAndView verifyMail(String sid, String username) {
ModelAndView modelAndView = new ModelAndView("resetpass");
ResultVO resultVO = mailRetrieveService.verifyMailUrl(sid, username);
//验证通过,显示设置密码页面
if ("000".equals(resultVO.getCode())) {
modelAndView.addObject("action", "resetpass");
modelAndView.addObject("username", username);
modelAndView.addObject("sid", sid);
} else {
//链接无效,显示找回密码页面
modelAndView.addObject("action", "lostpass");
//显示错误信息
modelAndView.addObject("error", resultVO.getMsg());
}
return modelAndView;
}
/**
* 重置密码提交
*
* @param sid 根据用户sid来查询用户名
* @param password
* @return
*/
@PostMapping(value = "/resetpass")
public ModelAndView resetPass(String sid, String username, String password) {
ModelAndView modelAndView = new ModelAndView("login");
ResultVO resultVO = mailRetrieveService.verifyMailUrl(sid, username);
//如果验证通过(防止用户自定义表单,再次验证)
if ("000".equals(resultVO.getCode())) {
//修改密码
User user = userLowService.findByUsername(username);
user.setPassword(password);
userLowService.UpdatePasswordById(user.getId(), user.getPassword());
}
//验证失败
else {
//显示找回密码页面
modelAndView.addObject("action", "lostpass");
//显示错误信息
modelAndView.addObject("error", "用户名或sid不正确");
}
return modelAndView;
}
}
ServiceImpl
package com.example.service.serviceImpl;
//import com.example.Repository.MailRetrieveRepository;
import com.example.dto.MD5Util;
import com.example.mapper.MailLowMapper;
import com.example.mapper.UserLowMapper;
import com.example.pojo.MailRetrieve;
import com.example.pojo.ResultVO;
import com.example.pojo.User;
import com.example.service.MailRetrieveService;
import com.sun.jmx.snmp.Timestamp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MailRetrieveServiceImpl implements MailRetrieveService {
@Autowired
private UserLowMapper userLowMapper;
@Autowired
private MailLowMapper mailRetrieveRepository;
/**
* 生成链接
* @param basePath
* @param account
* @return
*/
@Override
public ResultVO generateMailUrl(String basePath, String account) {
User user = userLowMapper.findByUsername(account);
ResultVO resultVO = new ResultVO();
//用户名不存在
if (user == null) {
resultVO.setCode("001");
resultVO.setMsg("用户不存在");
} else {
//生成邮件URL唯一地址
String key = ((Math.random()*9+1)*100000)+ "";
Timestamp outDate = new Timestamp(System.currentTimeMillis() + (long) (30 * 60 * 1000));//30分钟后过期
long outtimes = outDate.getSysUpTime();
System.out.println(outtimes);
String sid = account + key + outtimes;
MailRetrieve mailRetrieve = new MailRetrieve(account, sid, outtimes);
MailRetrieve findMailRetrieve = mailRetrieveRepository.findByAccount(account);
if (findMailRetrieve != null) {
mailRetrieveRepository.delete(findMailRetrieve.getAccount());
}
mailRetrieveRepository.save(mailRetrieve.getOutTime(), mailRetrieve.getAccount(), mailRetrieve.getSid());
resultVO.setCode("005");
resultVO.setMsg("邮件重置密码");
resultVO.setData(basePath + "resetpassword?sid=" + sid + "&username=" + account);
}
return resultVO;
}
/**
* 验证链接
* @param sid
* @param username
* @return
*/
@Override
public ResultVO verifyMailUrl(String sid, String username) {
ResultVO resultVO = new ResultVO();
MailRetrieve mailRetrieve = mailRetrieveRepository.findByAccount(username);
sid = mailRetrieve.getSid();
if(mailRetrieve != null) {
long outTime = mailRetrieve.getOutTime();
Timestamp outDate = new Timestamp(System.currentTimeMillis());
long nowTime = outDate.getSysUpTime();
System.out.println("5555" + sid);
System.out.println("4444" + username);
System.out.println("3333" + mailRetrieve);
System.out.println("nowTime:" + nowTime);
if (outTime <= nowTime) {
resultVO.setCode("006");
resultVO.setMsg("邮件已经过期!");
// } else if (" ".equals(sid)) {
// resultVO.setCode("007");
// resultVO.setMsg("sid不完整!");
} else if (!sid.equals(mailRetrieve.getSid())) {
resultVO.setCode("008");
resultVO.setMsg("sid错误!");
} else {
resultVO.setCode("000");
resultVO.setMsg("验证成功!");
}
} else {
//account 对应的用户不存在
resultVO.setCode("002");
resultVO.setMsg("链接无效!");
}
return resultVO;
}
}
package com.example.service.serviceImpl;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class MailServiceImpl {
private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender sender;
@Value("${spring.mail.username}")
private String from;
/**
* 发送纯文本的简单邮件
* @param to
* @param subject
* @param content
*/
public void sendSimpleMail(String to, String subject, String content){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
sender.send(message);
logger.info("简单邮件已经发送。");
} catch (Exception e) {
logger.error("发送简单邮件时发生异常!", e);
}
}
/**
* 发送html格式的邮件
* @param to
* @param subject
* @param content
*/
public void sendHtmlMail(String to, String subject, String content){
MimeMessage message = sender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
sender.send(message);
logger.info("html邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送html邮件时发生异常!", e);
}
}
/**
* 发送带附件的邮件
* @param to
* @param subject
* @param content
* @param filePath
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath){
MimeMessage message = sender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
sender.send(message);
logger.info("带附件的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送带附件的邮件时发生异常!", e);
}
}
/**
* 发送嵌入静态资源(一般是图片)的邮件
* @param to
* @param subject
* @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:rscId01\" >
* @param rscPath 静态资源路径和文件名
* @param rscId 静态资源id
*/
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
MimeMessage message = sender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
sender.send(message);
logger.info("嵌入静态资源的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送嵌入静态资源的邮件时发生异常!", e);
}
}
}
还有一些好用的工具类
ResultVO
package com.example.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author yuanshushu
* @date 2018/8/29
* @description 返回结果VO对象
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class ResultVO<T> {
// @ApiModelProperty("状态码 0失败 1成功 2未登录 3没有权限")
private String code;
// @ApiModelProperty("返回信息")
private String msg;
// @ApiModelProperty("返回数据")
private T data;
// /**
// * 请求成功 状态码 1
// *
// * @param msg 返回信息
// * @param <T> 类型
// * @return ResultVO
// */
// public static <T> ResultVO getSuccess(String msg) {
// return new ResultVO(1, msg);
// }
//
// /**
// * 请求成功 状态码 1
// *
// * @param msg 返回信息
// * @param data 返回对象
// * @param <T> 类型
// * @return ResultVO
// */
// public static <T> ResultVO getSuccess(String msg, T data) {
// return new ResultVO(1, msg, data);
// }
//
// /**
// * 请求失败 状态码 0
// *
// * @param msg 返回信息
// * @param <T> 类型
// * @return ResultVO
// */
// public static <T> ResultVO getFailed(String msg) {
// return new ResultVO(0, msg);
// }
//
// /**
// * 请求失败 状态 0
// *
// * @param msg 返回信息
// * @param data 返回数据
// * @param <T> 类型
// * @return ResultVO
// */
// public static <T> ResultVO getFailed(String msg, T data) {
// return new ResultVO(0, msg, data);
// }
//
//
// /**
// * 用户未登录
// *
// * @param <T> 类型
// * @return ResultVO
// */
// public static <T> ResultVO getNoLogin() {
// return new ResultVO(2, "用户未登录,请重新登录");
// }
//
//
// /**
// * 用户没有操作权限
// *
// * @param <T> 类型
// * @return ResultVO
// */
// public static <T> ResultVO getNoAuthorization() {
// return new ResultVO(3, "用户没有操作权限,请重新登录");
// }
//
//
// public Integer getCode() {
// return code;
// }
//
// public void setCode(Integer code) {
// this.code = code;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
}
MD5UTIL
package com.example.dto;
import java.security.MessageDigest;
/**
* @author create by yaoyuan
* @date 2017年6月5日 下午8:13:09
*/
public class MD5Util{
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
RegexUtil
package com.example.dto;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
public class RegexUtil {
public final static boolean isNull(Object[] objs) {
if (objs == null || objs.length == 0)
return true;
return false;
}
public final static boolean isNull(Integer integer) {
if (integer == null || integer == 0)
return true;
return false;
}
public final static boolean isNull(Collection collection) {
if (collection == null || collection.size() == 0)
return true;
return false;
}
public final static boolean isNull(Map map) {
if (map == null || map.size() == 0)
return true;
return false;
}
public final static boolean isNull(String str) {
return str == null || "".equals(str.trim())
|| "null".equals(str.toLowerCase());
}
public final static boolean isNull(Long longs) {
if (longs == null || longs == 0)
return true;
return false;
}
public final static boolean isNotNull(Long longs) {
return !isNull(longs);
}
public final static boolean isNotNull(String str) {
return !isNull(str);
}
public final static boolean isNotNull(Collection collection) {
return !isNull(collection);
}
public final static boolean isNotNull(Map map) {
return !isNull(map);
}
public final static boolean isNotNull(Integer integer) {
return !isNull(integer);
}
public final static boolean isNotNull(Object[] objs) {
return !isNull(objs);
}
/**
* 匹配URL地址
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean isUrl(String str) {
return match(str, "^http://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$");
}
/**
* 匹配密码,以字母开头,长度在6-12之间,只能包含字符、数字和下划线。
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean isPwd(String str) {
return match(str, "^[a-zA-Z]\\w{6,12}$");
}
/**
* 验证字符,只能包含中文、英文、数字、下划线等字符。
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean stringCheck(String str) {
return match(str, "^[a-zA-Z0-9\u4e00-\u9fa5-_]+$");
}
/**
* 匹配Email地址
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean isEmail(String str) {
return match(str,
"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
}
/**
* 匹配非负整数(正整数+0)
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean isInteger(String str) {
return match(str, "^[+]?\\d+$");
}
/**
* 判断数值类型,包括整数和浮点数
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean isNumeric(String str) {
if (isFloat(str) || isInteger(str))
return true;
return false;
}
/**
* 只能输入数字
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean isDigits(String str) {
return match(str, "^[0-9]*$");
}
/**
* 匹配正浮点数
*
* @param str
* @return
* @author jiqinlin
*/
public final static boolean isFloat(String str) {
return match(str, "^[-\\+]?\\d+(\\.\\d+)?$");
}
/**
* 联系电话(手机/电话皆可)验证
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isTel(String text) {
if (isMobile(text) || isPhone(text))
return true;
return false;
}
/**
* 电话号码验证
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isPhone(String text) {
return match(text, "^(\\d{3,4}-?)?\\d{7,9}$");
}
/**
* 手机号码验证
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isMobile(String text) {
if (text.length() != 11)
return false;
return match(text,
"^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$");
}
/**
* 身份证号码验证
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isIdCardNo(String text) {
return match(text, "^(\\d{6})()?(\\d{4})(\\d{2})(\\d{2})(\\d{3})(\\w)$");
}
/**
* 邮政编码验证
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isZipCode(String text) {
return match(text, "^[0-9]{6}$");
}
/**
* 判断整数num是否等于0
*
* @param num
* @return
* @author jiqinlin
*/
public final static boolean isIntEqZero(int num) {
return num == 0;
}
/**
* 判断整数num是否大于0
*
* @param num
* @return
* @author jiqinlin
*/
public final static boolean isIntGtZero(int num) {
return num > 0;
}
/**
* 判断整数num是否大于或等于0
*
* @param num
* @return
* @author jiqinlin
*/
public final static boolean isIntGteZero(int num) {
return num >= 0;
}
/**
* 判断浮点数num是否等于0
*
* @param num
* 浮点数
* @return
* @author jiqinlin
*/
public final static boolean isFloatEqZero(float num) {
return num == 0f;
}
/**
* 判断浮点数num是否大于0
*
* @param num
* 浮点数
* @return
* @author jiqinlin
*/
public final static boolean isFloatGtZero(float num) {
return num > 0f;
}
/**
* 判断浮点数num是否大于或等于0
*
* @param num
* 浮点数
* @return
* @author jiqinlin
*/
public final static boolean isFloatGteZero(float num) {
return num >= 0f;
}
/**
* 判断是否为合法字符(a-zA-Z0-9-_)
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isRightfulString(String text) {
return match(text, "^[A-Za-z0-9_-]+$");
}
/**
* 判断英文字符(a-zA-Z)
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isEnglish(String text) {
return match(text, "^[A-Za-z]+$");
}
/**
* 判断中文字符(包括汉字和符号)
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isChineseChar(String text) {
return match(text, "^[\u0391-\uFFE5]+$");
}
/**
* 匹配汉字
*
* @param text
* @return
* @author jiqinlin
*/
public final static boolean isChinese(String text) {
return match(text, "^[\u4e00-\u9fa5]+$");
}
/**
* 是否包含中英文特殊字符,除英文"-_"字符外
*
* @param str
* @return
*/
public static boolean isContainsSpecialChar(String text) {
if (StringUtils.isBlank(text))
return false;
String[] chars = { "[", "`", "~", "!", "@", "#", "$", "%", "^", "&",
"*", "(", ")", "+", "=", "|", "{", "}", "'", ":", ";", "'",
",", "[", "]", ".", "<", ">", "/", "?", "~", "!", "@", "#",
"¥", "%", "…", "&", "*", "(", ")", "—", "+", "|", "{", "}",
"【", "】", "‘", ";", ":", "”", "“", "’", "。", ",", "、", "?", "]" };
for (String ch : chars) {
if (text.contains(ch))
return true;
}
return false;
}
/**
* 过滤中英文特殊字符,除英文"-_"字符外
*
* @param text
* @return
*/
public static String stringFilter(String text) {
String regExpr = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regExpr);
Matcher m = p.matcher(text);
return m.replaceAll("").trim();
}
/**
* 过滤html代码
*
* @param inputString
* 含html标签的字符串
* @return
*/
public static String htmlFilter(String inputString) {
String htmlStr = inputString; // 含html标签的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
java.util.regex.Pattern p_ba;
java.util.regex.Matcher m_ba;
try {
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
// }
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
// }
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
String patternStr = "\\s+";
p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
p_ba = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
m_ba = p_ba.matcher(htmlStr);
htmlStr = m_ba.replaceAll(""); // 过滤空格
textStr = htmlStr;
} catch (Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;// 返回文本字符串
}
/**
* 正则表达式匹配
*
* @param text
* 待匹配的文本
* @param reg
* 正则表达式
* @return
* @author jiqinlin
*/
private final static boolean match(String text, String reg) {
if (StringUtils.isBlank(text) || StringUtils.isBlank(reg))
return false;
return Pattern.compile(reg).matcher(text).matches();
}
}