2013-10-05 90 views
-1

這是我在我的JSP頁面中登錄的servlet。當我輸入正確的憑據時,它工作正常。如果我只輸入用戶名和空密碼,它會轉到else(invalid.jsp)。但我的問題是,當我沒有爲用戶名和密碼輸入任何東西,或者只是留下用戶名爲空,我的小服務程序失敗,網頁顯示什麼,只是空的。這是爲什麼?請善意解釋,我已經嘗試過並盡力而爲,但仍然無法正常工作。爲什麼我的登錄不成功

package servlet; 

import bean.User; 
import java.io.IOException; 
import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 

public class Login extends HttpServlet { 
@Override 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    try { 
     request.getSession().invalidate(); 

     String username = request.getParameter("user"); 
     String password = request.getParameter("pass"); 
     String fname, lname, idaccount, cat; 

     Connection conn = (Connection) this.getServletContext().getAttribute("conn"); 

     String query = "SELECT username, password, user_type, firstname, lastname, idaccount FROM account WHERE username = ?"; 

     PreparedStatement ps = conn.prepareStatement(query); 
     ps.setString(1, username); 


     ResultSet rs = ps.executeQuery(); 
     while(rs.next()){ 
      cat = rs.getString(3); 
      fname = rs.getString(4); 
      lname = rs.getString(5); 
      idaccount = rs.getString(6); 
      // for testing int test = username.length(); 

      if (username.equals(rs.getString(1)) && (password.equals(rs.getString(2)))) { 
       User users = new User(); 
       users.setUsername(username); 
       users.setPassword(password); 
       users.setCat(cat); 
       users.setIdaccount(idaccount); 
       users.setFname(fname); 
       users.setLname(lname); 

       HttpSession session = request.getSession(); 
       session.setAttribute("user", users); 
       // System.out.println(test); 
       response.sendRedirect("healthlink/home.jsp"); 
      } else { 
       response.sendRedirect("invalid.jsp"); 
      } 
     } 

     rs.close(); 
     ps.close(); 

    } catch (Exception e) { 
     response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
    } 
} 
} 
+0

我的意思是我的標題爲什麼我的登錄失敗... – PeDzKy

回答

1

這是預期的。如果用戶名爲空,則查詢不會返回任何內容,因此rs.next()始終爲false,並且您的方法不會執行任何操作。

while循環其實應該是一個if(因爲不應該有幾個用戶使用相同的用戶名),並應該有一個else條款處理非現有用戶名:

ResultSet rs = ps.executeQuery(); 
if (rs.next()) { 
    // there is a user with this name. Check its password 
} 
else { 
    // there is no user with this name: send back an error response here 
} 
+0

你可以請張貼一些代碼,如果可能的話?我試圖做到這一點,但servlet仍然失敗,我仍然想創建豆... – PeDzKy

+0

o nevermind先生...我知道了..謝謝...也許我只是累了... ...再次感謝你 – PeDzKy