我正在为Java Web应用程序创建登录表单。我让用户通过Java Servlet使用正确的密码登录,但是如果用户输入了错误的密码,我想将用户重定向到另一个JSP页面。我的第一个想法是创建一个try / catch语句。但是,尝试此操作时会收到空白页。如何确保用户知道输入密码错误的时间?谢谢
public class Loginn extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
MyDb1 db = new MyDb1();
Connection con = db.getCon();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select uid,name,pass from register where email = '"+name+"' and pass = '"+pass+"'");
while ((rs.next())) {
String uid = rs.getString("uid");
HttpSession session=request.getSession();
session.setAttribute("name",uid);
response.sendRedirect("http://localhost:8080/Final_Year_Project_5_/userprofile.jsp");
}
} catch (SQLException ex) {
Logger.getLogger(Loginn.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:1)
尝试使用if
和else
,
public class Loginn extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
MyDb1 db = new MyDb1();
Connection con = db.getCon();
PreparedStatement ps = c.prepareStatement("select uid,name,pass from register where email = ? and pass = ?");
ps.setString(1, un);
ps.setString(2, pw);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String uid = rs.getString("uid");
HttpSession session=request.getSession();
session.setAttribute("name", uid);
response.sendRedirect("userprofile.jsp"); // No need to add whole URL unless this is in another Folder.
} else {
response.sendRedirect("error.jsp");
}
} catch (SQLException ex) {
Logger.getLogger(Loginn.class.getName()).log(Level.SEVERE, null, ex);
}
答案 1 :(得分:1)
您的代码是安全漏洞。想象一下,我将Web表单放在pass字段中:
whatever' OR TRUE;--
我要登录(只需将该字符串放入查询中,然后将其打印回去,看看它会做什么...
您需要使用PreparedStatement
,用问号替换所有变量。
JSP是过时的技术,您的异常处理使连接处于浮动状态。我建议这样做:throw new ServletException(ex)
,至少,然后在正确的位置(servlet容器)进行错误处理。
空白页可能是由于您处理异常的方式(先记录它们,然后不执行任何操作,导致空白页)。解决此问题,现在您可以查看一个实际的错误。