SpringBoot-【1】配置

1、实现登录拦截

# 1、登录页面(为什么用indexPage,直接用index在Linux执行jar的时候访问不到)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
    <link rel="icon" href="./client/favicon.ico" type="image/x-icon"/>
</head>
<body>
<!--中间-->
<div class="divBody">
    <form name="indexPage" method="post" action="">
        <div class="divBody-login">用户登录</div>
        <span class="divBody-name">账号:</span><br>
        <input class="divBody-nameInput" name="name" type="text" ><br>
        <span class="divBody-password">密码:</span><br>
        <input class="divBody-passwordInput" name="password" type="password"><br>
        <!--登录-->
        <div class="divBody-loginButton" onclick="login()">登&nbsp录</div>
        <!--登录错误提示-->
        <span class="divBody-loginInfo" th:text="${user.message}" onerror="this.style.display='none'"></span><br>
    </form>
</div>
</body>
<script type="text/javascript">
    function login(){
        document.indexPage.action="/indexPage";
        document.indexPage.submit();
        return true;
    }
</script>
<style>
</style>
</html>

# 2、Controller登录页面的逻辑
//用户登录
    @RequestMapping(value = "indexPage")
    public String indexPage(HttpSession httpSession, User user) {
        ModelAndView mv = new ModelAndView();
        try {
            User existUser = bigMapper.findUserByUserName(user);
            if (existUser != null) {
                String existPassword = bigMapper.findPasswordByUserName(user);
                if (existPassword.equals(user.getPassword())) {
                    user.setMessage(user.getName() + " 用户登录成功,欢迎您!");
                    //设置用户信息
                    httpSession.setAttribute("user",user);
                    //session存活时间3600==1小时
                    httpSession.setMaxInactiveInterval(28800);
                    //登录成功跳转欢迎界面
                    return "redirect:/welcome";
                } else {
                    user.setMessage("登陆失败,密码错误!");
                }
            } else if(user.getName() == null || user.getName().equals("")){
                user.setMessage("账户名没有输入,请先登录");
            }else{
                user.setMessage("登陆失败,账户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            user.setMessage(e.getMessage());
        }
        mv.addObject("user", user);
        return "indexPage";
    }
#【1】@Resource private BigMapper bigMapper; 这里是mybatis对应的BigMapper.xml的代理接口
#【2】通过查询数据库用户密码与输入密码比对,比对无误则跳转登录成功welcome页面

# 3、登录成功页面welcome
//欢迎首页
    @RequestMapping(value = "welcome")
    public ModelAndView welcome(HttpSession httpSession, User user) {
        ModelAndView mv = new ModelAndView();
        user= (User) httpSession.getAttribute("user");
        //用来传递左侧菜单信息与当前页一级每页多少条信息,看User的内容
        mv.addObject("user", user);
        return mv;
    }
#【1】由于httpSession是共享的,所以再welcome页面同样能拿到user的信息。
#【2】从而可以让登录成功页面的欢迎语使用。 

4、如何拦截非登录页面
package com.day.config;
import com.day.pojo.User;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    //这个方法是在访问接口之前执行的,我们只需要在这里写验证登陆状态的业务逻辑,
    //就可以在用户调用指定接口之前验证登陆状态了。
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse,
                             Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别,我这里使用最简单的Session提取User来验证登陆。
        HttpSession httpSession = httpServletRequest.getSession();
        //这里的User是登陆时放入session的
        User user = (User) httpSession.getAttribute("user");
        //如果session中没有user,表示没登陆
        if (user == null){
            //这个方法返回false表示忽略当前请求,如果一个用户调用了需要登陆才能使用的接口,
            // 如果他没有登陆这里会直接忽略掉。
            //当然你可以利用response给用户返回一些提示信息,告诉他没登陆
            httpServletResponse.sendRedirect
                    (httpServletRequest.getContextPath()+"/indexPage");
            return false;
        }else {
            return true;
            //如果session里有user,表示该用户已经登陆,放行,用户即可继续调用自己需要的接口
        }
    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
【1】只要httpSession获取不到user的信息,就跳转主页

5、配置不需要登录就可以访问的页面合资源
package com.day.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    //Windows与Linux通用,如果是普通jar包参考离线命令使用方法
    private static String systemPath=System.getProperty("user.dir")
            .replaceAll("\\\\", "/");
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
        //System.err.println(systemPath);
        //添加Windows系统下指定目录client为上传文件目录且可以直接回显图片
        //如果是Windows系统
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")) {
            resourceHandlerRegistry.addResourceHandler("/client/**")
                    .addResourceLocations("file:"+systemPath+"/src/main/resources/static/client/");
        }else {  //Linux/Mac
            //注意这里jar包的名称
            resourceHandlerRegistry.addResourceHandler("/client/**")
                    .addResourceLocations("file:"+systemPath+"/client/")//额外配置一个目录
                    /*MyFileWriter.initPrintWriter("/home/xlliu24/Springboot/log.txt");
                    MyFileWriter.printWriter.println("systemPath|"+systemPath);
                    MyFileWriter.printWriter.println("设置存储路径|"+systemPath+"client/");
                    MyFileWriter.printWriter.flush();
                    MyFileWriter.printWriter.close();*/
                    //只能下载,不能上传,上传需要再Controller里配置另外的路径,暂时用这两个同时的方法,一个负责上传一个负责下载
                    .addResourceLocations("classpath:/BOOT-INF/classes/static/client/");
        }
    }
    // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        // addPathPatterns("/**") 表示拦截所有的请求,
        // excludePathPatterns("/login", "/register")
        // 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问。
        interceptorRegistry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/indexPage", "/regist"
                        ,"/client/favicon.ico");
    }
}
#【1】这里排除了/indexPage", "/regist","/client/favicon.ico  也就是非登录就可以访问。
#【2】这里注意:在Linux系统下
.addResourceLocations("classpath:/BOOT-INF/classes/static/client/"); 负责下载的路径
.addResourceLocations("file:"+systemPath+"/client/")//负责上传的路径
#【3】同时注意拦截器的定义与添加
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
    // addPathPatterns("/**") 表示拦截所有的请求,
    // excludePathPatterns("/login", "/register")
    // 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问。
    interceptorRegistry.addInterceptor(loginInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns("/indexPage", "/regist"
                    ,"/client/favicon.ico");
}

