2023-03-07 17:16:47 +01:00
|
|
|
== How to fix it in Java SE
|
|
|
|
|
|
|
|
=== Code examples
|
2023-01-31 14:16:30 +01:00
|
|
|
|
|
|
|
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 {
|
2023-08-18 11:31:42 +02:00
|
|
|
String xml =
|
|
|
|
"""<user>
|
|
|
|
<username>"""+req.getParameter("username")+"""</username>
|
|
|
|
<role>user</role>
|
|
|
|
</user>""";
|
2023-01-31 14:16:30 +01:00
|
|
|
|
|
|
|
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
2023-08-18 11:31:42 +02:00
|
|
|
|
2023-01-31 14:16:30 +01:00
|
|
|
try {
|
|
|
|
DocumentBuilder builder = factory.newDocumentBuilder();
|
2023-08-18 11:31:42 +02:00
|
|
|
builder.parse(new InputSource(new StringReader(xml))); // Noncompliant
|
2023-01-31 14:16:30 +01:00
|
|
|
} 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();
|
2023-08-18 11:31:42 +02:00
|
|
|
|
2023-01-31 14:16:30 +01:00
|
|
|
try {
|
|
|
|
DocumentBuilder builder = factory.newDocumentBuilder();
|
2023-08-18 11:31:42 +02:00
|
|
|
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) {
|
2023-01-31 14:16:30 +01:00
|
|
|
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[]
|
|
|
|
|