So I have this problem where I have my html files in a certain structure, example:
I´m using a form tag which redirects the request to the appropriate servlet file, in the servlet file (java) I use JSOUP to load the content, modify it and send it back as a new webpage. My problem is resource are not getting loaded (such as images, js and css) since servlet publish the file in the root folder. Is their any way to change the default publish site for that specific html?
So for example If I load Page3.html I want it to be able to posted it under the Extras folder not the WebContent folder.
Thanks
My problem is resource are not getting loaded (such as images, js and css)
Either:
Let's dive into the second option.
During the modifications, the code need to set the resources urls properly. Jsoup can help you here. To do so, there is a two steps process:
baseuri
baseuri
The way you set the baseuri
will depend on how you load the content with Jsoup.
This is the easiest way to do it. Jsoup will set the baseuri for you.
Document doc = Jsoup.connect(url).get(); // Document is parsed with baseuri set.
If url host is the server hosting your servlets there may be a code smell here.
If the url is another server, you'll need to parse the document like below:
Jsoup.parse( //
Jsoup.connect(otherServerUrl).response().body(), //
"http://resources-site.com/" //
);
Choose the most appropriate signature for your case in the signatures below and set the baseUri:
Jsoup.parse(html, baseUri);
Jsoup.parse(in, charsetName, baseUri);
Jsoup.parse(html, baseUri, parser);
Jsoup.parse(in, charsetName, baseUri, parser);
Jsoup.parseBodyFragment(bodyHtml, baseUri);
You may check also the sister method Jsoup.parseBodyFragment(bodyHtml, baseUri)
.
Once the baseuri is set, it's time to make urls absolute. See the following Java 8 code:
@SuppressWarnings("serial")
Map<String, String> attributesNames = new HashMap<String, String>() {
{
put("a", "href");
put("img", "src");
}
};
for (Element elt : doc.select(String.join(",", attributesNames.keySet())) {
String elementTagName = elt.tagName();
String attributeName = attributesNames.get(elementTagName);
if (attributeName == null) {
throw new RuntimeException("Unexpected element: " + elementTagName);
}
elt.attr(attributeName, elt.absUrl(attributeName));
}