@GetMapping("/users") public List<Map<String, Object>> getUser(@RequestParamint id) { Stringsql="SELECT * FROM users WHERE id = ?"; return jdbcTemplate.queryForList(sql, id); } }
2、使用Spring Data JPA或Hibernate
Spring Data JPA或Hibernate自动处理参数化查询,有效防止SQL注入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@RestController publicclassUserController {
@Autowired private UserRepository userRepository;
@GetMapping("/users") public Optional<User> getUser(@RequestParam Long id) { return userRepository.findById(id); } }
@GetMapping("/users") public List<Map<String, Object>> getUser(@RequestParamint id) { // Validate the input if (id <= 0) { thrownewIllegalArgumentException("Invalid ID"); } Stringsql="SELECT * FROM users WHERE id = ?"; return jdbcTemplate.queryForList(sql, id); }