简体   繁体   English

防止SQL注入(Java)

[英]Prevent Sql Injection (Java)

I want to secure my application from SQL Injection attacks. 我想从SQL注入攻击中保护我的应用程序。

First question : What is better way to do it? 第一个问题 :有什么更好的方法呢?

The first method: I convert every request to json here: 第一种方法:我将每个请求转换为json:

public JsonObject requestToJson(HttpServletRequest request) throws UnsupportedEncodingException{

        request.setCharacterEncoding("UTF-8");

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) { /*report an error*/ }

        return new JsonParser().parse(jb.toString()).getAsJsonObject();
    }

If it is best way, to prevent it here, then second question: how to do it here? 如果这是最好的方法,在这里防止它,那么第二个问题:这里怎么做?

The second method: It can be done by Hibernate level. 第二种方法:它可以通过Hibernate级别完成。 Second question: how to do it? 第二个问题:怎么做?

Thanks this user: Elliott Frisch . 感谢此用户: Elliott Frisch He answered in comment. 他在评论中回答。

JPARepository like this already prevented from SQL Injection: 这样的JPARepository已经阻止了SQL注入:

public interface UserRepository extends JpaRepository<User, Integer> {
    User findByPhoneNumber(String phoneNumber);
}

Just need to prevent if you using HQL: 如果您使用HQL,只需要防止:

String query1 = "select * from MyBean where id = "+ id;
String query2 = "select * from MyBean where id = :id";

Second one, will be secured. 第二个,将得到保障。

Thanks, everyone. 感谢大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM