本次案例采取的是spring data jpa和bootstrap3来完成的,并没有使用github提供的分页插件Pagehelper,因为jpa中有分页的方法。
创建springboot项目:
另外还需要的pom依赖:
5.1.44
${mysql.version}
com.alibaba
druid-spring-boot-starter
1.1.10
commons-fileupload
commons-fileupload
1.3.1
application.yml文件配置:
server:
servlet:
context-path: /springboot
spring:
#解决图片上传大小限制问题,也可采取配置类
servlet:
multipart:
max-file-size: 20MB
max-request-size: 60MB
jpa:
hibernate:
ddl-auto: update
show-sql: true
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: root
password: root
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
login-username: admin
login-password: admin
allow: 127.0.0.1
上传文件映射配置类MyWebAppConfigurer.java:
package com.zking.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 资源映射路径
* @author LJ
* @Date 2019/2/22
* @Time 17:56
*/
@Configuration//不写注释这一注解的话图片和下一页样式出不来
public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//一定要加上这里的代码,如果不加意味着static不是静态资源,MVC会把他当成一个请求,然后会拦截
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/uploadImages/**").addResourceLocations("file:D://QQ浏览器下载//图片/");
super.addResourceHandlers(registry);
}
}
后台其他代码:
StringUtils帮助类:
package com.zking.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 17:02
*/
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
/**
* set集合转string
* @param hasPerms
* @return
*/
public static String SetToString(Set hasPerms){
return Arrays.toString(hasPerms.toArray()).replaceAll(" ", "").replace("[", "").replace("]", "");
}
/**
* 转换成模糊查询所需参数
* @param before
* @return
*/
public static String toLikeStr(String before){
return isBlank(before) ? null : "%"+before+"%";
}
/**
* 将图片的服务器访问地址转换为真实存放地址
* @param imgpath 图片访问地址(http://localhost:8080/uploadImage/2019/01/26/20190126000000.jpg)
* @param serverDir uploadImage
* @param realDir E:/temp/
* @return
*/
public static String serverPath2realPath(String imgpath, String serverDir, String realDir) {
imgpath = imgpath.substring(imgpath.indexOf(serverDir));
return imgpath.replace(serverDir,realDir);
}
/**
* 过滤掉集合里的空格
* @param list
* @return
*/
public static List filterWhite(List list){
List resultList=new ArrayList();
for(String l:list){
if(isNotBlank(l)){
resultList.add(l);
}
}
return resultList;
}
/**
* 从html中提取纯文本
* @param strHtml
* @return
*/
public static String html2Text(String strHtml) {
String txtcontent = strHtml.replaceAll("?[^>]+>", ""); //剔出的标签
txtcontent = txtcontent.replaceAll("\\s*|\t|\r|\n", "");//去除字符串中的空格,回车,换行符,制表符
return txtcontent;
}
}
PageBean:
package com.zking.util;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 17:03
*/
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 分页工具类
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 3;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
// 保存上次查询的参数
private Map paramMap;
// 保存上次查询的url
private String url;
public void setRequest(HttpServletRequest request) {
String page = request.getParameter("page");
String rows = request.getParameter("offset");
String pagination = request.getParameter("pagination");
this.setPage(page);
this.setRows(rows);
this.setPagination(pagination);
this.setUrl(request.getRequestURL().toString());
this.setParamMap(request.getParameterMap());
}
public PageBean() {
super();
}
public Map getParamMap() {
return paramMap;
}
public void setParamMap(Map paramMap) {
this.paramMap = paramMap;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if(StringUtils.isNotBlank(page)) {
this.page = Integer.parseInt(page);
}
}
public int getRows() {
return rows;
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.rows = Integer.parseInt(rows);
}
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
if(StringUtils.isNotBlank(total)) {
this.total = Integer.parseInt(total);
}
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
public void setPagination(String pagination) {
if(StringUtils.isNotBlank(pagination) && "false".equals(pagination)) {
this.pagination = Boolean.parseBoolean(pagination);
}
}
/**
* 最大页
* @return
*/
public int getMaxPage() {
int max = this.total/this.rows;
if(this.total % this.rows !=0) {
max ++ ;
}
return max;
}
/**
* 下一页
* @return
*/
public int getNextPage() {
int nextPage = this.page + 1;
if(nextPage > this.getMaxPage()) {
nextPage = this.getMaxPage();
}
return nextPage;
}
/**
* 上一页
* @return
*/
public int getPreviousPage() {
int previousPage = this.page -1;
if(previousPage < 1) {
previousPage = 1;
}
return previousPage;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
PageUtil:
package com.zking.util;
import java.util.Map;
import java.util.Set;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 18:01
* 基于bootstrap3生成分页代码
*/
public class PageUtil {
public static String createPageCode(PageBean pageBean) {
StringBuffer sb = new StringBuffer();
/*
* 拼接向后台提交数据的form表单
* 注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值
*/
sb.append("");
if(pageBean.getTotal()==0){
return "未查询到数据";
}else{
sb.append("首页 ");
if(pageBean.getPage()>1){
sb.append("上一页 ");
}else{
sb.append("上一页 ");
}
for(int i=pageBean.getPage()-1;i<=pageBean.getPage()+1;i++){
if(i<1||i>pageBean.getMaxPage()){
continue;
}
if(i==pageBean.getPage()){
sb.append(""+i+" ");
}else{
sb.append(""+i+" ");
}
}
if(pageBean.getPage()下一页");
}else{
sb.append("下一页 ");
}
sb.append("尾页 ");
}
/*
* 给分页条添加与后台交互的js代码
*/
sb.append("");
return sb.toString();
}
}
实体类entity:
package com.zking.entity;
import lombok.ToString;
import javax.persistence.*;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 16:03
*/
@Entity
@Table(name = "t_springboot_teacher")
@ToString
public class Teacher {
@Id
@GeneratedValue
private Integer tid;
@Column(length = 16)
private String tname;
@Column(length = 4)
private String sex;
@Column(length = 100)
private String description;
@Column(length = 200)
private String imagePath;
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
dao层:
package com.zking.dao;
import com.zking.entity.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 18:03
* 只要继承JpaRepository,通常所用的增删查改方法都有
* 第一个参数:操作的实体类
* 第二个参数:实体类对应数据表的主键
* 要使用高级查询必须继承:
* org.springframework.data.jpa.repository.JpaSpecificationExecutor接口
*/
public interface TeacherDao extends JpaRepository, JpaSpecificationExecutor {
}
service层:
package com.zking.service;
import com.zking.entity.Teacher;
import com.zking.util.PageBean;
import org.springframework.data.domain.Page;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 18:06
*/
public interface TeacherService {
/**
* 新增/修改
* @author LJ
* @Date 2019/2/23
* @Time 13:45
* @param teacher
* @return com.zking.entity.Teacher
*/
public Teacher save(Teacher teacher);
/**
* 删除
* @author LJ
* @Date 2019/2/23
* @Time 13:45
* @param tid
* @return void
*/
public void del(Integer tid);
/**
* 查询单个
* @author LJ
* @Date 2019/2/23
* @Time 13:46
* @param tid
* @return com.zking.entity.Teacher
*/
public Teacher findById(Integer tid);
/**
* 分页查询
* @author LJ
* @Date 2019/2/23
* @Time 13:46
* @param teacher
* @param pageBean
* @return org.springframework.data.domain.Page
*/
public Page listPager(Teacher teacher, PageBean pageBean);
}
service实现层:
package com.zking.service.impl;
import com.zking.dao.TeacherDao;
import com.zking.entity.Teacher;
import com.zking.service.TeacherService;
import com.zking.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 18:11
*/
@Service
public class TeacherServiceImpl implements TeacherService {
@Autowired
private TeacherDao teacherDao;
@Override
public Teacher save(Teacher teacher) {
return this.teacherDao.save(teacher);
}
@Override
public void del(Integer tid) {
this.teacherDao.deleteById(tid);
}
@Override
public Teacher findById(Integer tid) {
return this.teacherDao.findById(tid).get();
}
/**
* 分页查询的方法
* @author LJ
* @Date 2019/2/23
* @Time 13:52
* @param teacher
* @param pageBean
* @return org.springframework.data.domain.Page
* 返回Page而不是List的原因是分页须用到符合查询条件的总记录数,返回Page则
* 可以通过getTotalElements()方法得到,而返回List的话则没有办法得到
*/
@Override
public Page listPager(Teacher teacher, PageBean pageBean) {
//jpa的Pageable分页是从0页码开始,所以第一个参数为当前页数-1
Pageable pageable = PageRequest.of(pageBean.getPage() - 1, pageBean.getRows());
return this.teacherDao.findAll(new Specification() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Predicate predicate = criteriaBuilder.conjunction();
if (teacher != null){
if (teacher.getTname() != null && !"".equals(teacher.getTname())){
predicate.getExpressions().add(criteriaBuilder.like(root.get("tname"),"%"+teacher.getTname()+"%"));
}
}
return predicate;
}
},pageable);
}
}
controller层:
package com.zking.controller;
import com.zking.entity.Teacher;
import com.zking.service.TeacherService;
import com.zking.util.PageBean;
import com.zking.util.PageUtil;
import com.zking.util.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
/**
* @author LJ
* @site www.lijun.com
* @Date 2019年02月22日
* @Time 18:26
*/
@Controller
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
/**
* 分页查询
* @author LJ
* @Date 2019/2/23
* @Time 13:59
* @param teacher
* @param request
* @return org.springframework.web.servlet.ModelAndView
*/
@RequestMapping("/listPager")
public ModelAndView list(Teacher teacher, HttpServletRequest request){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
ModelAndView modelAndView = new ModelAndView();
Page teachers = this.teacherService.listPager(teacher, pageBean);
modelAndView.addObject("teachers",teachers.getContent());
//得到符合查询条件的总记录数
pageBean.setTotal(teachers.getTotalElements()+"");
modelAndView.addObject("pageCode", PageUtil.createPageCode(pageBean));
modelAndView.setViewName("list");
return modelAndView;
}
/**
* 去编辑页面
* @author LJ
* @Date 2019/2/23
* @Time 14:00
* @param teacher
* @return org.springframework.web.servlet.ModelAndView
*/
@RequestMapping("/toEdit")
public ModelAndView toEdit(Teacher teacher){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("edit");
modelAndView.addObject("sexArr",new String[]{"男","女"});
if (teacher.getTid() != null && !"".equals(teacher.getTid())){
Teacher t = this.teacherService.findById(teacher.getTid());
modelAndView.addObject("teacher",t);
}
return modelAndView;
}
/**
* 新增
* @author LJ
* @Date 2019/2/23
* @Time 14:00
* @param teacher
* @param image
* @return java.lang.String
*/
@RequestMapping("/add")
public String add(Teacher teacher, MultipartFile image){
try {
//本地磁盘路径
String diskPath = "D://QQ浏览器下载//图片/" + image.getOriginalFilename();
//服务器路径
String serverPath = "http://localhost:8080/springboot/uploadImages/" + image.getOriginalFilename();
if (StringUtils.isNotBlank(image.getOriginalFilename())){
FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
teacher.setImagePath(serverPath);
}
this.teacherService.save(teacher);
}catch (Exception e){
e.printStackTrace();
}
return "redirect:/teacher/listPager";
}
/**
* 修改
* @author LJ
* @Date 2019/2/23
* @Time 14:01
* @param teacher
* @param image
* @return java.lang.String
*/
@RequestMapping("/edit")
public String edit(Teacher teacher,MultipartFile image){
try {
String diskPath = "D://QQ浏览器下载//图片/" + image.getOriginalFilename();
String serverPath = "http://localhost:8080/springboot/uploadImages/" + image.getOriginalFilename();
if (StringUtils.isNotBlank(image.getOriginalFilename())){
FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
teacher.setImagePath(serverPath);
}
}catch (Exception e){
e.printStackTrace();
}
this.teacherService.save(teacher);
return "redirect:/teacher/listPager";
}
/**
* 删除
* @author LJ
* @Date 2019/2/23
* @Time 14:01
* @param tid
* @return java.lang.String
*/
@RequestMapping("/del/{id}")
public String del(@PathVariable("id") Integer tid){
this.teacherService.del(tid);
return "redirect:/teacher/listPager";
}
}
前台页面:
list.html:
用户列表
新增
ID
头像
姓名
性别
简介
操作
![]()
删除
修改
edit.html:
用户编辑界面
目录结构截图:
运行一波:
注意事项总结:
1、HTML页面中如何获取项目名:
2、超链接传值的两种方式(字符串拼接):
删除
修改
3、三元运算符的写法:
4、utext 与text区别:
utext:在当前标签中追加上html的字符串
text:直接在页面上打印出字符串
效果如下:
5、修改时thymeleaf单选回显、多选回显、下拉选回显、默认选中第一个:
//默认选中第一个
//单选回显
//多选回显
//下拉选回显默认选中 前台接收到参数:user对象和businessList集合
6、后台分页方面:
①分页需要到用到一个 PageUtil,因为自定义标签是基于jsp的 ,所以HTML需通过controller层调方法,传分页值到页面
②jpa内置的分页是从第0页开始查起,所以需要减1
③因为分页需要获取符合查询条件的总记录数,所以分页方法的返回值是Page,而不是List