2013-12-14 117 views
1

我有一個輸入文本,假設它用於輸入價格。 我有doinsertproducts.jsp驗證碼後,用戶點擊提交按鈕insertproducts.jsp輸入文本驗證錯誤 - JSP

驗證輸入的價格是:

  1. 輸入文本必須填寫。
  2. 輸入文本必須是數字。
  3. 價格必須大於零。

這裏的第一代碼:

if(price.equals("")||price==null){ 
    response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err=Price must be filled."); 
    return; 
} 
else{ 
     try{ 
      intprice=Integer.parseInt(price); 
     } 
     catch (Exception e) { 
      response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err=Price must be numeric."); 
     } 
    } 

而且我不有一個想法在哪裏我已經把第二個代碼來檢查,如果輸入小於1:

if(intprice<1){ 
      response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err=Price must be greater than 0 (zero)."); 
    } 

無論如何,當我執行第一個代碼並嘗試在輸入文本中輸入字符(不包括第二個代碼)時,存在根本原因錯誤:

Cannot call sendRedirect() after the response has been committed 

看起來錯誤還沒有被代碼處理。 是否有解決方案,以便代碼可以檢測到來自用戶的3個錯誤?

+2

旁註:'如果(price.equals( 「」)||價格== NULL)' - '價格== null'不可達。由於'price == null',你會得到NPE。做'if(「」。equals(price))'。 – Maroun

+0

@MarounMaroun仍然有錯誤,看起來像問題是代碼無法處理文本框中的字符輸入 – noobprogrammer

+0

您必須通過javascript/jquery在insertproducts.jsp上處理您的驗證,然後在doinsertproducts.jsp上檢查null並獲取參數。 –

回答

0

試試這個:

String price = request.getParameter("price").toString(); 
String errorMessage = ""; 

if(price != null && price != ""){ 
    try{ 
     intPrice = Integer.parseInt(price); 
     if(intPrice > 0){ 
      System.out.println("Price " + intPrice + " is greater to 0."); 
     }else{ 
      System.out.println("Price " + intPrice + " is less then or equal to 0."); 
     } 
    }catch(Exception ex){ 
     ex.getMessage(); 
     errorMessage = "Price is not a Number."; 
     response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err="+errorMessage); 
    } 
}else{ 
    errorMessage = "Price was not given."; 
    response.sendRedirect("../insertproducts.jsp?insertproduct="+producttype+"&err="+errorMessage); 
} 
+0

@noobprogrammer嘗試上面的代碼,問我,如果你發現任何困難。 –