Search code examples
servletsjakarta-eeresourcesurl-patterneclipse-jee

Resources won't load with the second url pattern in J2EE


I'm having a strange problem, i have a servlet that is mapped to /home and /home/next with the web annotation as follows:

@WebServlet(urlPatterns= {"/home", "/home/next"})
public class IndexServlet extends HttpServlet {

and it's doGet method send an index.jsp that has the following:

<body>
    <p>Hello world!</p>
    <img src="resources/logo.png" alt="logo">
</body>

and the files hierarchy is as follows:

  • src/main/
    • java/
      • IndexServlet.java
    • webapp/
      • WEB-INF/
        • index.jsp
      • resources/
        • logo.png

And here is the problem, when i access

localhost:8080/_08/home (_08 is the projects name)

Everything is as to be expected, it works fine. However, if i were to access

localhost:8080/_08/home/next

I get the expected jsp but the image won't load, i get the broken image icon.

I dont understand why it happens, i tried adding a url pattern like this:

@WebServlet(urlPatterns= {"/home", "/home/next", "/foo", "/foo/bar"})
public class IndexServlet extends HttpServlet {

and i get the same result, the /foo work, but /foo/bar doesn't, it also won't load the image. I'm using Tomcat v10.0 and Eclipse JEE IDE.

Thank you guys in advance.


Solution

  • A colleague gave me the answer, it turns out i already stumbled upon it but not in this context. Not adding a '/' at the beginning of your href will look for the path relative to where it is. For example in the localhost:8080/_08/home it looked for the image in localhost:8080/_08/ which explains why it worked, because that's where the image is, it's in /_08/resources/logo.png (the WebApp is _08), but when i go to localhost:8080/_08/home/next it look for it in localhost:8080/_08/home/. Adding a '/' at the beginning specifies that the path is from the root of the WebApp, so making editing the jsp to this solves the problem:

    <img src="/_08/resources/logo.png" alt="logo">
    

    However that is an app based solution, and what should be used is:

    <img src="${pageContext.request.contextPath}/resources/logo.png" alt="logo">
    

    Which returns the root dir for your WebApp. Same problem will occur with anchor links, same solution tho.