How to Prevent XSS and SQL Injection in SpringBoot: Filters and Code Examples

This article explains XSS attack types, SQL injection risks, and provides practical SpringBoot filter implementations with MyBatis prepared statements and custom deserializers to sanitize request parameters, JSON bodies, and prevent malicious script and database attacks.

Programmer DD
Programmer DD
Programmer DD
How to Prevent XSS and SQL Injection in SpringBoot: Filters and Code Examples

1. XSS Cross‑Site Scripting (XSS) Attack

① XSS vulnerability introduction

Cross‑site scripting (XSS) is an attack where the attacker injects malicious script code into a web page, which is executed when the user views the page, targeting the user layer.

② XSS vulnerability classification

Stored XSS: Persistent code stored on the server (e.g., in user profiles or articles). If not filtered, the code is saved and executed when the page is accessed, potentially stealing cookies.

Reflected XSS: Non‑persistent; requires the user to click a crafted link. Common on search pages.

DOM‑based XSS: Occurs on the client side without backend involvement, based on the Document Object Model (DOM). It is triggered by URL parameters and is essentially a reflected XSS.

③ Protection recommendations

Restrict user input types (e.g., age must be an integer, name alphanumeric).

Apply HTML encoding to data.

Filter or remove special HTML tags.

Filter JavaScript event attributes.

2. SQL Injection Attack

① SQL injection vulnerability introduction

SQL injection (SQLi) allows an attacker to inject malicious SQL statements into a query, gaining full control over the database behind a web application. It can bypass authentication, retrieve entire database contents, and modify or delete records.

SQL injection can affect any site using SQL databases such as MySQL, Oracle, SQL Server, etc., exposing sensitive data.

② Protection recommendations

Using MyBatis with #{} placeholders enables prepared statements that prevent SQL injection.

<select id="getBlogById" resultType="Blog" parameterType="int">
    select id,title,author,content
    from blog where id=#{id}
</select>

MyBatis relies on JDBC PreparedStatement, which compiles the SQL once and substitutes parameters with “?” placeholders, eliminating injection risk.

Using ${} inserts raw values directly into the SQL string and does not prevent injection; such usage must be manually sanitized.

<select id="orderBlog" resultType="Blog" parameterType="map">
    select id,title,author,content
    from blog order by ${orderParam}
</select>

3. Preventing XSS and SQL Injection in SpringBoot

Implement a request filter that wraps HttpServletRequest to sanitize parameters, JSON bodies, and request streams.

1. Create XSS request wrapper class

public class XssHttpServletRequestWraper extends HttpServletRequestWrapper {
    // Override getParameterValues, getParameter, getInputStream
    // Apply cleanXSS and cleanSQLInject on incoming data
    ...
}

2. Register the wrapper in a filter

@Component
public class XssFilter implements Filter {
    private final String[] excludeUrls = new String[]{"null"};
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        XssHttpServletRequestWraper wrapped = new XssHttpServletRequestWraper(request);
        chain.doFilter(wrapped, response);
    }
    ...
}

An alternative approach customizes MappingJackson2HttpMessageConverter with a StringDeserializer that checks for SQL keywords and XSS patterns before deserializing JSON strings.

@Component
public class StringDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String str = p.getText().trim();
        if (sqlInject(str)) {
            throw new CustomerException("Parameter contains illegal characters, request blocked!");
        }
        return xssClean(str);
    }
    // sqlInject and xssClean implementations omitted for brevity
}

Both methods achieve comprehensive XSS and SQL injection protection for request parameters and JSON bodies.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

MyBatisSQL injectionXSSSpringBootRequest SanitizationSecurity Filter
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.