【发布时间】:2016-05-07 14:36:12
【问题描述】:
我想知道是否可以使用选择下拉列表中的字符串在 sql 语句中使用。例如,用户从下拉框中选择“学生”,该下拉框应用于选择要在数据库中搜索的表。
index.jsp
<% @page language = "java"
contentType = "text/html; charset=ISO-8859-1"
pageEncoding = "ISO-8859-1" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< meta http - equiv = "Content-Type"
content = "text/html; charset=ISO-8859-1" >
< title > Home < /title>
</head >
< body >
< form method = "post"
action = "validate.jsp" >
< center > < h2 style = "color:green" > eBooking Login < /h2></center >
< table border = "0"
align = "center" >
< tr >
< td > Enter Your Name: < /td>
<td><input type="text" name="username" required></td >
< /tr>
<tr>
<td>Enter Your Password :</td >
< td > < input type = "password"
name = "password"
required / > < /td>
</tr >
< tr >
< td > Select User Type: < /td>
<td><select name="usertype">
<option value="select">Student</option >
< option value = "select" > PAT < /option>
<option value="select">Administrator</option >
< /select>
</td >
< /tr>
<tr>
<td></td >
< td > < input type = "submit"
value = "Login" / > < /td>
</table >
< /form>
</body >
< /html>
验证.jsp
<% @page language = "java"
contentType = "text/html; charset=ISO-8859-1"
pageEncoding = "ISO-8859-1" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<% @page import = "java.sql.*" %>
<%
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
String usertype = request.getParameter("usertype");
String driver = ("com.mysql.jdbc.Driver");
Class.forName(driver); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ebooking" + "?user=user&password=user");
PreparedStatement pst = conn.prepareStatement("Select * from ? where stu_username=? and stu_password=?");
pst.setString(1, usertype);
pst.setString(2, username);
pst.setString(3, password);
ResultSet rs = pst.executeQuery();
session.setAttribute("username", username);
if (rs.next())
response.sendRedirect("studentwelcome.jsp");
else
out.println("Invalid login credentials");
} catch (Exception e) {
System.out.println(e);
out.println("Something went wrong !! Please try again");
} %>
studentwelcome.jsp
<% @page language = "java"
contentType = "text/html; charset=ISO-8859-1"
pageEncoding = "ISO-8859-1" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< meta http - equiv = "Content-Type"
content = "text/html; charset=ISO-8859-1" >
< title > Student Welcome < /title>
</head >
< body >
Welcome <%= session.getAttribute("username") %>
< /body>
</html >
【问题讨论】:
-
这是一件非常危险的事情。您不应该在 sql 语句中使用未经处理的用户输入。阅读 SQL 注入,您应该会找到一些替代方法。
-
@MarkChorley 哦,我明白了。我绝对明白。我可以看到黑客如何利用这一点。谢谢。