为什么我的登录没有失败

时间:2013-10-05 15:32:23

标签: jsp servlets

这是我在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);
    }
}
}

1 个答案:

答案 0 :(得分:1)

这是预期的。如果用户名为null,则查询不返回任何内容,因此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
}