Attaching a CSS file to a Java Servlet in Tomcat

20,048

Solution 1

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.

Solution 2

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>")
Share:
20,048
KyleCrowley
Author by

KyleCrowley

Updated on January 30, 2020

Comments

  • KyleCrowley
    KyleCrowley over 4 years

    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.