sql查询的时候发生注入攻击现象的代码演示
注入攻击的原理**
通俗一点讲就是,登录的表格,通过特殊的字符串作为密码,被提交上去,由于sql本身查询的机制问题,导致注入攻击现象的产生。
示例:select * from user where username=’" + username + “’ and password=’” + password + “’”;
当String password = “abc’ or ‘1’='1”;的时候,or关键字的存在导致查询的条件改变,所以发生了注入攻击的现象。
---- 下面是完整的代码演示
jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/loginServlet" autocomplete="off">
<input type="text" placeholder="请输入账号" name="username">
<input type="text" placeholder="请输入密码" name="password">
<button type="submit">提交</button>
</form>
</body>
</html>
controller层
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取参数
String username = request.getParameter("username");
String password = request.getParameter("password");
//传递参数给service
StudentServiceImpl studentService = new StudentServiceImpl();
boolean flag=studentService.login(username, password);
//判断username和password是否存在,不存在则响应消息“登录失败”,存在则响应消息“登录成功”
if (flag) {
PrintWriter writer = response.getWriter();
writer.write("登录成功");
}else{
response.getWriter().write("登录失败");
}
}
service接口层
public interface StudentService {
boolean login(String username, String password);
}
service接口的实现类
public class StudentServiceImpl implements StudentService {
public StudentDao dao=new StudentDaoImpl();
public boolean login(String username, String password) {
boolean flag=dao.login(username,password);
return flag;
}
}
dao层接口
public interface StudentDao {
ArrayList<Student> findAll();
}
dao层实现类
@Test
public void zhurugongjioo() throws Exception {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接对象
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db911", "root", "root");
//获取执行者对象
Statement state = con.createStatement();
String username = "lisi";
String password = "123456' or '1'='1";
String sql = "select * from user where username='" + username + "' and password='" + password + "'";
Statement stat = con.createStatement();
ResultSet resultSet = stat.executeQuery(sql);
System.out.println(resultSet.next());
}
自己定义的数据库