1. 程式人生 > >SSM框架整合(基本CRUD+分頁+Excel匯入匯出)

SSM框架整合(基本CRUD+分頁+Excel匯入匯出)

前言

之前學習了SSM(Spring+SpringMVC+Mybatis),一直想自己弄一個小專案自己來寫一下,最近寫了一個,該專案使用Maven進行依賴包管理,使用MySQL5.6資料庫實現了一個管理系統的基礎功能。

(如果喜歡,可以點一個Star又不會懷孕,大家有什麼好的意見,可以pull request一下啦)

如果有什麼問題,也歡迎加入QQ群一起交流啦:416052025

技術棧:

  • JDK 1.8
  • (SSM) -> Spring,SpringMVC,Mybatis
  • BootStrap,JQuery,Bootstrap-table
  • POI
  • Maven
  • SLF4J

已經實現的功能:

  • 使用者登入註冊
  • 學生資訊的增刪改查(CRUD)
  • 學生資料的Excel匯入匯出

後期新增功能:

  • 前後端分離
  • 郵件系統
  • 註冊認證
  • 簡訊API接入
  • ……不僅僅侷限於這些

專案結構

目錄結構

目錄結構

java

  • common:基礎通用類
  • controller:控制層
  • cts:常量類
  • dao:DB倉庫層
  • exception:自定義異常
  • filter:過濾器
  • pojo:實體物件
  • service:業務服務層
  • util:工具類層
  • vo:view-Objct:頁面互動物件

resource

  • mapper:存放mybatis的xml對映檔案
  • appliactionContext.xml:Spring總配置檔案
  • appliactionContext-datasource.xml:資料配置檔案
  • appliactionContext-mvc.xml:Spring mvc配置檔案
  • datasource.properties 資料庫配置檔案
  • generatoorConfig.xml:生成mybatis的xml對映時候的配置檔案
  • logback.xml:日誌配置檔案

webapp

  • assets:靜態檔案目錄
  • WEB-INF
    • pages:頁面檔案
    • web.xml:tomcat的配置檔案
  • index.jsp:引入的入口檔案

pom.xml:Maven配置檔案

基本程式碼演示

這裡寫圖片描述
登入程式碼:

    /**
     * 登入認證
     * @param username
     * @param password
     * @param session
     * @param attributes
     * @return
     */
    @PostMapping("doLogin")
    public String doLogin(String username, String password, HttpSession session, RedirectAttributes attributes){
        try {
            User user=userService.login(username,password);
            session.setAttribute(Constants.CURRENT_USER,user);
            return "redirect:/student/list";
        }catch (Exception e){
            if (e instanceof BusinessException){
                logger.debug(e.getMessage());
                attributes.addAttribute("msg",e.getMessage());
            }
            logger.error(e.getStackTrace().toString(),e.getMessage());
        }
        return "redirect:login";
    }

註冊頁面
註冊:

    /**
     * 註冊認證
     * @param user
     * @param attributes
     * @return
     */
    @PostMapping("/doRegister")
    public String doRegister(User user,RedirectAttributes attributes){
        try {
            User registerUser=userService.register(user);
        }catch (Exception e){
            if (e instanceof BusinessException){
                attributes.addAttribute("msg",e.getMessage());
                return "redirect:register";
            }
        }
        return "redirect:login";
    }

student頁面
這裡寫圖片描述

新增頁面
這裡寫圖片描述
匯入頁面
這裡寫圖片描述

    /**
     * 匯入
     *
     * @param file
     * @return
     */
    @PostMapping("/import")
    //@ResponseBody
    public String importStudent(MultipartFile file) {
        //檔案上傳後處理檔案
        R r = studentService.importStudentExcel(file);
        return "redirect:/student/list";
    }

匯出頁面
這裡寫圖片描述

    /**
     * 匯出
     *
     * @param request
     * @return
     * @throws IOException
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportStudent(HttpServletRequest request) throws IOException {
        File file = studentService.exportStudent();
        HttpHeaders headers = new HttpHeaders();
        //下載顯示的檔名,解決中文名稱亂碼問題
        String downloadFilelName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
        //通知瀏覽器以attachment(下載方式)開啟圖片
        headers.setContentDispositionFormData("attachment", downloadFilelName);
        //application/octet-stream : 二進位制流資料(最常見的檔案下載)。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

excel解析工具類

package cn.lonecloud.student.util;

import com.google.common.collect.Lists;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author lonecloud
 * @version v1.0
 * @date 2017/10/21
 */
