我是jsp的新手,并且在验证用户是否已经在数据库中时遇到了一些问题。这是我的代码:
package bean;
import java.sql.*;
public class LoginDao {
public static boolean validate(LoginBean bean){
boolean status=false;
try (Connection con = ConnectionProvider.getCon()) {
String query = "SELECT * FROM test.UserInfo WHERE email = ? and password = ?";
PreparedStatement statementSQL = con.prepareStatement(query);
statementSQL.setString(1, bean.getEmail());
statementSQL.setString(2, bean.getPassword());
ResultSet resultSet = statementSQL.executeQuery();
status = resultSet.next();
} catch(Exception e){}
return status;
}
}
这里的问题是状态永远不等于真。但是下面的方法工作得很好(我在main方法中尝试了另一个java类):
public static void getSpecificUser(String email, String password) throws SQLException {
try (Connection con = ConnectionProvider.getCon()) {
boolean status = false;
String query = "SELECT * FROM test.UserInfo WHERE email = ? and password = ?";
PreparedStatement statementSQL = con.prepareStatement(query);
statementSQL.setString(1, email);
statementSQL.setString(2, password);
ResultSet resultSet = statementSQL.executeQuery();
status = resultSet.next();
System.out.println(status);
}
}
附加档案:
LoginBean.java
package bean;
public class LoginBean {
private String email, password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String pass) {
this.password = pass;
}
}
loginprocess.jsp(这里我总是得到结果为false,因为LoginDAO.validate())
<%@page import="bean.LoginDao"%>
<jsp:useBean id="obj" class="bean.LoginBean"/>
<jsp:setProperty property="*" name="obj"/>
<jsp:include page="index.jsp"></jsp:include>
<hr/>
<%
out.println(obj.getEmail());
out.println(obj.getPassword());
out.println(LoginDao.validate(obj));
%>
和login.jsp
<%@ include file="index.jsp" %>
<hr/>
<h3>Login Form</h3>
<br/>
<form action="loginprocess.jsp" method="post">
Email:<input type="text" name="email"/><br/><br/>
Password:<input type="password" name="password"/><br/><br/>
<input type="submit" value="login"/>
</form>
我希望有人可以帮助我,因为我无法找到我的错误。
编辑:刚刚在LoginDao类中发现Connection con等于null,但在getSpecificUser()方法中它可以正常工作。我没有发布我的ConnectionProvider类,所以这里是:
package bean;
import java.sql.*;
import static bean.Provider.*;
public class ConnectionProvider {
static Connection con=null;
static{
try{
con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);
}catch(Exception e){}
}
public static Connection getCon(){
return con;
}
}
我无法理解为什么Connection在方法中有效但在我的LoginDao类
中没有