Common Web Security Vulnerabilities and Their Prevention Methods

This article explains several typical web security threats—including XSS, SQL injection, request forgery, CSRF, hotlink protection, upload/download vulnerabilities, and whitelist/blacklist misuse—while providing concrete Java code examples and practical defense techniques to mitigate each risk.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Common Web Security Vulnerabilities and Their Prevention Methods

The document introduces a series of common web security vulnerabilities and demonstrates how to defend against them using Java-based solutions.

1. XSS (Cross‑Site Scripting) – Attackers inject malicious scripts into web pages, which are executed by the browser. Example payloads:

<script>alert('sss')</script>
<script>window.location.href='http://www.baidu.com'</script>

To prevent XSS, input should be filtered or escaped before rendering. A typical approach is to override getParameter in a servlet filter and escape HTML characters:

@Override
public String getParameter(String name) {
    String value = super.getParameter(name);
    if (!StringUtils.isEmpty(value)) {
        value = StringEscapeUtils.escapeHtml(value);
    }
    return value;
}

2. SQL Injection – Unsanitized user input is concatenated into SQL statements, allowing attackers to manipulate queries. Example using MyBatis with string interpolation:

public interface UserMapper {
    @Select("SELECT * FROM user_info WHERE userName='${userName}' AND password='${password}'")
    UserEntity login(UserEntity userEntity);
}

Replacing the ${} placeholder with #{} (prepared statements) eliminates the risk: SELECT * FROM user_info WHERE userName=? AND password=? Another illustration builds the query with StringBuffer:

StringBuffer sbt = new StringBuffer();
sbt.append("SELECT * FROM user_info ");
sbt.append("WHERE userName='" + username + "' ");
sbt.append("AND password='" + password + "'");

3. Ordinary Request Forgery – Manipulating backend API parameters (e.g., dealer advertising requests) can change data for unauthorized users. The suggested mitigation is to generate a server‑side token bound to the user ID, store it in Redis, and validate it on each critical request.

public String addLoginDealer(long dealerId, HttpServletResponse response) {
    String token = T.genetateToken();
    opsForValue.set(dealerId + "-token", token, 1800, TimeUnit.SECONDS);
    // ... create MD5 token, set cookie ...
    return token;
}

Interceptor example that checks the token before processing the request:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String dealerId = getDealerId(request);
    if (T.isBlank(dealerId)) { response.sendRedirect(...); return false; }
    String token = opsForValue.get(dealerId + "-token");
    Cookie cookie = getCookieValue(request, DealerTokenKey.getCookiNameToken());
    if (cookie == null || !MD5Util.encrypt(...).equals(cookie.getValue())) {
        response.sendRedirect(...); return false;
    }
    // refresh token and cookie
    return true;
}

4. CSRF (Cross‑Site Request Forgery) – Attackers trick authenticated users into sending unwanted requests. Defenses include checking the Referer header and adding a per‑request token that is verified server‑side.

5. Hotlink Protection – Prevent other sites from directly linking to your media files by validating the request's Referer against a whitelist.

@WebFilter(filterName = "imgFilter", urlPatterns = "/imgs/*")
public class ImgFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String referer = req.getHeader("Referer");
        if (StringUtils.isEmpty(referer) || !getDomain(referer).equals(domainName)) {
            request.getRequestDispatcher("/imgs/error.png").forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }
    // getDomain implementation omitted for brevity
}

6. Upload/Download Vulnerabilities – Allowing unrestricted file uploads can lead to web shells or arbitrary file execution. Mitigation strategies include strict file‑type validation, size limits, storing files outside the web root, and sanitizing path traversal sequences.

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String root = request.getServletContext().getRealPath("/upload");
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);
    for (FileItem it : items) {
        if (!it.isFormField()) {
            FileType type = getFileType(it.getInputStream());
            if (type == null) { response.getWriter().write("fail"); return; }
            it.write(new File(root + "/" + it.getName()));
            response.getWriter().write("success");
        }
    }
}

Utility method to detect image file signatures:

public static FileType getFileType(InputStream is) throws IOException {
    byte[] src = new byte[28];
    is.read(src, 0, 28);
    StringBuilder sb = new StringBuilder();
    for (byte b : src) {
        sb.append(String.format("%02X", b));
    }
    for (FileType ft : FileType.values()) {
        if (sb.toString().startsWith(ft.getValue())) return ft;
    }
    return null;
}

7. Whitelist & Blacklist – Controlling access to APIs by allowing only trusted IPs (whitelist) or blocking abusive IPs (blacklist) helps prevent unauthorized usage of internal endpoints.

8. Miscellaneous Tips – Hide detailed error messages from users, use multi‑character verification codes, and enforce idempotency for scheduled tasks.

Overall, the article provides a practical checklist and code‑level examples for securing Java web applications against a wide range of common attacks.

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.

JavaCSRFSQL injectionXSSWeb SecurityVulnerability Prevention
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

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.