2、配置yml文件

# 1、配置yml文件,包括数据库、mybatis、页面存储路径
server:
  port: 8011 #端口号
  tomcat:
    accesslog:
      buffered: true
      directory: /root/SpringBoot
      enabled: true
      file-date-format: .yyyy-MM-dd
      pattern: common
      prefix: access_log
      rename-on-rotate: false
      request-attributes-enabled: false
      rotate: true
      suffix: .log
spring:
  #devtools:
  #restart:
  #enabled=true: #支持热部署  可能导致重启,然后非实时语音转写报错。
  redis: #配置redis
    host: 主机IP
    prot: 6379
  datasource:
    name: mydb
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://主机IP:3306/mydb?serverTimezone=GMT%2b8
    username: 用户名
    password: 密码
    driver-class-name: com.mysql.cj.jdbc.Driver
  thymeleaf:
    prefix: classpath:/site/
    check-template-location: true  #check-tempate-location: 检查模板路径是否存在
    enabled: true
    encoding: UTF-8
    content-type: text/html
    cache: false
    mode: HTML
    suffix: .html
  servlet:
    multipart: #配置文件上传
      max-file-size: 1000MB #设置上传的单个文件最大值,单位可以是 MB、KB,默认为 1MB
      max-request-size: 1024MB #设置多文件上传时,单次内多个文件的总量的最大值,单位可以是 MB、KB,默认为 10 M
mybatis:
  mapper-locations: classpath*:/mybatis/*Mapper.xml
logging:
  level:
    springboot.springbootmaven.mapper: debug
# 2、结合WebAppConfigurer配置下载和上传文件路径
package com.day.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    //Windows与Linux通用,如果是普通jar包参考离线命令使用方法
    private static String systemPath=System.getProperty("user.dir")
            .replaceAll("\\\\", "/");
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
        //System.err.println(systemPath);
        //添加Windows系统下指定目录client为上传文件目录且可以直接回显图片
        //如果是Windows系统
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")) {
            resourceHandlerRegistry.addResourceHandler("/client/**")
                    .addResourceLocations("file:"+systemPath+"/src/main/resources/static/client/");
        }else {  //Linux/Mac
            //注意这里jar包的名称
            resourceHandlerRegistry.addResourceHandler("/client/**")
                    .addResourceLocations("file:"+systemPath+"/client/")//额外配置一个目录
                    /*MyFileWriter.initPrintWriter("/home/xlliu24/Springboot/log.txt");
                    MyFileWriter.printWriter.println("systemPath|"+systemPath);
                    MyFileWriter.printWriter.println("设置存储路径|"+systemPath+"client/");
                    MyFileWriter.printWriter.flush();
                    MyFileWriter.printWriter.close();*/
                    //只能下载,不能上传,上传需要再Controller里配置另外的路径,暂时用这两个同时的方法,一个负责上传一个负责下载
                    .addResourceLocations("classpath:/BOOT-INF/classes/static/client/");
        }
    }
    // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        // addPathPatterns("/**") 表示拦截所有的请求,
        // excludePathPatterns("/login", "/register")
        // 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问。
        interceptorRegistry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/indexPage", "/regist"
                        ,"/client/favicon.ico");
    }
}

3、上传文件Contoller

# 1、Windows与Linux通用代码
 @RequestMapping("insertAhOrderTable")
    public ModelAndView insertAhOrderTable(AhOrderTable ahOrderTable) throws Exception {
        ModelAndView mv=new ModelAndView();
        if(ahOrderTable.getAhOrderTableExcel()!=null){
            String os = System.getProperty("os.name");
            File finalStoreFile=null;
            String storeFileName="";
            String systemPath=System.getProperty("user.dir")
                    .replaceAll("\\\\", "/");
            if(os.toLowerCase().startsWith("win")) {//Windows系统
                String finalPath=systemPath+"/src/main/resources/static/client/";
                String tempFileName=System.currentTimeMillis()+ahOrderTable.getAhOrderTableExcel().getOriginalFilename().substring(ahOrderTable.getAhOrderTableExcel().getOriginalFilename().lastIndexOf("."));
                storeFileName=finalPath+tempFileName;
                finalStoreFile=new java.io.File(storeFileName);
            }else{//Linux系统
                String finalPath=systemPath+"/client/";
                String tempFileName=System.currentTimeMillis()+ahOrderTable.getAhOrderTableExcel().getOriginalFilename().substring(ahOrderTable.getAhOrderTableExcel().getOriginalFilename().lastIndexOf("."));
                storeFileName=finalPath+tempFileName;
                finalStoreFile=new File(storeFileName);
            }
            ahOrderTable.getAhOrderTableExcel().transferTo(finalStoreFile);
            ArrayList<AhOrderTable> ahOrderTableList= ReadExcelUtil2.doReadExcel(new File(storeFileName));
            bigMapper.insertAhOrderTableByList(ahOrderTableList);
            ahOrderTable.setOperateResultInfo("导入完成...");
        }
        mv.addObject("ahOrderTable",ahOrderTable);
        return mv;
    }
# 2、注意上传文件参数的类型,图-1
# 3、注意前端页面传递文件类型参数的写法
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<body>
<form name="insertAhDayTableChoice" method="post" enctype="multipart/form-data">
    <div class="close" id="close">X</div>
    <div class="totalInfo">
        当日比对Excel模板:<a href="./client/当日比对导入模板.xlsx">下载模板</a>
        <input type="file" id="file" class="file" name="ahDayTableExcel">
        <div class="getLocalFile" id="getLocalFile">获取本地文件</div>
        <span class="showFileName" id="showFileName" style="color: red;"></span>
        <div class="uploadButton" id="uploadButton">立即上传</div>
    </div>
