Attaching a CSS file to a Java Servlet in Tomcat [duplicate] - java

This question already has answers here:
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
(9 answers)
Closed 5 years ago.
After a lot of looking around on various forums and such, I was not able to find an answer to my question.
I want to attach a stylesheet to my servlet instead of having to use <style> tags.
I am using Apache Tomcat 7 in Eclipse and I am manually writing the html code (via a PrintWriter).
I've tried putting the .css file in the ROOT of the WebApp. I've tried putting it in the css. Nothing is working.
Can someone point me in the right direction?
Here is some code that I tried.
Attempt 1 (css is in a folder. WebContent/css:
String cssLocation = request.getContextPath() + "/WebContent/css/styles2.css";
String cssTag = "<link rel='stylesheet' type='text/css' href='" + cssLocation + "'>";
Attempt 2 (css is in the ROOT):
String cssLocation = request.getContextPath() + "/styles2.css";
String cssTag = "<link rel='stylesheet' type='text/css' href='" + cssLocation + "'>";
Neither of those worked.
EDIT: Here is my directory structure:
PROJECT ROOT
src
testPackage
DownloadServlet.java
WebContent
css
styles2.css
files
fonts
js
META-INF
WEB-INF
index.html
To explain: I am trying to reference /WebContent/css/styles2.css in DownloadServlet.java
How I am doing that:
In the method 'doGet', I am initializing a `PrintWriter'. I'm printing out:
<html>
<head>
HERE IS WHERE THE LINK NEEDS TO GO
</head>
<body>
...
</body>
</html>
Where the text "HERE IS WHERE THE LINK NEEDS TO GO" is, that is where I need the link to the css file. I've tried the methods above, but I had no luck.

Just a guess: Try String cssTag = "<link rel='stylesheet' type='text/css' href='/css/styles.css'>";
The browser will look for the css file in the sub-folder of the root directory of the server, which is in your case the WebContent-directory. You usually don't need to call request.getContextPath() when linking resources inside HTML tags.

First you create the css file, suppose style.css in the folder name css inside the WebContent directory of your project.
Then, you must know the tomcat server path where the .css file is located.
String cssTag="<link rel='stylesheet' type='text/css' href='css/style.css'>"
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head><title>Title Name</title>"+cssTag+"</head>");
out.println("<body>");
/*
Your code
*/
out.println("</body></html>")

Related

how to apply css files in servlet code written inside jsp file?

Below is my code. I have all css files in webcontent root and inside css folder.
String cssLocation = request.getContextPath() + "/WebContent/css/style.css";
String cssTag = "<link rel='stylesheet'<img class=gallery_img'> type='text/css' href=' "+ cssLocation +" '>";
out.println("<h4> <p><div class='gallery_img'> " + rs.getString("title") + "</div></div></P></h4>");
out.println("");
out.println("<a href='#'><div style='float:left;width:10% border:10px solid;padding:20px ;'><link rel='stylesheet' type='text/css' href='css/style.css'><table style='width:50%' ><td><img width='230' height='230' src=displayphoto?id=" + rs.getString("id") + " style='opacity: 1'></img></td></table></body></a> <p/>");
All jsp files are converted into servlet java files and compiled, you can simply call this jsp file and go get the servlet file from the cache directory. copy the css part and paste into your own servlet,you can even make it a function or a seperate class.
If you can't find the servlet cache directory simply search the name of the jsp file without extension on the hard drive, you will see that there is a java file with that name.
Good Luck

Some URL patterns lose css

I'm making a simple servlet app, which is supposed to produce the same output for the following URL patterns:
#WebServlet(urlPatterns={"/Start", "/Start/*", "/Startup", "/Startup/*"})
The output for the following addresses is correct:
http://localhost:4413/TestA/Startup
http://localhost:4413/TestA/Start
http://localhost:4413/TestA
However, once I try something like this:
http://localhost:4413/TestA/Startup/
or
http://localhost:4413/TestA/Startup/blablabla
The css file does not see it.
What could be wrong here?
The css links are of the form:
<link rel="StyleSheet" href="res/mc.css" type="text/css" title="cse4413" media="screen, print"/>
This depends on how you have included the CSS file. If you had included like:
<link href="css/style.css" />
Then, it won't work on directory structures. So change your code, which is similar to the above one like this:
<link href="/css/style.css" />
You need to provide the relative path to the domain, not the file. So that it always requests the right URL.
Solved the problem by setting href to
href="${pageContext.request.contextPath}/res/mc.css"
Could anyone explain how is this different from a link of the form
project/WebContent/res/mc.css?

Dropwizard, serving two assets for the same URI

How may I serve two assets folder for the same URI in Dropwizard. Currently only the first one is being served, when using the same name for URI.
I'm registering AssetsBundle using (in my main application class):
public void initialize(Bootstrap<DummyFrontendConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/assets1", "/public", null, "assets1"));
bootstrap.addBundle(new AssetsBundle("/assets2", "/public", null, "assets2"));
bootstrap.addBundle(new ViewBundle());
}
Css file (main.css) in assets1:
h2{
color: red;
}
Css file (main2.css) in assets2:
h4{
color: green;
}
In html template head:
<link rel="stylesheet" type="text/css" href="public/stylesheets/main.css">
<link rel="stylesheet" type="text/css" href="public/stylesheets/main2.css">
In html template body:
<h2>This should be red</h2>
<h4>This should be green</h4>
Unfortunately the second css file (main2.css) couldn't be loaded during the html page rendering (404 - not found), any ideas?
The assets module isn't designed to function this way. Under the hood it's calling:
environment.servlets().addServlet(assetsName, createServlet()).addMapping(uriPath + '*');
Both servlets can't be mapped to the same path. You could fix this by switching one of the "public" mappings to be another path ("public2", for instance).
If you indeed need to keep your resources completely separate you may want to consider introducing another step in your build (via maven or ant) that merges the assets into a single directory structure for deployment.

Servlet in Eclipse - Where to put static content [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 9 years ago.
When writing a servlet with Eclipse, where am I to put my static content (images, CSS, etc.), so that I can make my HTML link to it (e.g. <img src="http://localhost:8080/context/image.png>). I have tried putting it into the WebContent directory, but that didn't work (or I didn't know how to link to it, I tried <img src="image.png"> and also <img src="http://localhost:8080/context/image.png">).
I attached an image of my Project Explorer, so you can maybe sort it in.
To make it easier to find, here is everything I posted in comments or elsewhere:
The project's web.xml: http://pastebin.com/sTg4ugyw
My Servlet code: http://pastebin.com/az97bZAY
One of my HTML templates: http:pastebin.com/6KALf0Bw
Create a test.html file and place it at /Blog/WebContent/test.html in your Eclipse project.
<html>
<head>
<title>Test WebContent</title>
</head>
<body>
<img src="images/test.png" />
</body>
</html>
Also place a test.png image file inside the /Blog/WebContent/images folder.
Now, point your browser to http://localhost:8080/<your-web-app-name>/test.html and check if test.png gets rendered or not. If yes, then the problem lies in the way you're writing HTML output from your servlet.
For a sample ImgServlet configured as
<servlet>
<servlet-name>ImgServlet</servlet-name>
<servlet-class>pkg.path.to.ImgServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImgServlet</servlet-name>
<url-pattern>/ImgServlet</url-pattern>
</servlet-mapping>
your doGet() method should ouput HTML as
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Test WebContent</title></head>" +
"<body><img src=\"images/test.png\" /></body></html>");
EDIT: To print all the request parameters your servlet is receiving add the following just before your handleRequest() method call (which you can comment out also for testing)
PrintWriter out = response.getWriter();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String param = (String) parameterNames.nextElement();
out.println(param + " = [" + request.getParameter(param) + "]");
}
Try
<img src="/context/image.png">
But it does depend on how you deploy your application. Anyways, files like images must be inside WebContent folder.
First of all, dont hard code your context in your link, it will make you hard to change the link later if your context path is changed. Instead, use EL to make the relative path:
<img src="${pageContext.request.contextPath}/img/abc.png" />
Secondly, I dont see any image in your WebContent, if you put the image manually into the window folder, you need to refresh eclipse project in order to let eclipse detects all the added files. Right click on your project in the Project Explorer and select Refresh

JSP not detecting the javascript file

From a servlet, I'm forwarding the request to a JSP page which renders a FusionChart.
But I've a problem in loading the chart. The JSP file is not detecting the JavaScript file. The folder structure is:
axis
|
WebContent
|
WEB-INF
|
classes
|_ com
|_FusionCharts.js
|_MyChartJsp.jsp
|_Line.swf
And the JSP code:
<html>
<head>
<script language="text/javascript" src="/WEB-INF/classes/FusionCharts.js"></script>
</head>
<body bgcolor="#ffffff">
<div id="chartdiv" align="left">The chart will appear within
this DIV. This text will be replaced by the chart.</div>
<script type="text/javascript">
var foo = //value fetched from DAO
var myChart = new FusionCharts("/WEB-INF/classes/Line.swf",
"myChartId", "1000", "500");
myChart
.setDataXML("<graph caption='aCaption' xAxisName='xAxis' yAxisName='yAxis' showNames='1' decimalPrecision='0' formatNumberScale='0'>"+foo+"</graph>");
myChart.render("chartdiv");
</script>
</body>
</html>
The Servlet code to forward the request:
final RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/classes/MyChartJsp.jsp");
requestDispatcher.forward(request, response);
The request is getting forwarded to the JSP. But the chart is not getting displayed because it is unable to figure out what FusionCharts is in the line
var myChart = new FusionCharts("/WEB-INF/classes/Line.swf",
"myChartId", "1000", "500");
I tried
src="/FusionCharts.js"
src="FusionCharts.js"
but no luck.
Has it something to do with the request being forwarded??
You cannot have .js (or .swf, .jpg, etc.) files in WEB-INF - they are not publically accessible.
Move it to /js/
There is no reason to hide static resources (like scripts and css) in WEB-INF. If you insist on that, you should make a servlet that, given the name of the js/css, would read it from its location and will serve it as a response. This is what the default servlet does when you access static resources.
The flow of the page loading is as follows: the browser sends a request to the servlet; the servlet forwards internally to the JSP, and the JSP is rendered as a response; then the browser parses the <script> tag and fires another request to the script. If the script is not accessible via URL, it's not loaded.
Then, to make the script url fixed to the servlet context root, use
src="<c:url value="/js/script.js" />"
This will work regardless of what is the current url
Not the cause of your problem, but also note that your <script> element is incorrect. It should be <script type="text/javascript"....
(I tried to post this as a comment, but for some reason it wouldn't let me.)
I was facing same issue. In my case when I calling the myFile.jsp directly its reading the myFile.js;
But when calling through login-> myFile.jsp, its not reading the myFile.js;
After analyzing the path through the Developer tools :=> console, I found that its inserting the uri, so final path was incorrect.
Final Solution:
I'd used the absolute path for all .js and .css. Now its called from everywhere.
My Project Structure is:
In my servlet-context.xml
i) <context:component-scan base-package="com.SBP.SHWeb" />
ii) <resources mapping="/resources/**" location="/resources/" />
My old path for including .js was: /resources/MyJs/myfile.js ===> Its not get called sometimes.
My Absolute path, which get called from all places is like this:
/SHweb/resources/MyJs/myfile.js ==> Its get called from everywhere.
Hope it help you.

Categories

Resources