请用java代码实现SQL注入和XSS漏洞的防护?
时间: 2024-02-11 17:06:33 浏览: 119
SQL注入漏洞的防护示例代码:
1. 使用预编译语句:
```java
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
```
2. 对用户输入的数据进行过滤:
```java
public static boolean isValidInput(String input) {
String regex = "^[a-zA-Z0-9]+$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
return matcher.matches();
}
if (isValidInput(username) && isValidInput(password)) {
String sql = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
}
```
3. 使用ORM框架:
```java
@Entity
@Table(name = "users")
public class User {
@Id
private Long id;
private String username;
private String password;
// getter and setter
}
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = builder.createQuery(User.class);
Root<User> root = query.from(User.class);
query.where(builder.equal(root.get("username"), username))
.where(builder.equal(root.get("password"), password));
List<User> users = entityManager.createQuery(query).getResultList();
```
XSS漏洞的防护示例代码:
1. 对用户输入的数据进行转义:
```java
public static String escapeHtml(String input) {
return StringEscapeUtils.escapeHtml4(input);
}
String username = request.getParameter("username");
String escapedUsername = escapeHtml(username);
out.println("Hello, " + escapedUsername + "!");
```
2. 使用CSP:
```java
response.setHeader("Content-Security-Policy", "default-src 'self'");
```
3. 设置HttpOnly标志:
```java
Cookie cookie = new Cookie("username", "admin");
cookie.setHttpOnly(true);
response.addCookie(cookie);
```
阅读全文