</form>
</body>
<script type="text/javascript">
    $("#uploadButton").click(function(callback){
        //必须要先执行上传文件,否则页面重新加载$("#file")[0].files[0]无法执行
        if ($("#file").val() != "") {
            var formData = new FormData();//获取表单中的文件
            formData.append('ahDayTableExcel', $("#file")[0].files[0]);
            //这种方式也可以上传字段,考虑到不返回性,就暂不做集成
            //formData.append('hello','吃饭');
            $.ajax({
                url : "/insertAhDayTable",//后台的接口地址
                type : "post",//post请求方式
                data : formData,//参数
                cache : false,
                processData : false,
                contentType : false,
                success : function() {
                    var url = "/insertAhDayTable";
                    var sendData = {
                        operateResultInfo: "导入完成...",
                        currentPage: parseInt("[[${ahDayTable.currentPage}]]"),
                        pageItem: parseInt("[[${ahDayTable.pageItem}]]"),
                        orderBy: "[[${ahDayTable.orderBy}]]"
                    };
                    $("#myShow").empty();
                    $("#myShow").load(url, sendData);
                    $("#myShow").show();
                    $("#myShade").show();
                },
                error : function() {
                    alert("操作失败~");
                }
            })
        } else {
            alert("没有选择文件,请选择后上传");
            return false;
        }
        var url = "/totalInfo";
        var sendData = {
            infoFlag: "当日-导入"
        };
        $("#myShow").empty();
        $("#myShow").load(url, sendData);
        $("#myShow").show();
        $("#myShade").show();
    });
    $("#close").click(function(){
        $("#myShow").empty();
        $("#myShade").empty();
        $("#myShow").hide();
        $("#myShade").hide();
    });
    $("#getLocalFile").click(function(){
        $('#file').click();
    });
    $("#file").change(function(){
        var filePath=$(this).val();
        if(filePath.indexOf("xls")!=-1 || filePath.indexOf("xlsx")!=-1){
            var array=filePath.split('\\');
            var fileName=array[array.length-1];
            $("#showFileName").html(fileName);
        }else{
            $("#showFileName").html("您上传的文件类型有误!");
            return false;
        }
    });
</script>
<style>
    .close{
        background-color: red;
        width: 30px;
        line-height: 30px;
        font-size: x-large;
        color: white;
        float: right;
        text-align: center;
        cursor: pointer;
    }
    .file{
        /*隐藏原有的文件选择*/
        display: none;
    }
    .getLocalFile{
        margin-top: 20px;
        color: white;
        background-color: grey;
        line-height: 30px;
        width: 200px;
        text-align: center;
        font-size: 18px;
        cursor: pointer;
    }
    .uploadButton{
        margin-top: 20px;
        color: white;
        background-color: #199ED8;
        line-height: 45px;
        width: 200px;
        text-align: center;
        font-size: 18px;
        cursor: pointer;
    }
    .totalInfo{
        width: 60%;
        line-height: 100%;
        color: green;
        font-size: large;
        position: absolute;
        left: 60%;
        top: 40%;
        transform: translate(-50%, -50%);
    }
    .totalInfo a{
        text-decoration: none;
    }
</style>
</html>

 4、读取Excel文件

# 1、把Excel文件读取到程序的List,然后为存到数据库做准备
package com.day.utils;
import com.day.pojo.AhDayTable;
import com.day.pojo.AhOrderTable;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
 
public class ReadExcelUtil1 {
    public static void main(String[] args) throws Exception {
        doReadExcel(new File("src/main/resources/static/client/表1.xlsx"));
    }
    public static ArrayList<AhDayTable> doReadExcel(File xlsFile) throws Exception {
        ArrayList<AhDayTable> ahDayTableList=new ArrayList();
        // 工作表
        Workbook workbook = WorkbookFactory.create(xlsFile);
        // 表个数。
        int numberOfSheets = workbook.getNumberOfSheets();
        // 遍历表。
        for (int i = 0; i < numberOfSheets; i++) {
            Sheet sheet = workbook.getSheetAt(i);
            // 行数。
            int rowNumbers = sheet.getLastRowNum() + 1;
            // Excel第一行。
            Row temp = sheet.getRow(0);
            if (temp == null) {
                continue;
            }
            int cells = temp.getPhysicalNumberOfCells();
            // 读数据。
            for (int row = 0; row < rowNumbers; row++) {
                AhDayTable tempAhDayTable=new AhDayTable();
                Row r = sheet.getRow(row);
                for (int col = 0; col < cells; col++) {
                    String tempResult = "";
                    if(r!=null&&r.getCell(col)!=null) {
                        switch (r.getCell(col).getCellType()) {
                            case NUMERIC: // 数字
                                DecimalFormat df = new DecimalFormat("0");
                                tempResult = df.format(r.getCell(col).getNumericCellValue());
                                break;
                            case STRING: // 字符串
                                tempResult = r.getCell(col).getStringCellValue();
                                break;
                        }
                    }else{
                        tempResult="";
                    }
                    //过滤特殊字符
                    if (StringUtils.isNotBlank(tempResult)) {
                        String[] fbsArr = { "\\", "$","'","/","(", ")", "*", "+", "[", "]", "?", "^", "{", "}", "|" };
                        for (String key : fbsArr) {
                            if (tempResult.contains(key)) {
                                tempResult = tempResult.replace(key, "\\" + key);
                            }
                        }
                    }
                    if (row > 0) {
                        switch (col) {
                            case 0: // 订单编号
                                tempAhDayTable.setOrderCode(tempResult);
                                break;
                            case 1: // 订单内容
                                tempAhDayTable.setOrderContent(tempResult);
                                break;
                            case 2: // 订单数量
                                if(tempResult.equals("")){
                                    tempAhDayTable.setOrderCount(0);
                                }else{
                                    tempAhDayTable.setOrderCount(Integer.parseInt(tempResult));
                                }
                                break;
                            case 3: // 订单价格
                                if(tempResult.equals("")){
                                    tempAhDayTable.setOrderPrice(0.0);
                                }else{
                                    tempAhDayTable.setOrderPrice(Double.parseDouble(tempResult));
                                }
                                break;
                            case 4: // 姓名
                                tempAhDayTable.setOrderPersonName(tempResult);
                                break;
                            case 5: // 手机
                                tempAhDayTable.setOrderPhone(tempResult);
                                break;
                            case 6: // 客户备注
                                tempAhDayTable.setOrderMark(tempResult);
                                break;
                            case 7: // 下单IP
                                tempAhDayTable.setOrderIP(tempResult);
                                break;
                            case 8: // 下单时间
                                //如果时间为空,则设置为2021-01-01
                                if(tempResult==null||tempResult.equals("")){
                                    tempResult="2021-01-01 00:00:00";
                                }else if(tempResult.length()==5){
                                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    Calendar calendar = new GregorianCalendar(1900,0,-2);
                                    calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(tempResult));
                                    tempResult=simpleDateFormat.format(calendar.getTime());
                                }
                                tempAhDayTable.setOrderTimeAnother(tempResult);
                                break;
                            case 9: // 下单地址
                                tempAhDayTable.setOrderAddress(tempResult);
                                break;
                        }
                    }
                }
                // 换行。
                if(row>0){
                    if(tempAhDayTable.getOrderCode().equals("") &&
                            tempAhDayTable.getOrderContent().equals("")&&
                            tempAhDayTable.getOrderCount()==0&&
                            tempAhDayTable.getOrderPrice()==0.0&&
                            tempAhDayTable.getOrderPersonName().equals("")&&
                            tempAhDayTable.getOrderPhone().equals("")&&
                            tempAhDayTable.getOrderMark().equals("")&&
                            tempAhDayTable.getOrderIP().equals("")&&
                            tempAhDayTable.getOrderAddress().equals("")){
                        System.out.print("空行");
                    }else{
                        ahDayTableList.add(tempAhDayTable);
                    }
                }
                tempAhDayTable=null;
                //System.out.println();
            }
        }
        /*for(int i=0;i<ahDayTableList.size();i++){
            AhDayTable tempAhDayTable=ahDayTableList.get(i);
            System.out.println(tempAhDayTable.getOrderPrice());
        }*/
        return ahDayTableList;
    }
}

