1. 程式人生 > >登入防注入最簡單的實現

登入防注入最簡單的實現

原來是這樣寫的,當我登入時輸入:' or 1=1 -- 會導致登入成功!這樣讓我必須要做防注入。
 
 
    /**
     * 獲取登入使用者
     * @param userName
     * @param md5password
     * @return
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getFabaoUser(String userName, String md5password) {
        String loginSQL="select * from CM_CONF_User where Login_Name='"+userName+"' and Password='"+md5password+"'";
        Map<String, Object> u=null;
        try {
            //List<FabaoUser> list = this.findPojoBySqlToBean(loginSQL, FabaoUser.class);
            List<Map<String, Object>> list = this.DBSelect(loginSQL);
            if (list!=null && list.size()>0)  {
                u = list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return u;
    }
後來參考了別人的寫法,使用了預編譯的方法進行防sql注入!
@SuppressWarnings("unchecked")
    public Map<String, Object> getFabaoUser(String userName, String md5password) throws SQLException {
        Connection conn = ConnectionUtil.getConnection();
        String loginSQL="select User_ID from CM_CONF_User where Login_Name= ? and Password=? ";
        PreparedStatement preState = conn.prepareStatement(loginSQL); 
preState.setString(1, userName); preState.setString(2, md5password); ResultSet rs = preState.executeQuery();
if (rs.next()) { String userId = rs.getObject("User_ID").toString(); Map<String, Object> u=new HashMap<String, Object>(); u.put("User_ID", userId); return u; } return null; }