CRUD和文件上传下载

目录

  • 一、CRUD
    • 1.1Pom.xml
    • 1.2.相关配置文件
    • 1.3.web.xml相关配置
    • 1.4.逆向生成
    • 1.5.代码开发
      • 1.5.1 Web层
      • 1.5.2页面层
  • 二、文件上传
    • 2.1pom依赖
    • 2.2Springmvc.xml配置
    • 2.3前台
    • 2.4后台
    • 2.5地址映射
    • 2.6测试
  • 三、文件下载
    • 前端
    • 后端

一、CRUD

1.1Pom.xml




  4.0.0

  org.example
  testssm02
  1.0-SNAPSHOT
  war

  testssm02 Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.8
    1.8
    3.7.0

    
    
    5.0.2.RELEASE
    
    3.4.5
    
    5.1.44
    
    5.1.2
    
    1.3.1
    
    2.1.1
    2.4.3
    
    2.9.1
    
    4.12
    4.0.0
    1.18.2
  

  
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-orm
      ${spring.version}
    
    
      org.springframework
      spring-tx
      ${spring.version}
    
    
      org.springframework
      spring-aspects
      ${spring.version}
    
    
      org.springframework
      spring-web
      ${spring.version}
    
    
      org.springframework
      spring-test
      ${spring.version}
    

    
    
      org.mybatis
      mybatis
      ${mybatis.version}
    
    
    
      mysql
      mysql-connector-java
      ${mysql.version}
    
    
    
      com.github.pagehelper
      pagehelper
      ${pagehelper.version}
    
    
    
      org.mybatis
      mybatis-spring
      ${mybatis.spring.version}
    

    
    
      org.apache.commons
      commons-dbcp2
      ${commons.dbcp2.version}
    
    
      org.apache.commons
      commons-pool2
      ${commons.pool2.version}
    

    
    
    
      org.apache.logging.log4j
      log4j-core
      ${log4j2.version}
    
    
      org.apache.logging.log4j
      log4j-api
      ${log4j2.version}
    
    
    
      org.apache.logging.log4j
      log4j-web
      ${log4j2.version}
    

    
    
      junit
      junit
      ${junit.version}
      test
    
    
      javax.servlet
      javax.servlet-api
      ${servlet.version}
      provided
    
    
      org.projectlombok
      lombok
      ${lombok.version}
      provided
    

    
      org.springframework
      spring-webmvc
      ${spring.version}
    

    
    
      javax.servlet.jsp
      javax.servlet.jsp-api
      2.3.3
    
    
      jstl
      jstl
      1.2
    
    
      taglibs
      standard
      1.1.2
    
  

  
    testssm02
    
      
      
        src/main/java
        
          **/*.xml
        
      
      
      
        src/main/resources
        
          jdbc.properties
          *.xml
        
      
    

    
      
        
          org.apache.maven.plugins
          maven-compiler-plugin
          ${maven.compiler.plugin.version}
          
            ${maven.compiler.source}
            ${maven.compiler.target}
            ${project.build.sourceEncoding}
          
        
        
          org.mybatis.generator
          mybatis-generator-maven-plugin
          1.3.2
          
            
            
              mysql
              mysql-connector-java
              ${mysql.version}
            
          
          
            true
          
        

        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-war-plugin
          3.2.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  

1.2.相关配置文件

applicationContext.xml
applicationContext-mybatis.xml
generatorConfig.xml
jdbc.properties
log4j2.xml
mybatis.cfg.xml
springmvc-servlet.xml

1.3.web.xml相关配置


  Archetype Created Web Application
  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
  
    org.springframework.web.context.ContextLoaderListener
  

  
  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
    
      contextConfigLocation
      /WEB-INF/springmvc-servlet.xml
    
    1
    
    true
  
  
    SpringMVC
    /
  

  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
    true
    
      encoding
      UTF-8
    
  
  
    encodingFilter
    /*
  

1.4.逆向生成

将t_struts_class表逆向生成出Model、Mapper.xml、Mapper.java
分页查询补充

Mapper配置文件


Mapper层

List listPager(Clayy clayy);

Service层

 @Override
    public List listPager(Clayy clayy, PageBean pageBean) {
        return clayyMapper.listPager(clayy);
    }

1.5.代码开发

注意:记得配置aop分页切面
==PagerAspect ==

package com.yzp.util;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
@Aspect
public class PagerAspect {

    /**
     * *:返回值类型
     * *..:无限包
     * *Service:以Service结尾接口名
     * *Pager:以Pager方法
     * 只要同时匹配上诉四个条件,就会被列为目标对象
     * 上述配置要生效,代理注解不能少
     * @param args
     * @return
     * @throws Throwable
     */
    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        Object[] params = args.getArgs();
        PageBean pageBean = null;
        for (Object param : params) {
            if(param instanceof PageBean){
                pageBean = (PageBean)param;
                break;
            }
        }

        if(pageBean != null && pageBean.isPagination())
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());

//        执行目标方法
        Object list = args.proceed(params);

        if(null != pageBean && pageBean.isPagination()){
            PageInfo pageInfo = new PageInfo((List) list);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return list;
    }


}

1.5.1 Web层

package com.yzp.controller;

import com.yzp.biz.ClayyBiz;
import com.yzp.model.Clayy;
import com.yzp.model.dto.ClayyDto;
import com.yzp.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author易泽鹏
 * @site 16670388677
 * @company
 * @create  2022-08-17 19:51
 */
@Controller
@RequestMapping("/cly")
public class ClayycController {

    @Autowired
    private ClayyBiz clayyBiz;
    //list->clylist
    // tolist->重定向list->"redirect:/cly/list"
    // toedit->跳转编辑页面->clyEdit
    //clayy:以前是通过模型驱动接口封装,现在是直接在方法中接收参数即可