# 2、Controller里的调用
//数据库操作 表1
    @RequestMapping("insertAhDayTableChoice")
    public ModelAndView insertAhDayTableChoice(AhDayTable ahDayTable) throws Exception{
        ModelAndView mv=new ModelAndView();
        return mv;
    }
    @RequestMapping("insertAhDayTable")
    public ModelAndView insertAhDayTable(AhDayTable ahDayTable) throws Exception{
        ModelAndView mv=new ModelAndView();
        if(ahDayTable.getAhDayTableExcel()!=null){
            String os = System.getProperty("os.name");
            File finalStoreFile=null;
            String storeFileName="";
            String systemPath=System.getProperty("user.dir")
                    .replaceAll("\\\\", "/");
            if(os.toLowerCase().startsWith("win")) {//Windows系统
                String finalPath=systemPath+"/src/main/resources/static/client/";
                String tempFileName=System.currentTimeMillis()+ahDayTable.getAhDayTableExcel().getOriginalFilename().substring(ahDayTable.getAhDayTableExcel().getOriginalFilename().lastIndexOf("."));
                storeFileName=finalPath+tempFileName;
                finalStoreFile=new java.io.File(storeFileName);
            }else{//Linux系统
                String finalPath=systemPath+"/client/";
                String tempFileName=System.currentTimeMillis()+ahDayTable.getAhDayTableExcel().getOriginalFilename().substring(ahDayTable.getAhDayTableExcel().getOriginalFilename().lastIndexOf("."));
                storeFileName=finalPath+tempFileName;
                finalStoreFile=new File(storeFileName);
            }
            ahDayTable.getAhDayTableExcel().transferTo(finalStoreFile);
            ArrayList<AhDayTable> ahDayTableList= ReadExcelUtil1.doReadExcel(new File(storeFileName));
            bigMapper.insertAhDayTableByList(ahDayTableList);
            ahDayTable.setOperateResultInfo("导入完成...");
        }
        mv.addObject("ahDayTable",ahDayTable);
        return mv;
    }

5、数据库操作Mybatis大全

