java 执行sql注入_java sql 注入 与防范

1.注入

db9285dc25dd7e074bcb91db5d9f99dd.png

2 .预防

c20570c8a33915c16be58366c4a6cfeb.png

package com.jdbc;

import java.sql.*;

import java.util.Scanner;

public class loginDemo {

public static void main(String[] args)throws ClassNotFoundException, SQLException {

//1.注册驱动

Class.forName("com.mysql.jdbc.Driver");

//2.连接

String url = "jdbc:mysql://localhost:3306/zfj";

String username = "root";

String password = "root";

Connection con = DriverManager.getConnection(url,username,password);

//3.语句执行对象 (执行sql) 返回值 Statement

//Statement stat = con.createStatement();

Scanner sc = new Scanner(System.in);

String user = sc.nextLine();

String pas = sc.nextLine();

//4.执行sql 查询 select

String sql = "SELECT * FROM user where user_name= ? AND user_sex=?";

//防止注入

PreparedStatement pst = con.prepareStatement(sql);

pst.setObject(1,user);

pst.setObject(2,pas);

System.out.println(sql);

ResultSet rs = pst.executeQuery();

//处理结果集

while (rs.next()){

//获取每列的的数据

System.out.println(rs.getString("id")+" "+rs.getString("user_name")+" "+rs.getString("user_age")+" "+rs.getString("user_sex"));

}

//5.释放资源

rs.close();

pst.close();

con.close();

}

}

package com.tarena.dingdang.filter; 02 03 import java.io.IOException; 04 import java.util.Enumeration; 05 06 import javax.servlet.Filter; 07 import javax.servlet.FilterChain; 08 import javax.servlet.FilterConfig; 09 import javax.servlet.ServletException; 10 import javax.servlet.ServletRequest; 11 import javax.servlet.ServletResponse; 12 import javax.servlet.http.HttpServletRequest; 13 14 public class AntiSqlInjectionfilter implements Filter { 15 16 public void destroy() { 17 // TODO Auto-generated method stub 18 } 19 20 public void init(FilterConfig arg0) throws ServletException { 21 // TODO Auto-generated method stub 22 } 23 24 public void doFilter(ServletRequest args0, ServletResponse args1, 25 FilterChain chain) throws IOException, ServletException { 26 HttpServletRequest req=(HttpServletRequest)args0; 27 HttpServletRequest res=(HttpServletRequest)args1; 28 //获得所有请求参数名 29 Enumeration params = req.getParameterNames(); 30 String sql = ""; 31 while (params.hasMoreElements()) { 32 //得到参数名 33 String name = params.nextElement().toString(); 34 //System.out.println("name===========================" + name + "--"); 35 //得到参数对应值 36 String[] value = req.getParameterValues(name); 37 for (int i = 0; i < value.length; i++) { 38 sql = sql + value[i]; 39 } 40 } 41 //System.out.println("============================SQL"+sql); 42 //有sql关键字,跳转到error.html 43 if (sqlValidate(sql)) { 44 throw new IOException("您发送请求中的参数中含有非法字符"); 45 //String ip = req.getRemoteAddr(); 46 } else { 47 chain.doFilter(args0,args1); 48 } 49 } 50 51 //效验
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值