這是我在我的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);
}
}
}
我的意思是我的標題爲什麼我的登錄失敗... – PeDzKy