== How to fix it in a Servlet

=== Code examples

The following code is vulnerable to cross-site scripting because it returns an HTML response that contains user input.

Third-party data, such as user input, is not to be trusted.
If embedded in HTML code, it should be HTML-encoded to prevent the injection of additional code. This can be done with the https://owasp.org/www-project-java-encoder/[OWASP Java Encoder] or similar libraries.

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
public void endpoint(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    String data        = request.getParameter("input");
    PrintWriter writer = response.getWriter();

    writer.print(data);
}
----

==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
import org.owasp.encoder.Encode;

public void endpoint(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    String data        = request.getParameter("input");
    PrintWriter writer = response.getWriter();

    writer.print(Encode.forHtml(data));
}
----

If you do not intend to send HTML code to clients, the vulnerability can be fixed by specifying the type of data returned in the response with the content-type header.

For example, setting the content-type to `text/plain` with the `setContentType` function allows to safely reflect user input because browsers will not try to parse and execute the response.

==== Noncompliant code example

[source,java,diff-id=2,diff-type=noncompliant]
----
public void endpoint(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    String data        = request.getParameter("input");
    PrintWriter writer = response.getWriter();

    writer.print(data);
}
----

==== Compliant solution

[source,java,diff-id=2,diff-type=compliant]
----
public void endpoint(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    String data        = request.getParameter("input");
    PrintWriter writer = response.getWriter();

    response.setContentType("text/plain");
    writer.print(data);
}
----

=== How does this work?

include::../../common/fix/data_encoding.adoc[]

`org.owasp.encoder.Encode.forHtml` is the recommended method to encode HTML entities.

=== Pitfalls

include::../../common/pitfalls/content-types.adoc[]

include::../../common/pitfalls/validation.adoc[]

=== Going the extra mile

include::../../common/extra-mile/csp.adoc[]

