[我正在尝试创建一个关于使用Eclipse(MARS)IDE使用Servlet和JSP进行登录以及SQL数据库的非常简单的应用程序。
login.jsp
<body>
<form action="Login"method="post">
Enter username : <input type="text" name="uname"> <br>
Enter password : <input type="password" name="pass"> <br>
<input type="submit" value="login">
</form>
</body>
welcome.jsp
<body>
<%
response.setHeader("Cache-Control", "no-cache,no-store,must-revaildate");
response.setHeader("Pragma","no-cache");
response.setHeader("Expires","0");
if(session.getAttribute("username")==null){
response.sendRedirect("login.jsp");
}
%>
Welcome ${username}
<a href="video.jsp">Videos here </a>
<form action="Logout">
<input type="submit" value="Logout">
</form>
</body>
video.jsp
<body>
<%
response.setHeader("Cache-Control", "no-cache,no-store,must-revaildate");
response.setHeader("Pragma","no-cache");
response.setHeader("Expires","0");
if(session.getAttribute("username")==null){
response.sendRedirect("login.jsp");
}
%>
www.thefeind.mp4
</body>
Logout.java
@WebServlet("/Logout")
public class Logout extends HttpServlet {
private static final long serialVersionUID = 1L;
public Logout() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("username");
session.invalidate();
response.sendRedirect("login.jsp");
}
}
LoginDao.java
public class LoginDao {
String sql ="select * from login where uname=? and pass=?";
String url ="jdbc:mysql://localhost:3306/akash";
String username="root";
String password="";
public boolean check(String uname,String pass){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,username,password);
PreparedStatement st = con.prepareStatement("sql");
st.setString(1,uname);
st.setString(2,pass);
ResultSet rs = st.executeQuery();
if(rs.next()){
return true;
}
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
}
Login.java
public class Login extends HttpServlet {
public Login() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
LoginDao dao = new LoginDao();
if(dao.check(uname, pass)){
HttpSession session = request.getSession();
session.setAttribute("username", uname);
response.sendRedirect("welcome.jsp");
}
else{
response.sendRedirect("login.jsp");
}
}
问题是,使用数据库中存储的正确凭据时,我无法登录。我无法找到为什么在此代码中发生这种情况?
我看到的一个问题是
PreparedStatement st = con.prepareStatement("sql");
必须
PreparedStatement st = con.prepareStatement(sql);