2016-04-15 55 views
0

如果在JSP形式的錯誤,我們希望顯示JSP頁面上正確的錯誤消息,那麼我們就應該在哪裏處理的錯誤在jsp頁面或servlet的驗證錯誤在JSP

+0

你試過'試試catch'塊嗎? – Santhucool

+0

通過這個對你有用http://www.tutorialspoint.com/jsp/jsp_exception_handling.htm – Santhucool

回答

0

絕對不是一個jsp

最好在servlet

理想的輔助類由Servlet稱爲

我會試着勾勒一個簡單的例子:

Servlet類

// within the doPost method 
String email = request.getParameter("email"); 
String password = request.getParameter("password"); 

FormValidator fm = new FormValidator(); 
fm.validateLogin(email, password); 

// the errors attribute will contain a HashMap (returned by 
// the getter method) containing error String literals 
request.setAttribute("errors", fm.getInlineErrors()); 

request.getRequestDispatcher("formpage.jsp").forward(request,response); 

的FormValidator類內內(輔助類)

private HashMap<String, String> errors = new Hashmap<String, String>(); 

// set empty inline errors in the constructor 
public FormValidator(){ 
    errors.put("emailError", ""); 
    errors.put("passwordError", ""); 
    // add other errors for register form... 
} 

public HashMap<String, String> getInlineErrors(){ 
    return errors; 
} 

public void validateLogin(String email, String password){ 
    // put your validation code here 
    // set inline errors accordingly 
} 

// create validateRegister() method 

關於JSP

<form action="Servlet" method="post"> 
    <input type="text" name = "email" value="${email}"/> ${errors['emailError']} 
    <input type="text" name = "password" value="${password}"/> ${errors['passwordError']} 
    <input type="submit" value="Log in"/> 
</form> 

注:

  1. 你不」你不得不爲你的錯誤使用HashMap,喲你可以使用arraylist或數組...我只是喜歡一個HashMap,所以有一個字符串鍵而不是數字索引訪問字段,以避免Jsp頁面上的「幻數」

  2. 你會可能使用內嵌錯誤的登記表格,而不是一個登錄,但登錄表單是更快地在這裏實現

  3. 我沒有把任何HTML標籤,你可能需要將它們添加

這枚方法不能在單個應用程序中提供大規模的重用,因爲您通常不會有超過2個表單(註冊表)呃和登錄),它將允許將表單驗證邏輯封裝在自己的類中,從而使servlet更加輕量:servlet主要負責在應用程序中路由流量。