<?xml version="1.0" encoding="UTF-8"?><!-- 动态sql的书写和这个xml文件的路径一定要和mapper包的路径保持一致 -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.day.mapper.BigMapper">
    <!-- 分割线 -->
    <select id="findAllUser"
            parameterType="com.day.pojo.User"
            resultType="com.day.pojo.User">
        select * from user_table
    </select>
    <select id="findUserByUserName"
            parameterType="com.day.pojo.User"
            resultType="com.day.pojo.User">
        select * from user_table where user_table.name = '${user.name}'
    </select>
    <select id="findPasswordByUserName"
            parameterType="com.day.pojo.User"
            resultType="String">
        select password from user_table where user_table.name = '${user.name}'
    </select>
    <insert id="saveUser"
            parameterType="com.day.pojo.User">
        insert into user_table(name,password) values ('${user.name}','${user.password}')
    </insert>
    <!--安徽数据库1 升级版-->
    <insert id="insertAhDayTableByList" parameterType="java.util.List">
        insert into ah_day_table(orderPersonName,orderPhone,orderTime,orderCode,orderCount,orderContent,orderMark,orderAddress,orderIP,orderPrice) values
        <foreach collection ="list" item="ahDayTable" index= "index" separator =",">
            (
            '${ahDayTable.orderPersonName}', '${ahDayTable.orderPhone}',
            '${ahDayTable.orderTimeAnother}','${ahDayTable.orderCode}',
            '${ahDayTable.orderCount}','${ahDayTable.orderContent}',
            '${ahDayTable.orderMark}','${ahDayTable.orderAddress}',
            '${ahDayTable.orderIP}','${ahDayTable.orderPrice}'
            )
        </foreach>
    </insert>
    <!--安徽数据库2 升级版-->
    <insert id="insertAhOrderTableByList" parameterType="java.util.List">
        insert into ah_order_table(orderPersonName,orderPhone,orderContent,orderTime,orderAddress,orderStatus) values
        <foreach collection ="list" item="ahOrderTable" index= "index" separator =",">
            (
            '${ahOrderTable.orderPersonName}', '${ahOrderTable.orderPhone}',
            '${ahOrderTable.orderContent}','${ahOrderTable.orderTimeAnother}',
            '${ahOrderTable.orderAddress}','${ahOrderTable.orderStatus}'
            )
        </foreach>
    </insert>
    <!--安徽数据库3 升级版-->
    <insert id="insertAhSfTableByList" parameterType="java.util.List">
        insert into ah_sf_table(billCode,sendTime,lastLogisticsStatus,orderPersonName,orderPhone,orderContent,orderAddress,orderCount,orderCash) values
        <foreach collection ="list" item="ahSfTable" index= "index" separator =",">
            (
            '${ahSfTable.billCode}','${ahSfTable.sendTimeAnother}',
            '${ahSfTable.lastLogisticsStatus}',
            '${ahSfTable.orderPersonName}','${ahSfTable.orderPhone}',
            '${ahSfTable.orderContent}','${ahSfTable.orderAddress}',
            '${ahSfTable.orderCount}','${ahSfTable.orderCash}'
            )
        </foreach>
    </insert>
    <!--查询-->
    <!--表1-->
    <select id="selectAhDayTableTotalItem" parameterType="com.day.pojo.AhDayTable"
            resultType="Integer">
        select count(id) from ah_day_table
        <where>
            <include refid="selectAhDayTableTotalItem"></include>
        </where>
    </select>
    <sql id="selectAhDayTableTotalItem">
        <!-- 使用动态sql,通过if判断满足条件。有id则查询id,没有则查询分页。 -->
        <if test="ahDayTable!=null">
            <if test="(ahDayTable.idChoose!=null and ahDayTable.idChoose!='')
                      or
                      (ahDayTable.orderPersonNameChoose!=null and ahDayTable.orderPersonNameChoose!='')
                      or
                     (ahDayTable.orderPhoneChoose!=null and ahDayTable.orderPhoneChoose!='')">
                ah_day_table.id= '${ahDayTable.idChoose}'
                or
                ah_day_table.orderPersonName= '${ahDayTable.orderPersonNameChoose}'
                or
                ah_day_table.orderPhone= '${ahDayTable.orderPhoneChoose}'
            </if>
        </if>
    </sql>
    <select id="selectAhDayTable" parameterType="com.day.pojo.AhDayTable"
            resultType="com.day.pojo.AhDayTable">
        select * from ah_day_table
        <where>
            <include refid="selectAhDayTable"></include>
        </where>
        <choose>
            <when test="ahDayTable.orderBy != null and ahDayTable.orderBy!= ''">
                order by ${ahDayTable.orderBy}
            </when>
            <!-- 没有激活排序条件时,默认按商品发布时间倒序排序 asc是默认的从大到小 desc-->
            <otherwise>
                order by id asc
            </otherwise>
        </choose>
        limit ${ahDayTable.startItem},${ahDayTable.endItem};
    </select>
    <sql id="selectAhDayTable">
        <!-- 使用动态sql,通过if判断满足条件。有id则查询id,没有则查询分页。 -->
        <if test="ahDayTable!=null">
            <if test="(ahDayTable.idChoose!=null and ahDayTable.idChoose!='')
                      or
                      (ahDayTable.orderPersonNameChoose!=null and ahDayTable.orderPersonNameChoose!='')
                      or
                     (ahDayTable.orderPhoneChoose!=null and ahDayTable.orderPhoneChoose!='')">
                ah_day_table.id= '${ahDayTable.idChoose}'
                or
                ah_day_table.orderPersonName= '${ahDayTable.orderPersonNameChoose}'
                or
                ah_day_table.orderPhone= '${ahDayTable.orderPhoneChoose}'
            </if>
        </if>
    </sql>
    <!--表2-->
    <select id="selectAhOrderTableTotalItem" parameterType="com.day.pojo.AhOrderTable"
            resultType="Integer">
        select count(id) from ah_order_table
        <where>
            <include refid="selectAhOrderTableTotalItem"></include>
        </where>
    </select>
    <sql id="selectAhOrderTableTotalItem">
        <!-- 使用动态sql,通过if判断满足条件。有id则查询id,没有则查询分页。 -->
        <if test="ahOrderTable!=null">
            <if test="(ahOrderTable.idChoose!=null and ahOrderTable.idChoose!='')
                       or
                      (ahOrderTable.orderPersonNameChoose!=null and ahOrderTable.orderPersonNameChoose!='')
                       or
                      (ahOrderTable.orderPhoneChoose!=null and ahOrderTable.orderPhoneChoose!='')">
                ah_order_table.id= '${ahOrderTable.idChoose}'
                or
                ah_order_table.orderPersonName= '${ahOrderTable.orderPersonNameChoose}'
                or
                ah_order_table.orderPhone= '${ahOrderTable.orderPhoneChoose}'
            </if>
        </if>
    </sql>
    <select id="selectAhOrderTable" parameterType="com.day.pojo.AhOrderTable"
            resultType="com.day.pojo.AhOrderTable">
        select * from ah_order_table
        <where>
            <include refid="selectAhOrderTable"></include>
        </where>
        <choose>
            <when test="ahOrderTable.orderBy != null and ahOrderTable.orderBy!= ''">
                order by ${ahOrderTable.orderBy}
            </when>
            <!-- 没有激活排序条件时,默认按商品发布时间倒序排序 asc是默认的从大到小 desc-->
            <otherwise>
                order by id asc
            </otherwise>
        </choose>
        limit ${ahOrderTable.startItem},${ahOrderTable.endItem};
    </select>
    <sql id="selectAhOrderTable">
        <!-- 使用动态sql,通过if判断满足条件。有id则查询id,没有则查询分页。 -->
        <if test="ahOrderTable!=null">
            <if test="(ahOrderTable.idChoose!=null and ahOrderTable.idChoose!='')
                       or
                      (ahOrderTable.orderPersonNameChoose!=null and ahOrderTable.orderPersonNameChoose!='')
                       or
                      (ahOrderTable.orderPhoneChoose!=null and ahOrderTable.orderPhoneChoose!='')">
                ah_order_table.id= '${ahOrderTable.idChoose}'
                or
                ah_order_table.orderPersonName= '${ahOrderTable.orderPersonNameChoose}'
                or
                ah_order_table.orderPhone= '${ahOrderTable.orderPhoneChoose}'
            </if>
        </if>
    </sql>
    <!--表3-->
    <select id="selectAhSfTableTotalItem" parameterType="com.day.pojo.AhSfTable"
            resultType="Integer">
        select count(id) from ah_sf_table
        <where>
            <include refid="selectAhSfTableTotalItem"></include>
        </where>
    </select>
    <sql id="selectAhSfTableTotalItem">
        <!-- 使用动态sql,通过if判断满足条件。有id则查询id,没有则查询分页。 -->
        <if test="ahSfTable!=null">
            <if test="(ahSfTable.idChoose!=null and ahSfTable.idChoose!='')
                       or
                       (ahSfTable.orderPersonNameChoose!=null and ahSfTable.orderPersonNameChoose!='')
                       or
                       (ahSfTable.orderPhoneChoose!=null and ahSfTable.orderPhoneChoose!='')">
                ah_sf_table.id= '${ahSfTable.idChoose}'
                or
                ah_sf_table.orderPersonName= '${ahSfTable.orderPersonNameChoose}'
                or
                ah_sf_table.orderPhone= '${ahSfTable.orderPhoneChoose}'
            </if>
        </if>
    </sql>
    <select id="selectAhSfTable" parameterType="com.day.pojo.AhSfTable"
            resultType="com.day.pojo.AhSfTable">
        select * from ah_sf_table
        <where>
            <include refid="selectAhSfTable"></include>
        </where>
        <choose>
            <when test="ahSfTable.orderBy != null and ahSfTable.orderBy!= ''">
                order by ${ahSfTable.orderBy}
            </when>
            <!-- 没有激活排序条件时,默认按商品发布时间倒序排序 asc是默认的从大到小 desc-->
            <otherwise>
                order by id asc
            </otherwise>
        </choose>
        limit ${ahSfTable.startItem},${ahSfTable.endItem};
    </select>
    <sql id="selectAhSfTable">
        <!-- 使用动态sql,通过if判断满足条件。有id则查询id,没有则查询分页。 -->
        <if test="ahSfTable!=null">
            <if test="(ahSfTable.idChoose!=null and ahSfTable.idChoose!='')
                       or
                       (ahSfTable.orderPersonNameChoose!=null and ahSfTable.orderPersonNameChoose!='')
                       or
                       (ahSfTable.orderPhoneChoose!=null and ahSfTable.orderPhoneChoose!='')">
                ah_sf_table.id= '${ahSfTable.idChoose}'
                or
                ah_sf_table.orderPersonName= '${ahSfTable.orderPersonNameChoose}'
                or
                ah_sf_table.orderPhone= '${ahSfTable.orderPhoneChoose}'
            </if>
        </if>
    </sql>
    <!--删除数据-->
    <!--设置自增主键编号从1开始-->
    <update id="setAhDayTableIDFrom1">
    alter table ah_day_table AUTO_INCREMENT=1;
    </update>
    <!--表1-->
    <delete id="deleteAhDayTableByTableIDArray" parameterType="java.util.List">
        delete from ah_day_table where id in
        <foreach collection="IDArray" item="item" index="no" open="("
                 separator="," close=")">
            #{item}
        </foreach>
    </delete>
    <!--表2-->
    <delete id="deleteAhOrderTableByTableIDArray" parameterType="java.util.List">
        delete from ah_order_table where id in
        <foreach collection="IDArray" item="item" index="no" open="("
                 separator="," close=")">
            #{item}
        </foreach>
    </delete>
    <!--表3-->
    <delete id="deleteAhSfTableByTableIDArray" parameterType="java.util.List">
        delete from ah_sf_table where id in
        <foreach collection="IDArray" item="item" index="no" open="("
                 separator="," close=")">
            #{item}
        </foreach>
    </delete>
    <!--数据比对  总体需要的数据库操作, useCache="false" 用不到-->
    <!--为了避免null,导致顺丰订单追加不上内容-->
    <update id="updateAhDayTableFiveKeyToSpace">
        update ah_day_table
        set
        repeatPersonName='',
        repeatIP='',
        repeatPhone='',
        repeatAddress='',
        repeatContent= '';
    </update>
    <!--当日VS系统订单姓名-->
    <select id="compareDayAndOrderTableName" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('系统订单',ah_order_table.id,'',ah_order_table.orderStatus)
        as
        table_need_data
        from  ah_day_table join ah_order_table
        ON
        ah_day_table.orderPersonName=ah_order_table.orderPersonName
        GROUP BY ah_day_table.id;
    </select>
    <!--当日VS系统订单手机-->
    <select id="compareDayAndOrderTablePhone" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('系统订单',ah_order_table.id,'',ah_order_table.orderStatus)
        as
        table_need_data
        from  ah_day_table join ah_order_table
        ON
        ah_day_table.orderPhone=ah_order_table.orderPhone
        GROUP BY ah_day_table.id;
    </select>
    <!--当日VS系统订单地址-->
    <select id="compareDayAndOrderTableAddress" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('系统订单',ah_order_table.id,'',ah_order_table.orderStatus)
        as
        table_need_data
        from  ah_day_table join ah_order_table
        ON
        ah_day_table.orderAddress=ah_order_table.orderAddress
        GROUP BY ah_day_table.id;
    </select>
    <!--当日VS系统订单内容-->
    <select id="compareDayAndOrderTablePhoneAndContent" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('系统订单',ah_order_table.id,'',ah_order_table.orderStatus)
        as
        table_need_data
        from  ah_day_table join ah_order_table
        ON
        ah_day_table.orderPhone=ah_order_table.orderPhone
        and
        ah_day_table.orderContent=ah_order_table.orderContent
        GROUP BY ah_day_table.id;
    </select>
    <!-- 查询完毕 升级系统订单-姓名-->
    <update id="updateDayAndOrderTableName" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatPersonName =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then #{item.table_need_data}
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!-- 查询完毕 升级系统订单-手机-->
    <update id="updateDayAndOrderTablePhone" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatPhone =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then #{item.table_need_data}
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!-- 查询完毕 升级系统订单-地址-->
    <update id="updateDayAndOrderTableAddress" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatAddress =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then #{item.table_need_data}
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!-- 查询完毕 升级系统订单-内容-->
    <update id="updateDayAndOrderTablePhoneAndContent" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatContent =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then #{item.table_need_data}
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!--顺丰的表-->
    <!--当日VS顺丰订单姓名-->
    <select id="compareDayAndSfTableName" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('顺丰订单',ah_sf_table.id,'',ah_sf_table.lastLogisticsStatus)
        as
        table_need_data
        from  ah_day_table join ah_sf_table
        ON
        ah_day_table.orderPersonName=ah_sf_table.orderPersonName
        GROUP BY ah_day_table.id;
    </select>
    <!--当日VS顺丰订单手机-->
    <select id="compareDayAndSfTablePhone" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('顺丰订单',ah_sf_table.id,'',ah_sf_table.lastLogisticsStatus)
        as
        table_need_data
        from  ah_day_table join ah_sf_table
        ON
        ah_day_table.orderPhone=ah_sf_table.orderPhone
        GROUP BY ah_day_table.id;
    </select>
    <!--当日VS顺丰订单地址-->
    <select id="compareDayAndSfTableAddress" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('顺丰订单',ah_sf_table.id,'',ah_sf_table.lastLogisticsStatus)
        as
        table_need_data
        from  ah_day_table join ah_sf_table
        ON
        ah_day_table.orderAddress=ah_sf_table.orderAddress
        GROUP BY ah_day_table.id;
    </select>
    <!--当日VS顺丰订单内容-->
    <select id="compareDayAndSfTablePhoneAndContent" resultType="com.day.pojo.Compare">
        select
        ah_day_table.id 'ah_day_table_id',
        GROUP_CONCAT('顺丰订单',ah_sf_table.id,'',ah_sf_table.lastLogisticsStatus)
        as
        table_need_data
        from  ah_day_table join ah_sf_table
        ON
        ah_day_table.orderPhone=ah_sf_table.orderPhone
        and
        ah_day_table.orderContent=ah_sf_table.orderContent
        GROUP BY ah_day_table.id;
    </select>
    <!-- 查询完毕 追加顺丰订单-姓名-->
    <update id="appendDayAndSfTableName" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatPersonName =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then CONCAT(ah_day_table.repeatPersonName,#{item.table_need_data})
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!-- 查询完毕 追加顺丰订单-手机-->
    <update id="appendDayAndSfTablePhone" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatPhone =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then CONCAT(ah_day_table.repeatPhone,#{item.table_need_data})
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!-- 查询完毕 追加顺丰订单-地址-->
    <update id="appendDayAndSfTableAddress" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatAddress =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then CONCAT(ah_day_table.repeatAddress,#{item.table_need_data})
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!-- 查询完毕 追加顺丰订单-内容-->
    <update id="appendDayAndSfTablePhoneAndContent" parameterType="java.util.List">
        update ah_day_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="repeatContent =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清楚历史数据,不为空要注释-->
                    when ah_day_table.id=#{item.ah_day_table_id}
                    then CONCAT(ah_day_table.repeatContent,#{item.table_need_data})
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.ah_day_table_id}
        </foreach>
    </update>
    <!-- 升级顺丰运单状态 -->
    <!--查询需要升级的-->
    <select id="selectAhSfTableByLastLogisticsStatus"
            resultType="com.day.pojo.AhSfTable">
        select
        ah_sf_table.billCode 'billCode',
        ah_sf_table.lastLogisticsStatus 'lastLogisticsStatus'
        from ah_sf_table  where
        ah_sf_table.lastLogisticsStatus!= '正常签收'
        and
        ah_sf_table.lastLogisticsStatus!= '退回签收'
    </select>
    <!--真正升级-->
    <update id="updateAhSfTableLastLogisticsStatusByBillCode" parameterType="java.util.List">
        update ah_sf_table
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="lastLogisticsStatus =case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <!--<if test="item.repeatPersonName!=null"> 为了清除历史数据,不为空要注释-->
                    when ah_sf_table.billCode='${item.billCode}'
                    then '${item.lastLogisticsStatus}'
                    <!-- </if>-->
                </foreach>
            </trim>
        </trim>
        where billCode in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.billCode}
        </foreach>
    </update>
</mapper>

6、Maven引入本地包并打包到JAR

# 1、引入本地包的方法
 <dependency>
            <groupId>com.iflytek.msp.sfexpress</groupId>
            <artifactId>express-sdk</artifactId>
            <version>2.1.5</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/libs/sf-csim-express-sdk-V2.1.5.jar</systemPath>
        </dependency>

# 2、Maven-Package的时候打到JAR包里
 <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                </configuration>
                <version>2.1.5.RELEASE</version>
            </plugin>

7、Thymeleaf使用总结

# 1、设置文本
<div th:text="${user.orderBy}">这是显示欢迎信息</div>
# 2、设置值
<input type="hidden" name="orderBy" th:value="${ahDayTable.orderBy}">
# 3、遍历集合与时间格式化
 <tr th:each="temp:${ahDayTableList}">
        <td><input type="checkbox" class="idList" th:id="${temp.id}"></td>
        <td th:text="${temp.orderIP}"></td>
        <td th:text="${#dates.format(temp.orderTime,'yyyy-MM-dd HH:mm:ss')}"></td>
    </tr>
# 4、JS中使用Thymeleaf
<script th:inline="javascript">
       //对象属性的获取
       if([[${ahDayTable.idChoose}]]!=null){
            $("#idChoose").val([[${ahDayTable.idChoose}]]);
       }
       //设置分页参数
       $("#currentPage").val([[${ahDayTable.currentPage}]]);
       $("#totalItem").text("共"+[[${ahDayTable.totalItem}]]+"条数据");
       //集合数据的获取
       var ahDayTableList=[[${ahDayTableList}]];
</script>

8、前端页面JS使用总结

# 1、使用JS实现多选操作功能
//删除操作
    $("#删除").off("click").click(function(){
        if($('input[class="idList"]:checked').length>0){
            var flag=confirm("确定要删除选中项吗?");
            if(flag){
                var idArray="";
                $($('input[class="idList"]:checked')).each(function(){
                    idArray=idArray+$(this).attr("id")+",";
                });
                //使用load方法处理ajax
                var url = "/totalInfo";
                var sendData = {
                    infoFlag: "当日比对-删除"
                };
                $("#myShow").empty();
                $("#myShow").load(url, sendData);
                $("#myShow").show();
                var url = "/deleteAhDayTable";
                var sendData = {
                    idArray: idArray,
                    currentPage: $("#currentPage").val(),
                    pageItem: $("#pageItem").val(),
                    orderBy: $("#orderBy").val()
                };
                $("#myShow").empty();
                $("#myShow").load(url, sendData);
                $("#myShow").show();
                $("#myShade").show();
            }
        }else{
            confirm("请您先选中后删除!");
        }
    });
    //如果全选或者取消,则子复选框跟着改变。
    $("#idListHeader").click(function(){
        if($(this).is(':checked')){
            $('input[class="idList"]').each(function(){
                //此处如果用attr,会出现第三次失效的情况
                $(this).prop("checked",true);
            });
        }else{
            $('input[class="idList"]').each(function(){
                $(this).prop("checked",false);
            });
            //$(this).removeAttr("checked");
        }
    });
    //如果子复选框全选,则全选状态也跟着改变。
    $('input[class="idList"]').click(function(){
        //方法一,自己改的靠谱
        //console.log($("input[class='idList']").not(":checked").length);
        if ($("input[class='idList']").not(":checked").length <= 0){
            //获取抛弃选中的个数 来进行判断
            $('#idListHeader').prop('checked', true);
        } else {
            $('#idListHeader').prop('checked', false);
        }
    });
# 2、使用JS实现导出
#【1】注意需要引入ExcelExport.js
//导出所需要的JS函数
    //如果使用 FileSaver.js 就不要同时使用以下函数
    function saveAs(obj, fileName) {//当然可以自定义简单的下载文件实现方式
        var tmpa = document.createElement("a");
        tmpa.download = fileName || "下载";
        tmpa.href = URL.createObjectURL(obj); //绑定a标签
        tmpa.click(); //模拟点击实现下载
        setTimeout(function () { //延时释放
            URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
        }, 100);
    }
    function s2ab(s) {
        if (typeof ArrayBuffer !== 'undefined') {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        } else {
            var buf = new Array(s.length);
            for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
    }
    function downloadExcle(data, type) {
        const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };//这里的数据是用来定义导出的格式类型
        // const wopts = { bookType: 'biff2', bookSST: false, type: 'binary' };//xls格式
        const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
        wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通过json_to_sheet转成单页(Sheet)数据
        saveAs(new Blob([s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" }),
            dateFormat(new Date())+ "当日比对"+ '.' + (wopts.bookType=="biff2"?"xls":wopts.bookType));
    }
    $("#导出").off("click").click(function() {
        var ahDayTableList=[[${ahDayTableList}]];
        var finalStr="";
        for(var i=0;i<ahDayTableList.length;i++){
            //console.log(ahDayTableList[i]);
            finalStr=finalStr+"{"
                +"\"订单编号"+"\":"+"\""+ahDayTableList[i].orderCode+"\""
                + ","
                +"\"手机&订单内容重复"+"\":"+"\""+ahDayTableList[i].repeatContent+"\""+"},";
        }
        finalStr="["+finalStr.substring(0,finalStr.length-1)+"]";//获得json字符串
        finalStr=finalStr.replace(/\n/g,' ');
        console.log(finalStr);
        var jsonObject=$.parseJSON(finalStr);//转换为json对象
        //console.log(jsonObject);
        downloadExcle(jsonObject);
    });
# 3、实现日期格式化
【1】先引入moment.js
//日期标准化显示
    function dateFormat(value){
        //console.log(moment(value).format("YYYY-MM-DD HH:mm:ss"));
        return moment(value).format("YYYY-MM-DD HH:mm:ss");
    }

9、集成富文本编辑器

# 1、下载UEditor
# 【1】链接:https://pan.baidu.com/s/17Ly-12c77OoweDYBMmq5pQ 
# 需要提取码的可以聊我~
# 【2】下载后放到static目录下即可,图-1
# 2、在Controller里配置config.json
//UEditor配置config
 @RequestMapping("/config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
        String os = System.getProperty("os.name");
        String rootPath = "";
        String systemPath=System.getProperty("user.dir")
                .replaceAll("\\\\", "/");
        if(os.toLowerCase().startsWith("win")) {//Windows系统
            rootPath=systemPath+"/src/main/resources/static/";
        }else{//Linux系统
            //这里直接去读jar同目录的配置文件config记得存放,否则不能正常上传文件
            //!!!注意config文件与jar包同目录,
            rootPath=systemPath+"/";
            //System.out.println(rootPath);
        }
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
【1】注意:这里如果配置拦截登录,则需要放行/config,否则必须登录后才能使用UEditor
# 3、配置MyWebAppConfigurer
【1】因为富文本的原理,仍是把文件上传到服务器,所以必须配置一个上传文件的访问目录,否则将不能正常使用富文本。我这里使用的是static/client目录,包括配置文件也是写的这个目录。一定要对应正确。
【2】具体配置代码如下
package com.day.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    //Windows与Linux通用,如果是普通jar包参考离线命令使用方法
    private static String systemPath=System.getProperty("user.dir")
            .replaceAll("\\\\", "/");
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
        //System.err.println(systemPath);
        //添加Windows系统下指定目录client为上传文件目录且可以直接回显图片
        //如果是Windows系统
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")) {
            resourceHandlerRegistry.addResourceHandler("/client/**")
                    .addResourceLocations("file:"+systemPath+"/src/main/resources/static/client/");
        }else {  //Linux/Mac
            //注意这里jar包的名称
            resourceHandlerRegistry.addResourceHandler("/client/**")
                    .addResourceLocations("file:"+systemPath+"/client/")//额外配置一个目录
                    /*MyFileWriter.initPrintWriter("/home/xlliu24/Springboot/log.txt");
                    MyFileWriter.printWriter.println("systemPath|"+systemPath);
                    MyFileWriter.printWriter.println("设置存储路径|"+systemPath+"client/");
                    MyFileWriter.printWriter.flush();
                    MyFileWriter.printWriter.close();*/
                    //只能下载,不能上传,上传需要再Controller里配置另外的路径,暂时用这两个同时的方法,一个负责上传一个负责下载
                    .addResourceLocations("classpath:/BOOT-INF/classes/static/client/");
        }
    }
    // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        // addPathPatterns("/**") 表示拦截所有的请求,
        // excludePathPatterns("/login", "/register")
        // 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问。
        interceptorRegistry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/indexPage", "/regist"
                        ,"/client/favicon.ico");
    }
}
# 4、加入Maven包依赖
<!--Rich文本开始-->
<dependency>
    <groupId>com.gitee.qdbp.thirdparty</groupId>
    <artifactId>ueditor</artifactId>
    <version>1.4.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<!--Rich文本结束-->

#5、前端页面的配置与使用
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>RichText</title>
</head>
<body>
<textarea id="tempContent" name="tempContent"
          placeholder="请在此填写内容"
          style="width: 100%; height: 150px; text-align: center; font-size: 14px; padding-top: 5px; font-family: sans-serif;"></textarea>
</body>
<script src="ueditor/ueditor.config.js"></script>
<script src="ueditor/ueditor.all.min.js"></script>
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,
比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
<script src="ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">
    //创建富文本的方法
    UE.getEditor("tempContent");
</script>
</html>
6、最后我们就可以正常的使用了,图-2
【1】效果还是很赞的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值