76 lines
2.1 KiB
Plaintext
Raw Normal View History

== How to fix it in Java SE
=== Code examples
include::../../common/fix/code-rationale.adoc[]
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String xml =
"""<user>
<username>"""+req.getParameter("username")+"""</username>
<role>user</role>
</user>""";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.parse(new InputSource(new StringReader(xml))); // Noncompliant
} catch (ParserConfigurationException | SAXException e) {
resp.sendError(400);
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element user = doc.createElement("user");
doc.appendChild(user);
Element usernameElement = doc.createElement("username");
user.appendChild(usernameElement);
username_element.setTextContent(req.getParameter("username"));
Element role = doc.createElement("role");
user.appendChild(role);
role.setTextContent("user");
} catch (ParserConfigurationException e) {
resp.sendError(400);
}
}
----
=== How does this work?
include::../../common/fix/introduction.adoc[]
include::../../common/fix/object.adoc[]
The example compliant code takes advantage of the `javax.xml` and `org.w3c.dom`
libraries capabilities to programmatically build XML documents.
include::../../common/fix/casting.adoc[]