1. 程式人生 > >Java專案小bug

Java專案小bug

最近在一個專案測試的時候有一些小bug,總結一下以後提醒自己!!!

日期格式問題

專案中的日期是點選之後彈出一個日曆的東西讓使用者選擇;但如果使用者硬是要輸入不規則的字串的話,就會報錯。
解決:校驗字串的格式是否是想要的日期格式

public static boolean isValidDate(String str) {
      boolean convertSuccess=true;
     // 指定日期格式為四位年/兩位月份/兩位日期,注意yyyy/MM/dd區分大小寫;
       SimpleDateFormat format = new SimpleDateFormat
("yyyy/MM/dd HH:mm"); try {      // 設定lenient為false. 否則SimpleDateFormat會比較寬鬆地驗證日期,比如2007/02/29會被接受,並轉換成2007/03/01 format.setLenient(false); format.parse(str); } catch (ParseException e) { // e.printStackTrace(); // 如果throw java.text.ParseException或者NullPointerException,就說明格式不對
convertSuccess=false; } return convertSuccess; }

這樣就會把報錯資訊包裝,不讓使用者看到啦

整數長度限制問題

專案中有一個input是讓輸入整數表示網線長度,但是如果使用者輸入100000000000000000000000的話,就會報錯
解決:限制最大輸入的數字
java中int的範圍:-2147483648~2147483647
可以新增驗證,不能是負數並且不能超過最大範圍

上傳附件問題

專案中填寫資訊的時候需要上傳特定型別的檔案,問題就來了,如果使用者上傳1G大小左右的檔案,頁面就會沒有響應並且卡死在那個介面。
解決:限制上傳檔案的大小和型別

public static String fileUpload(HttpServletRequest request,HttpServletResponse response)throws Exception
{
    //允許上傳的檔案型別
    String fileType = "mp3,mp4,video,rmvb,pdf,txt,xml,doc,gif,png,bmp,jpeg";
    //允許上傳的檔案最大大小(100M,單位為byte)
    int maxSize = 1024*1024*100;
    response.addHeader("Access-Control-Allow-Origin", "*");
    //檔案要儲存的路徑
    String savePath = request.getRealPath("/") + "save/";
    response.setContentType("text/html; charset=UTF-8");
    //檢查目錄
    File uploadDir = new File(savePath);
    if ( !uploadDir.exists())
    {
       uploadDir.mkdirs();
    }
    if ( !uploadDir.canWrite())
    {
       return "上傳目錄沒有寫許可權!";
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024 * 1024); //設定緩衝區大小,這裡是1M
    factory.setRepository(uploadDir); //設定緩衝區目錄

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    List items = upload.parseRequest(request);
    Iterator it = items.iterator();
    FileItem item = null;
    String fileName = "";
    String name = "";
    String extName = "";
    String newFileName = "";
    while (it.hasNext())
    {
        item = (FileItem)it.next();

        fileName = item.getName();
        if (null == fileName || "".equals(fileName))
        {
            continue;
        }

        //判斷檔案大小是否超限
        if (item.getSize() > maxSize)
        {
            item.delete();
            JOptionPane.showMessageDialog(null, "檔案大小超過限制!應小於" + maxSize
                                                / 1024 / 1024 + "M");
            return "檔案大小超過限制!應小於" + maxSize;
        }

        //判斷檔案型別是否匹配
        //            System.getProperties().getProperty("file.separator"))
        //獲取檔名稱
        name = fileName.substring(fileName.lastIndexOf("\\") + 1,
            fileName.lastIndexOf("."));
        //獲取檔案字尾名
        extName = fileName.substring(fileName.indexOf(".") + 1).toLowerCase().trim();

        //判斷是否為允許上傳的檔案型別
        if ( !Arrays.<String> asList(fileType.split(",")).contains(extName))
        {
            item.delete();
            JOptionPane.showMessageDialog(null, "檔案型別不正確,必須為" + fileType
                                                + "的檔案!");
            return "檔案型別不正確,必須為" + fileType
                                                + "的檔案!";
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        newFileName = name + df.format(new Date()) + "." + extName;
        File uploadedFile = new File(savePath, newFileName);
    item.write(uploadedFile);
    }

    return "success";
}

通過getSize()和檔案字尾名可以判斷檔案的大小和型別

Reference

https://www.cnblogs.com/shihaiming/p/6210607.html
https://blog.csdn.net/moyanxuan_1993_2_24/article/details/45693705