这是我的 JSP 页面中用于登录的 servlet。当我输入正确的凭据时,它工作正常。如果我只是输入用户名和空密码,它会转到 else (invalid.jsp)。但是我的问题是当我没有为用户名和密码输入任何内容或只是将用户名留空时,我的 servlet 失败,网页什么也不显示,只是空的。这是为什么?请解释一下,我已经尝试过并尽力而为,但仍然无法正常工作。
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);
}
}
}