Proper protection of XSS and SQL injection (and generally data validation) can occur only on the server side. Client-side validation does not matter, as a malicious user can simply write their own client or send their own HTTP request. Client-side validation is only useful for notifying inappropriate users about a form validation without feedback from the server (for example: make sure the field is a number or an email address). Even in this situation, the server must also perform a check.
To prevent the use of SQL injection, use bind variables (for example, prepared statements) for all parameterized queries. You will never have to concatenate client inputs to generate an SQL query. If you never generate SQL queries from client input and use them only as binding variables, you donβt have to worry about SQL injection at all.
String clientValue = ... Connection conn = ... PreparedStatement stmt = conn.prepare("INSERT INTO foobar VALUES (?)"); stmt.setString(clientValue); stmt.executeUpdate();
Or using Spring JDBC:
String clientValue = ... JdbcTemplate jdbcTemplate = ... jdbcTemplate.update("INSERT INTO foobar VALUES (?)", clientValue);
To prevent XSS, make sure you deactivate all data before exiting. Whitelist client data when it is saved is also usually a good idea if you have an explicit subset of acceptable text, but it becomes more complex when you consider Unicode support. It is generally much easier to handle this on the rendering side.
For example, if you use JSTL to output your output, you should use something like:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> ${fn:escapeXml(myModelVariable)}
source share