Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link to css file from Velocity template

I am new to servlets and Velocity templates and I am trying to link my .vm template to a .css file. The .vm file and the css file are in the ROOT directory of Tomcat. The file itself displays fine but the css does not work.

The following link does not work:

<link rel="stylesheet" type="text/css" href="style.css"/>

nor does passing the filename as an attribute:

String stylesheet = "style.css";
req.setAttribute("stylesheet", stylesheet);

and then referencing as such:

<link rel="stylesheet" type="text/css" href="$stylesheet"/>

Also, I cannot bring up the css file in the browser, even though it is definitely there.

web.xml contains the following:

<!-- register servlet -->
<servlet>
    <servlet-name>testvmservlet</servlet-name>
    <servlet-class>net.myapp.app.TestVMServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>testvmservlet</servlet-name>
    <url-pattern>/velocity.service</url-pattern>
</servlet-mapping>

<!-- mapping all .vm files to velocity servlets -->
<servlet>
    <servlet-name>velocity</servlet-name>
    <servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class>

</servlet>
<servlet-mapping>
    <servlet-name>velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
</servlet-mapping>

Do I need to reference the css file relative to the app or relative to Velocity?

I have since adjusted one of my servlet mappings from:

<servlet-mapping>
    <servlet-name>startupservlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

to:

<servlet-mapping>
    <servlet-name>startupservlet</servlet-name>
    <url-pattern>/foo</url-pattern>
</servlet-mapping>

and now the css works fine. But I am unsure as to why this mapping was having an effect at all.

As I understand it <url-pattern>/</url-pattern> only applies where no path has been specified, however, a request for style.css should constitute a path?

like image 545
burntsugar Avatar asked Jul 05 '13 00:07

burntsugar


1 Answers

I believe your problem is the servlet mapping to /

By default, Tomcat maps / to it's DefaultServlet which serves static content. When you map / to your servlet, it seems to override the entire DefaultServlet behaviour. It acts as a /* mapping though it looks like it should only handle /

I'm not sure if this is a bug or a feature. :)

A solution may be to change your / servlet mapping to /home and then use a welcome-file mapping to reference that.

like image 157
slipperyseal Avatar answered Nov 07 '22 04:11

slipperyseal