Understanding XSS and SQL Injection Attacks and Their Prevention in SpringBoot
This article explains the concepts, classifications, and risks of XSS and SQL injection attacks, demonstrates how MyBatis and SpringBoot filters can be used to sanitize inputs and request bodies, and provides practical code examples for implementing robust web application security.
Cross‑Site Scripting (XSS) attacks involve injecting malicious script code into web pages, which is executed when users view the page, compromising user data. XSS is categorized into stored XSS, reflected XSS, and DOM‑based XSS, each with different injection points and impact.
Protection recommendations for XSS include:
Restrict user input types (e.g., age must be an integer, names alphanumeric).
Apply HTML encoding to data.
Filter or remove special HTML tags.
Filter JavaScript event attributes.
SQL injection (SQLi) allows attackers to insert arbitrary SQL statements into database queries, potentially gaining full control over the database, bypassing authentication, and modifying or deleting data.
Using MyBatis with #{} placeholders enables prepared statements, which pre‑compile SQL and replace placeholders with parameters, effectively preventing injection. In contrast, using ${} directly injects values into the SQL string and must be manually sanitized.
<select id="getBlogById" resultType="Blog" parameterType="int">
select id,title,author,content
from blog where id=#{id}
</select>MyBatis achieves SQL pre‑compilation through PreparedStatement, improving both security and performance.
To protect a SpringBoot application from both XSS and SQL injection, a request‑wrapping filter can be created. The filter overrides getParameterValues, getParameter, and getInputStream to clean parameters and JSON request bodies using custom sanitization methods.
public class XssHttpServletRequestWraper extends HttpServletRequestWrapper {
// ... implementation of parameter cleaning and input stream handling ...
}The filter is registered as a Spring component and delegates requests to the wrapper, optionally excluding specific URLs.
@Component
public class XssFilter implements Filter {
// ... filter logic that injects XssHttpServletRequestWraper ...
}Additional JSON body filtering can be achieved by customizing MappingJackson2HttpMessageConverter with a custom StringDeserializer that checks for SQL keywords and XSS patterns before deserialization.
@Configuration
public class MyConfiguration {
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
// configure converter and register StringDeserializer
}
}The StringDeserializer validates input against a list of illegal SQL keywords and XSS characters, throwing a CustomerException when violations are detected.
public class StringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
String str = jsonParser.getText().trim();
if (sqlInject(str)) {
throw new CustomerException("Parameter contains illegal characters");
}
return xssClean(str);
}
// ... sqlInject and xssClean implementations ...
}While the technical content provides comprehensive guidance for securing Java web applications, the article also includes promotional remarks encouraging readers to follow the author’s public account and purchase related courses.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
