Springboot+bootstrap界面版之增删改查及图片上传

本次案例采取的是spring data jpa和bootstrap3来完成的,并没有使用github提供的分页插件Pagehelper

 

新建项目

Springboot+bootstrap界面版之增删改查及图片上传_第1张图片

、文件上传的pom.xml依赖


    commons-fileupload
    commons-fileupload
    1.3.1

application.yml文件配置

server:
  servlet:
    context-path: /springboot
spring:
  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/mybatis_ssm?useUnicode=true&characterEncoding=utf8
    username: mybatis_ssm
    password: xiaoli
    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
  thymeleaf:
    cache: false

# 解决图片上传大小限制问题,也可采取配置类
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 60MB

后台代码

Stringutils类

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);
    }
}

PageBean类

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类

public class PageUtil {
    public static String createPageCode(PageBean pageBean) {
        StringBuffer sb = new StringBuffer();
        /*
         * 拼接向后台提交数据的form表单
         * 	注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值
         */
        sb.append("
"); sb.append(""); Map parameterMap = pageBean.getParamMap(); if(parameterMap != null && parameterMap.size() > 0) { Set> entrySet = parameterMap.entrySet(); for (Map.Entry entry : entrySet) { if(!"page".equals(entry.getKey())) { String[] values = entry.getValue(); for (String val : values) { sb.append(""); } } } } 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(); } }

    上传文件映射配置类MyWebAppConfigurer.java

    /**
     * 上传文件映射配置类MyWebAppConfigurer.java
     */
    @Configuration
    public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
        @Override
        protected void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
            registry.addResourceHandler("/uploadImages/**").addResourceLocations("file:F:/temp/");
            super.addResourceHandlers(registry);
        }
    }
    

     

     

     

    实体类

    @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层

    /**
     *
     * 只要继承JpaRepository,通常所用的增删查改方法都有
     * 第一个参数:操作的实体类
     * 第二个参数:实体类对应数据表的主键
     * 
     * 要使用高级查询必须继承
     */
    public interface TeacherDao extends JpaRepository, JpaSpecificationExecutor {
    }

    service层

    public interface TeacherService {
    
        public Teacher save(Teacher teacher);
    
        public void deleteById(Integer id) ;
    
        public Teacher findById(Integer id) ;
    
        public Page listPager(Teacher teacher, PageBean pageBean) ;
    }
    

    service的实现层

    @Service
    public class TeacherServiceImpl implements TeacherService {
    
        @Autowired
        private TeacherDao teacherDao;
    
        @Override
        public Teacher save(Teacher teacher) {
            return teacherDao.save(teacher);
        }
    
        @Override
        public void deleteById(Integer id) {
            teacherDao.deleteById(id);
        }
    
        @Override
        public Teacher findById(Integer id) {
            return teacherDao.findById(id).get();
        }
    
    //    分页
        @Override
        public Page listPager(Teacher teacher, PageBean pageBean) {
    //        jpa的Pageable分页是从0页码开始
    //        PageAspect 不仅仅查了数据,还给pagebean。setTotal()
    //        PageHelper.start("当前页","当页展示记录数")
            Pageable pageable = PageRequest.of(pageBean.getPage()-1, pageBean.getRows());
            return teacherDao.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    Predicate predicate = criteriaBuilder.conjunction();
                    if(teacher != null){
                        if(StringUtils.isNotBlank(teacher.getTname())){
                            predicate.getExpressions().add(criteriaBuilder.like(root.get("tname"),"%"+teacher.getTname()+"%"));
                        }
                    }
                    return predicate;
                }
            },pageable);
        }
    }

    controller层

    @Controller
    @RequestMapping("/teacher")
    public class TeacherController {
        @Autowired
        private TeacherService teacherService;
    
        @RequestMapping("/listPager")
        public ModelAndView list(Teacher teacher, HttpServletRequest request){
            PageBean pageBean = new PageBean();
            pageBean.setRequest(request);
            ModelAndView modelAndView = new ModelAndView();
            Page teachers = teacherService.listPager(teacher,pageBean);
    //       teachers.getContent()== List content = teachers.getContent();
            modelAndView.addObject("teachers",teachers.getContent());
            pageBean.setTotal(teachers.getTotalElements()+"");
            modelAndView.addObject("pageCode", PageUtil.createPageCode(pageBean)/*.replaceAll("<","<").replaceAll(">:",">")*/);
            modelAndView.setViewName("list");
            return 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 = teacherService.findById(teacher.getTid());
                modelAndView.addObject("teacher", t);
            }
            return modelAndView;
        }
    
        @RequestMapping("/add")
        public String add(Teacher teacher, MultipartFile image){
            try {
                String diskPath = "F://temp/"+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);
                }
                teacherService.save(teacher);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "redirect:/teacher/listPager";
        }
    
    
        @RequestMapping("/edit")
        public String edit(Teacher teacher, MultipartFile image){
            String diskPath = "F://temp/"+image.getOriginalFilename();
            String serverPath = "http://localhost:8080/springboot/uploadImages/"+image.getOriginalFilename();
            if(StringUtils.isNotBlank(image.getOriginalFilename())){
                try {
                    FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
                    teacher.setImagePath(serverPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            teacherService.save(teacher);
            return "redirect:/teacher/listPager";
        }
    
        @RequestMapping("/del/{bid}")
        public String del(@PathVariable(value = "bid") Integer bid){
            teacherService.deleteById(bid);
            return "redirect:/teacher/listPager";
        }
    }

    页面层

    list.html

    
    
    
    
        
        书籍列表
        
        
        
        
        
    
    
    
    
    书籍名称:
    新增
    ID 头像 姓名 性别 简介 操作
    删除 修改

    edit.html

    
    
    
    
        
        用户编辑界面
    
        
    
    
    
    

    教员名称:
    教员描述:
    单选回显

    目录截图

    Springboot+bootstrap界面版之增删改查及图片上传_第2张图片

    效果:

    Springboot+bootstrap界面版之增删改查及图片上传_第3张图片

    需要注意以下几点:

    ①将以往的  pageaspect-->pageutil

    ②jpa的Pageable是从第0页开始的  因此 当前页=当前页-1

    ③分页查询返回的数据类型是page (也可以是list) 

    ④文件上传设置可以图片上传大小(在yml文件中配置)

    thymeleaf单选回显,多选回显,下拉选回显,默认选中第一个

    //默认选中第一个
    
    
    //单选回显
    
    
    //多选回显
    
    
    //下拉选回显默认选中 前台接收到参数:user对象和businessList集合
    

     

    你可能感兴趣的:(springboot的学习)