== How to fix it in Spring

=== Code examples

include::../../common/fix/code-rationale.adoc[]

==== Noncompliant code example

[source,java,diff-id=21,diff-type=noncompliant]
----
@RestController
public class ApiController(
    private val jdbcTemplate: JdbcTemplate
) {
    @GetMapping(value = ["/authenticate"])
    @ResponseBody
    @Throws(SQLException::class)
    fun authenticate(
        @RequestParam("user") user: String?,
        @RequestParam("pass") pass: String?,
    ): ResponseEntity<String> {
        val query = "SELECT * FROM users WHERE user = $user AND pass = $pass"

        val userType = BeanPropertyRowMapper(User::class.java)
        val queryResult = jdbcTemplate.queryForObject<User>(query, userType)
        return if(queryResult != null) {
            ResponseEntity("Authentication Success", HttpStatus.OK)
        } else {
            ResponseEntity("Unauthorized", HttpStatus.UNAUTHORIZED)
        }
    }
}
----

==== Compliant solution

[source,java,diff-id=21,diff-type=compliant]
----
@RestController
public class ApiController(
    private val jdbcTemplate: JdbcTemplate
) {
    @GetMapping(value = ["/authenticate"])
    @ResponseBody
    @Throws(SQLException::class)
    fun authenticate(
        @RequestParam("user") user: String?,
        @RequestParam("pass") pass: String?,
    ): ResponseEntity<String> {
        val query = "SELECT * FROM users WHERE user = ? AND pass = ?"

        val userType = BeanPropertyRowMapper(User::class.java)
        val queryResult = jdbcTemplate.queryForObject<User>(query, userType, user, pass)
        return if(queryResult != null) {
            ResponseEntity("Authentication Success", HttpStatus.OK)
        } else {
            ResponseEntity("Unauthorized", HttpStatus.UNAUTHORIZED)
        }
    }
}

----

=== How does this work?

include::../../common/fix/prepared-statements.adoc[]

