将输入用户名和密码 ans将其传递给validation.jsp
的login.jsp
<center>
<table border="1" cellpadding="5" cellspacing="2">
<thead>
<tr>
<th colspan="2">Login Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>Username</td>
<td><input type="text" name="username" required/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" required/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" />
<input type="reset" value="Reset" />
</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>
validation.jsp
它将验证数据库中的数据并返回;
<%@ page import ="java.sql.*" %>
<%
try{
String username = request.getParameter("username");
String password = request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tejas?" + "user=root&password=tejas");
PreparedStatement pst = conn.prepareStatement("Select user,pass from login where user=tejas and pass=te65");
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
out.println("Valid login credentials");
else
out.println("Invalid login credentials");
}
catch(Exception e){
out.println("Something went wrong !! Please try again");
}
%>`
这是两个保存在webapps文件夹下的代码 webapps文件夹包含web-inf login.jsp validation.jsp
的web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
</web-app>
我需要向web.xml添加内容吗? 请帮忙......
答案 0 :(得分:2)
<强>第一强>
您setString
在查询中没有任何?
,您必须使用,所以如果您想要一些动态,则必须使用:
pst = conn.prepareStatement("Select user,pass from login where user=? and pass=?");
//------------------------------------------------------------------^----------^
pst.setString(1, username);
pst.setString(2, password);
如果您想修改用户名和密码,则无需使用.setString
。