    @RequestMapping("/list")
    public  String list(Clayy clayy, HttpServletRequest request){
       PageBean  pageBean = new PageBean();
       pageBean.setRequest(request);
        List lst = this.clayyBiz.listPager(clayy, pageBean);
        request.setAttribute("lst",lst);
        request.setAttribute("pageBean",pageBean);
        return  "clylist";
    }
    @RequestMapping("/toEdit")
    public  String toEdit(Clayy clayy, HttpServletRequest request){
        Integer cid = clayy.getCid();
        //传递的id代表了修改,没传代表新增
        if(cid!=null){
            List lst = this.clayyBiz.listPager(clayy, null);
            request.setAttribute("b",lst.get(0));
        }
        return  "clyedit";
    }
    @RequestMapping("/add")
    public  String add(Clayy clayy){
        this.clayyBiz.insertSelective(clayy);
        return  "redirect:/cly/list";
    }

    /**
     * @valid 是与实体类中的服务端校验 注解配合使用的
     * @param clayy
     * @param bindingResult  存放了所有违背 校验的错误信息
     * @return
     */
    @RequestMapping("/valiAdd")
    public  String valiAdd(@Valid Clayy clayy, BindingResult bindingResult,HttpServletRequest request){
        if(bindingResult.hasErrors()){
            Map msg = new HashMap();
//            违背规则
            List fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //cid :cid不能为空
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
                msg.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
                request.setAttribute("msg",msg);
            //如果出现了错误,应该将提示语显示在表单提示元素后方
            return  "clyedit";
        }else {
            this.clayyBiz.insertSelective(clayy);
        }
        return  "redirect:/cly/list";
    }

    @RequestMapping("/del")
    public  String del(Clayy clayy){
        this.clayyBiz.deleteByPrimaryKey(clayy.getCid());
        return  "redirect:/cly/list";
    }
    @RequestMapping("/edit")
    public  String edit(Clayy clayy){
        this.clayyBiz.updateByPrimaryKeySelective(clayy);
        return  "redirect:/cly/list";
    }

}

1.5.2页面层

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>



    
    
    
    班级相册
    


新增
ID 班级名称 指导老师 班级相册 操作
${b.cid } ${b.cname } ${b.cteacher } 修改 删除 上传图片 下载图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>



    
    班级的编辑界面


cid:${msg.cid}
cname:${msg.cname}
cteacher:${msg.cteacher}
pic:

运行结果:
CRUD和文件上传下载_第1张图片

二、文件上传

2.1pom依赖


      commons-fileupload
      commons-fileupload
      1.3.3

2.2Springmvc.xml配置


        
        
        
        
        
        
    

2.3前台

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/19
  Time: 21:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


2.4后台

建一个dto类

package com.yzp.model.dto;

import com.yzp.model.Clayy;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author易泽鹏
 * @site 16670388677
 * @company
 * @create  2022-08-19 21:19
 */
public class ClayyDto extends Clayy {

    //MultipartFile的属性名一定要跟form中的表单属性名一致
    private MultipartFile picFile;

    public MultipartFile getPicFile() {
        return picFile;
    }

    public void setPicFile(MultipartFile picFile) {
        this.picFile = picFile;
    }
}

上传方法

 @RequestMapping("/upload")
    public  String upload(ClayyDto clayyDto){
        try {
            //前台上传文件
            MultipartFile picFile = clayyDto.getPicFile();
            //实际应该配置resource.properties中
            String diskPath="K:/temp/images/";//图片的存放地址
            //http://localhost:8080/upload/mvc/0516.png
            String requestPath="/upload/mvc/";//数据库保存的地址,也是我们访问的地址


            //拿到上传文件的名字
            String fileName = picFile.getOriginalFilename();//0516.png
            FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(diskPath+fileName));

            //将图片上传之后,并且将图片地址更新到数据库中
            Clayy clayy = new Clayy();
            clayy.setCid(clayyDto.getCid());
            clayy.setPic(requestPath+fileName);
            this.clayyBiz.updateByPrimaryKeySelective(clayy);
        }catch (Exception e){
            e.printStackTrace();
        }

        return  "redirect:/cly/list";
    }

2.5地址映射

CRUD和文件上传下载_第2张图片

2.6测试

测试前
CRUD和文件上传下载_第3张图片
测试后
CRUD和文件上传下载_第4张图片

三、文件下载

前端

 下载图片

后端

  @RequestMapping("/download")
    public  ResponseEntity download(ClayyDto clayyDto){
        try {
            //1.点击下载传递文件的ID  通过文件的ID查询出文件的路径
            Clayy clayy = this.clayyBiz.selectByPrimaryKey(clayyDto.getCid());
            String pic = clayy.getPic();//一个数据库地址/upload/mvc

            //实际应该配置resource.properties中
            String diskPath="K:/temp/images/";//图片的存放地址
            //http://localhost:8080/upload/mvc/0516.png
            String requestPath="/upload/mvc/";//数据库保存的地址,也是我们访问的地址
            //2.通过文件的请求地址  转换成文件存放的硬盘地址
            String realPath = pic.replace(requestPath, diskPath);
            String fileName = realPath.substring(realPath.lastIndexOf("/") + 1);
            //3.将硬盘中文件下载下来-》固定代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

        }catch (Exception e){
            e.printStackTrace();
        }

        return  null;
    }

测试结果:
CRUD和文件上传下载_第5张图片
CRUD和文件上传下载_第6张图片
CRUD和文件上传下载_第7张图片

你可能感兴趣的:(java,mybatis,maven)