JSP網頁防止sql注入攻擊
SQL注入攻擊指的是通過構建特殊的輸入作為參數傳入Web應用程序,而這些輸入大都是SQL語法里的一些組合,通過執行SQL語句進而執行攻擊者所要的操作,其主要原因是程序沒有細致地過濾用戶輸入的數據,致使非法數據侵入系統。 prepareStatement方法是防止sql注入的簡單有效手段 preparedStatement和statement的區別 1、preparedStatement是statement的子方法 2、preparedStatement可以防止sql注入的問題 3、preparedStatement它可以對它所代表的sql語句進行預編譯,以減輕服務器壓力 實例如下 public User find(String username, String password) {Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try{conn = JdbcUtils.getConnection();String sql = "select * from users where username=? and password=?";st = conn.prepareStatement(sql);st.setString(1, username);st.setString(2, password);rs = st.executeQuery(); //if(rs.next()){User user = new User();user.setId(rs.getString("id"));user.setUsername(rs.getString("username"));user.setPassword(rs.getString("password"));user.setEmail(rs.getString("email"));user.setBirthday(rs.getDate("birthday"));return user;}return null;}catch (Exception e) {throw new DaoException(e);}finally{JdbcUtils.release(conn, st, rs);} }
public User find(String username, String password) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "select * from users where username=? and password=?"; st = conn.prepareStatement(sql); st.setString(1, username); st.setString(2, password); rs = st.executeQuery(); // if(rs.next()){ User user = new User(); user.setId(rs.getString("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setEmail(rs.getString("email")); user.setBirthday(rs.getDate("birthday")); return user; } return null; }catch (Exception e) { throw new DaoException(e); }finally{ JdbcUtils.release(conn, st, rs); } } |