public class ExcelUtils {

    private static final String XLS="xls";
    private static final String XLSX="xlsx";

    /**
     * 匯出資料
     * @param file
     * @return
     */
    public static List<String[]> readExcelContent(File  file) {
        List<String[]>  content = Lists.newArrayList();
        String str = "";
        POIFSFileSystem fs=null;
        HSSFWorkbook wb=null;
        HSSFSheet sheet=null;
        HSSFRow row=null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(file));
            wb = new HSSFWorkbook(fs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sheet = wb.getSheetAt(0);
        // 得到總行數
        int rowNum = sheet.getPhysicalNumberOfRows();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文內容應該從第二行開始,第一行為表頭的標題
        for (int i = 0; i < rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            String[] rowContents=new String[colNum];
            while (row!=null&&j < colNum) {
                rowContents[j]=getCellFormatValue(row.getCell(j));
                j++;
            }
            content.add(rowContents);
        }
        return content;
    }

    /**
     * 獲取cell值
     * @param cell
     * @return
     */
    private static String getCellFormatValue(HSSFCell cell) {
        String cellvalue = "";
        if (cell != null) {
            // 判斷當前Cell的Type
            switch (cell.getCellType()) {
                // 如果當前Cell的Type為NUMERIC
                case HSSFCell.CELL_TYPE_NUMERIC:
                case HSSFCell.CELL_TYPE_FORMULA: {
                    // 判斷當前的cell是否為Date
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date型別則,轉化為Data格式

                        //方法1:這樣子的data格式是帶時分秒的:2011-10-12 0:00:00
                        //cellvalue = cell.getDateCellValue().toLocaleString();

                        //方法2:這樣子的data格式是不帶帶時分秒的:2011-10-12
                        Date date = cell.getDateCellValue();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        cellvalue = sdf.format(date);

                    }
                    // 如果是純數字
                    else {
                        // 取得當前Cell的數值
                        cellvalue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                // 如果當前Cell的Type為STRING
                case HSSFCell.CELL_TYPE_STRING:
                    // 取得當前的Cell字串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                // 預設的Cell值
                default:
                    cellvalue = " ";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    /**
     * 匯出Excel
     * @param dataList 資料
     * @param filePath 檔案路徑
     * @param columnNames 列名字
     * @param excludeFiledName 排除的資料值名
     * @return
     * @throws IOException
     * @throws IllegalAccessException
     */
    public static File exportExcel(List dataList, String filePath,String[] columnNames,
                                   String... excludeFiledName) throws IOException, IllegalAccessException {
        File file=new File(filePath);
        if (!file.exists()){
            file.createNewFile();
        }
        // 第一步,建立一個webbook,對應一個Excel檔案
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet
        HSSFSheet sheet = wb.createSheet();
        // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short
        HSSFRow row = sheet.createRow(0);
        // 第四步,建立單元格,並設定值表頭 設定表頭居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式
        //設定標題資訊
        for (int i = 0; i < columnNames.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(columnNames[i]);
            cell.setCellStyle(style);
        }
        for (int i = 0; i < dataList.size(); i++)
        {
            row = sheet.createRow((int) i + 1);
            Object obj = dataList.get(i);
            if (obj!=null){
                Class<?> clazz = obj.getClass();
                Field[] declaredFields = clazz.getDeclaredFields();
                int j=0;
                for (Field field:declaredFields) {
                    if (Arrays.asList(excludeFiledName).stream().equals(field.getName())){
                        continue;
                    }
                    field.setAccessible(true);
                    Object value = field.get(obj);
                    row.createCell(j++).setCellValue(value!=null?value.toString():"-");
                }
            }
        }
        FileOutputStream fos = new FileOutputStream(file);
        wb.write(fos);
        fos.close();
        return file;
    }
}

執行

  1. 下載程式碼
git clone https://github.com/lonecloud/ssm-student
  1. 升級資料庫執行student.sql
  2. 執行maven指令碼
mvn compile
mvn tomcat7:run