62 lines
1.8 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 = "<node id=\""+req.getParameter("id")+"\"></node>";
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 {
String xml = "<node></node>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml));
Element element = (Element) doc.getElementsByTagName("node").item(0);
element.setAttribute("id", req.getParameter("id"));
} catch (ParserConfigurationException | SAXException 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[]