开发环境
- 开发工具 idea
- 开发使用的技术:
spring +SpringMVC 或Spring boot + Mybatis+通用Mapper+获取音频大小的jave+mybatis+mysql
页面:bootStrup+Gqurid
本文主要讲解工具类的封装
- Util
-
- CrudMapperImpl(基础的增删改)
ExtensionMapperImpl(扩展的增删改)
SecurityCode(验证码的封装)
SecurityImage(验证码的封装)
SelectAllPagingMapperImpl(分页 的查询)
- 测试使用的
-
-
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>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.6.RELEASEversion>
<relativePath/>
parent>
<groupId>com.baizhigroupId>
<artifactId>cmfzartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>cmfzname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
dependency>
<dependency>
<groupId>tk.mybatisgroupId>
<artifactId>mapper-spring-boot-starterartifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.19version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.46version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.54version>
dependency>
<dependency>
<groupId>com.github.dadiyanggroupId>
<artifactId>javeartifactId>
<version>1.0.5version>
dependency>
<dependency>
<groupId>cn.afterturngroupId>
<artifactId>easypoi-baseartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>cn.afterturngroupId>
<artifactId>easypoi-webartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>cn.afterturngroupId>
<artifactId>easypoi-annotationartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
CrudMapper
package com.util.service;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
import java.util.Map;
@Repository
public interface CrudMapper<T> {
Map<String, Object> add(T args, Mapper<T> mapper, String id);
Map<String, Object> edit(T args, Mapper<T> mapper, String id);
Map<String, Object> del(T args, Mapper<T> mapper, String id);
}
crudMapperImpl
package com.util;
import com.util.service.CrudMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import java.util.HashMap;
import java.util.Map;
@Service
public class CrudMapperImpl<T> implements CrudMapper<T> {
@Override
public Map<String, Object> add(T args, Mapper<T> mapper, String id) {
Map<String, Object> map = new HashMap<>();
try {
mapper.insertSelective(args);
map.put("status", true);
map.put("message", id);
} catch (Exception e) {
map.put("status", false);
map.put("message", e.getMessage());
}
return map;
}
@Override
public Map<String, Object> edit(T args, Mapper<T> mapper, String id) {
Map<String, Object> map = new HashMap<>();
try {
mapper.updateByPrimaryKeySelective(args);
map.put("status", true);
map.put("message", id);
} catch (Exception e) {
map.put("status", false);
map.put("message", e.getMessage());
}
return map;
}
@Override
public Map<String, Object> del(T args, Mapper<T> mapper, String id) {
Map<String, Object> map = new HashMap<>();
try {
mapper.deleteByPrimaryKey(args);
map.put("status", true);
map.put("message", id);
} catch (Exception e) {
map.put("status", false);
map.put("message", e.getMessage());
}
return map;
}
}
CrudExtenstionMapper
package com.util.service;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
import java.util.Map;
@Repository
public interface ExtensionMapper<T> {
Map<String, Object> add(T args, Mapper<T> mapper);
Map<String, Object> edit(T args, Mapper<T> mapper);
Map<String, Object> del(T args, Mapper<T> mapper);
}
CrudExtensionMapperImpl
package com.util;
import com.baizhi.util.service.ExtensionMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import java.util.Map;
@Service
public class ExtensionMapperImpl<T> implements ExtensionMapper<T> {
@Override
public Map<String, Object> add(T args, Mapper<T> mapper) {
return null;
}
@Override
public Map<String, Object> edit(T args, Mapper<T> mapper) {
return null;
}
@Override
public Map<String, Object> del(T args, Mapper<T> mapper) {
return null;
}
}
SelectAllPagingMapper
package com.util.service;
import tk.mybatis.mapper.common.Mapper;
import java.util.Map;
public interface SelectAllPagingMapper<T> {
Map<String, Object> selectAllPaging(Integer page, Integer rows, Mapper<T> mapper, T args);
}
SelectAllPagingMapperImpl
package com.baizhi.util;
import com.baizhi.util.service.SelectAllPagingMapper;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SelectAllPagingMapperImpl<T> implements SelectAllPagingMapper<T> {
@Override
public Map<String, Object> selectAllPaging(Integer page, Integer rows, Mapper<T> mapper, T args) {
Map<String, Object> map = new HashMap<>();
RowBounds rowBounds = new RowBounds((page - 1) * rows, rows);
List<T> banners = mapper.selectByRowBounds(args, rowBounds);
int count = mapper.selectCount(args);
map.put("page", page);
map.put("rows", banners);
map.put("total", count % rows == 0 ? count / rows : count / rows + 1);
map.put("records", count);
return map;
}
}
UploadUtil
package com.baizhi.util.service;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
@Service
public class UploadUtil {
public Map<String, Object> uploadFile(HttpSession httpSession, MultipartFile multipartFile, String realPath) throws IOException, EncoderException {
Map<String, Object> map = new HashMap<>();
if (realPath != null) {
String getRealPath = httpSession.getServletContext().getRealPath(realPath);
if (multipartFile.getOriginalFilename() != null) {
File file = new File(getRealPath, multipartFile.getOriginalFilename());
multipartFile.transferTo(file);
BigDecimal size = new BigDecimal(multipartFile.getSize());
BigDecimal dom = new BigDecimal(1024);
BigDecimal bigDecimal = size.divide(dom).divide(dom).setScale(2, BigDecimal.ROUND_HALF_UP);
map.put("bigDecimal", bigDecimal);
map.put("OriginalFilename", multipartFile.getOriginalFilename());
if (file != null) {
Encoder encoder = new Encoder();
long duration = encoder.getInfo(file).getDuration();
String Duration = duration / 1000 / 60 + ":" + duration / 1000 % 60;
map.put("Duration", Duration);
}
}
}
return map;
}
}
测试 Controller
package com.controller;
import com.dao.ChapterDao;
import com.entity.Chapter;
import com.service.ChapterService;
import com.util.service.CrudMapper;
import com.util.service.SelectAllPagingMapper;
import com.util.service.UploadUtil;
import it.sauronsoftware.jave.EncoderException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Controller
@RequestMapping("/chapter")
public class ChapterController {
@Autowired
private ChapterService chapterService;
@Autowired
private ChapterDao chapterDao;
@Qualifier("selectAllPagingMapperImpl")
@Autowired
private SelectAllPagingMapper<Chapter> selectAllPaging;
@Qualifier("crudMapperImpl")
@Autowired
private CrudMapper<Chapter> crudMapper;
@Autowired
private UploadUtil uploadUtil;
@RequestMapping("/selectChaptersBuAlbumId")
@ResponseBody
public Map<String, Object> getPage(Integer page, Integer rows, String albumId) {
System.out.println("albumId = " + albumId);
System.out.println("page = " + page);
System.out.println("rows = " + rows);
Chapter chapter = new Chapter();
chapter.setAlbumId(albumId);
Map<String, Object> stringObjectMap = selectAllPaging.selectAllPaging(page, rows, chapterDao, chapter);
return stringObjectMap;
}
@RequestMapping("/edit")
@ResponseBody
public Map<String, Object> editBanner(String oper, Chapter chapter, String albumId) {
System.out.println("albumId = " + albumId);
System.out.println(oper);
System.out.println("chapter = " + chapter);
Map<String, Object> map = new HashMap<>();
if (oper.equals("add")) {
chapter.setId(UUID.randomUUID().toString());
chapter.setCreateDate(new Date());
chapter.setAlbumId(albumId);
map = crudMapper.add(chapter, chapterDao, chapter.getId());
}
if (oper.equals("edit")) {
chapter.setAlbumId(albumId);
map = chapterService.edit(chapter, chapterDao);
}
if (oper.equals("del")) {
map = crudMapper.del(chapter, chapterDao, chapter.getId());
}
return map;
}
@RequestMapping("/upload")
@ResponseBody
public void upload(String id, MultipartFile name, HttpSession httpSession) throws IOException, EncoderException {
Chapter chapter = new Chapter();
chapter.setId(id);
Map<String, Object> map = uploadUtil.uploadFile(httpSession, name, "album/music");
map.forEach((k, v) -> {
if (k.equals("OriginalFilename")) {
chapter.setName((String) v);
}
if (k.equals("Duration")) {
chapter.setDuration((String) v);
}
if (k.equals("bigDecimal")) {
chapter.setSize(v + "MB");
}
System.out.println("k = " + k);
System.out.println("v = " + v);
});
chapterService.edit(chapter, chapterDao);
}
}
ChapterService
package com.service;
import com.entity.Chapter;
import com.util.service.ExtensionMapper;
import tk.mybatis.mapper.common.Mapper;
import java.util.Map;
public interface ChapterService extends ExtensionMapper<Chapter> {
@Override
Map<String, Object> add(Chapter args, Mapper<Chapter> mapper);
@Override
Map<String, Object> edit(Chapter args, Mapper<Chapter> mapper);
@Override
Map<String, Object> del(Chapter args, Mapper<Chapter> mapper);
}
ChapterServiceImpl
package com.baizhi.service.serviceImpl;
import com.baizhi.entity.Chapter;
import com.baizhi.service.ChapterService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import java.util.HashMap;
import java.util.Map;
@Service
public class ChapterServiceImpl implements ChapterService {
@Override
public Map<String, Object> add(Chapter args, Mapper<Chapter> mapper) {
return null;
}
@Override
public Map<String, Object> edit(Chapter args, Mapper<Chapter> mapper) {
Map<String, Object> map = new HashMap<>();
try {
if ("".equals(args.getName())) {
args.setName(null);
}
mapper.updateByPrimaryKeySelective(args);
map.put("status", true);
map.put("message", args.getId());
} catch (Exception e) {
map.put("status", false);
map.put("message", e.getMessage());
}
return map;
}
@Override
public Map<String, Object> del(Chapter args, Mapper<Chapter> mapper) {
return null;
}
}
SecurityCode
package com.baizhi.util;
import java.util.Arrays;
public class SecurityCode {
public enum SecurityCodeLevel {
Simple, Medium, Hard
};
public static String getSecurityCode() {
return getSecurityCode(4, SecurityCodeLevel.Medium, false);
}
private static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
int len = length;
char[] codes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
if (level == SecurityCodeLevel.Simple) {
codes = Arrays.copyOfRange(codes, 0, 10);
} else if (level == SecurityCodeLevel.Medium) {
codes = Arrays.copyOfRange(codes, 0, 36);
}
int n = codes.length;
if (len > n && isCanRepeat == false) {
throw new RuntimeException(String.format("调用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出现异常," + "当isCanRepeat为%3$s时,传入参数%1$s不能大于%4$s", len, level, isCanRepeat, n));
}
char[] result = new char[len];
if (isCanRepeat) {
for (int i = 0; i < result.length; i++) {
int r = (int) (Math.random() * n);
result[i] = codes[r];
}
} else {
for (int i = 0; i < result.length; i++) {
int r = (int) (Math.random() * n);
result[i] = codes[r];
codes[r] = codes[n - 1];
n--;
}
}
return String.valueOf(result);
}
public static void main(String[] args) {
System.out.println(SecurityCode.getSecurityCode());
}
}
SecurityImage
package com.baizhi.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
public class SecurityImage {
public static BufferedImage createImage(String securityCode){
int codeLength = securityCode.length();
int fontSize = 15;
int fontWidth = fontSize+1;
int width = codeLength*fontWidth+6;
int height = fontSize*2+1;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.LIGHT_GRAY);
g.setFont(new Font("Arial", Font.BOLD, height-2));
g.drawRect(0, 0, width-1, height-1);
Random rand = new Random();
g.setColor(Color.LIGHT_GRAY);
for (int i = 0; i < codeLength*6; i++) {
int x = rand.nextInt(width);
int y = rand.nextInt(height);
g.drawRect(x, y, 1, 1);
}
int codeY = height-10;
g.setColor(new Color(19,148,246));
g.setFont(new Font("Georgia", Font.BOLD, fontSize));
for(int i=0;i<codeLength;i++){
double deg=new Random().nextDouble()*20;
g.rotate(Math.toRadians(deg), i*16+13,codeY-7.5);
g.drawString(String.valueOf(securityCode.charAt(i)), i*16+5, codeY);
g.rotate(Math.toRadians(-deg), i*16+13,codeY-7.5);
}
g.dispose();
return image;
}
}
感谢您的观看,我当前封装的工具类我觉得挺实用,如果您看到后觉得有什么不好,您在我的博客下边留言。勿喷!!!@本篇文章归本人所有,翻版必究!!!