我有一个项目要进行登录,其中密码是硬编码的,用户名来自数据库。我有一个简单的index.jsp输入用户名和密码,info.jsp可以访问,如果凭证是正确的,可以访问凭证错误时的error.jsp和登录servlet。
这是我的登录servlet:
package webAccess;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("","", "");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from user where USERID=?");
if(username.equals(rs.getString("USERID")) && password.equals("password")){
response.sendRedirect("info.jsp");
}
else {
response.sendRedirect("index.jsp");
}
}
catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
在index.jsp中输入凭据后,只需加载一个空格。
我将代码更改为:
package webAccess;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String USERID = request.getParameter("username");
String PWD = request.getParameter("password");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("","", "");
PreparedStatement ps =con.prepareStatement
("select USERID from user where USERID=?");
ps.setString(1, USERID);
ResultSet rs=ps.executeQuery();
rs.next();
if(USERID.equals(rs.getString("USERID")) && PWD.equals("password")){
response.sendRedirect("info.jsp");
}
else {
response.sendRedirect("error.jsp");
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
如果用户名和密码正确,它将重定向到info.jsp,如果用户名正确且密码不正确,则会重定向到error.jsp。但是,如果用户名无效且密码正确且不正确,则会加载空格。
答案 0 :(得分:0)
您的代码和查询应修改如下:
从USERID =的用户中选择密码?
while(rs.next()) {
if(password.equals(rs.getString("password"))){
response.sendRedirect("info.jsp");
} else {
response.sendRedirect("error.jsp");
}
}