'Not able to load static images in jsp because of "/" servlet mapping [duplicate]

I am working with jsp servlet architecture with maven and I noticed I am not able to load any local images using src attribute.

<img src="img/placeholder.png" class="rounded-circle" alt="..." style="width: 18rem;">

If remote URL is mention then it works fine however I am facing this issue for local images only. As per my observation, main culprit is default PageController I have created using Servlet to deal with navigation requests. The servlet has @WebServlet("/") annotation. Because of this all my src attributes are being pass to this controller as request

http://localhost:8080/SM6MJ/img/placeholder.png

If I change @WebServlet("/") annotation to @WebServlet("/foo") then I am able to load images but then not able to do screen navigation.

Below is my PageController code

@WebServlet(
  name = "PageController",
  description = "Example Servlet Using Annotations",
  urlPatterns = {"/"}
)
public class PageController extends HttpServlet{

    private static final long serialVersionUID = 1L;
    private SongsDAOImpl songDao = SongsDAOImpl.getInstance();
    private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(PageController.class.getName());
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getServletPath();
        try {
            switch (action) {
            case "/dashboard":
                this.navigateToHomeScreen(req, resp);
                break;
            default:
                this.navigateToHomeScreen(req, resp);
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "SQL Error", e);
        }
         
    }

    private void navigateToHomeScreen(HttpServletRequest req, HttpServletResponse resp) throws SQLException,IOException, ServletException {
        req.setAttribute("screen", "dashboard");
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

and then in index.jsp I have implemented single page application by including relevant jsps based on setAttribute field called "screen"



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source