-1

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

1 回答 1

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
}
于 2013-10-05T15:41:33.403 回答