The JSP page is unable to locate or access relative resources such as CSS stylesheets and images

I'm struggling to create a basic web page using JSP. The issue I'm facing is that no resources, such as images or CSS, are being found regardless of the URL I use.

Here is my simple JSP code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="SHORTCUT ICON" href="img/logo.ico" />
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>

        <div id="banner">
            <div id="banner-wrapper">
                <div id="appname">
                    <a href="" >
                    <img alt="logo-cloudapi" height="50px" src="/logo.png">
                    </a>
                    ABC
                </div>
                <div id="a">
                    <img alt="logo2" height="50px" src="/logo2.jpg">
                </div>
            </div>
        </div>
</body>

I've tried different URLs:

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

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

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

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">

None of them seem to work.

This is the structure of my src folder:

I am not using web.xml but rather Java config files.

Configuration:

package com.websystique.springmvc.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.websystique.springmvc")
public class HelloWorldConfiguration {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/views/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }

}

Initializer

package com.orange.paddock.gofr.provider.ihm.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { HelloWorldConfiguration.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

I have come across several threads discussing similar issues, but none of the solutions provided have worked for me.

Any ideas on what could be the solution?

Answer №1

Utilize MVC static resources to map your static resources to a URL.

<mvc:resources mapping="/resources/**" location="/resources/, /WEB-INF/static/" />

For instance:

(XML configuration)

<mvc:resources mapping="/css/**" location="/css/" />

(Java-based configuration)

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/resources/**")
          .addResourceLocations("(/resources/");    
    }
}

Placing them within the webapp directory should suffice.

Answer №2

Can you describe how your project is structured?

Our project has a structure where all static files such as HTML, CSS, and JavaScript are located directly under the web application root directory. To enhance security, we ensure that these files are placed within the WEB-INF directory.

JSP files in our project can either be situated directly in the root directory or organized into subfolders within the WEB-INF folder. Placing them inside WEB-INF or its subfolders helps maintain a clean structure for easy navigation.

Answer №3

In my opinion, the directory containing the web application resources such as .html and .jsp files, as well as the CSS and JavaScript files, may be incorrectly referenced. Double-check your folder paths to ensure proper linking. For example:

<link href="path to your css folder/styles.css">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adaptive Container with Images that are not stretched to full width

Is there a way to achieve the same effect as seen in images 2 and 3 here: Although these images already have their own "padding," I'm curious if it can be replicated using just jQuery and CSS? I would appreciate any help or insights on this. Thank y ...

Meteor chat platform now offers the option to create multiple chat rooms

I've been working on an application that features multiple chat rooms. Currently, one of the rooms is functional in terms of sending and receiving messages. However, when I navigate to a different room and try to send a message, the message doesn&apos ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...

What are the recommended margins for various alphabets?

When displaying text, some alphabets take up more space than others. So how can I adjust the white space between elements '#re1' and '#re2' automatically in the scenario described below? In this code snippet, what is the best way to ad ...

How do I go about extracting and presenting the JSON data from the ESPN API?

In my current project, I am trying to utilize the jQuery library to work with API JSON data. Even though I am experienced in parsing JSON in PHP, I want to explore doing it with jQuery this time around. The goal is to extract information about each of the ...

Issue with CSS3 gradient display in Firefox and IE, functioning correctly only in Chrome

I recently developed a text gradient class that looks great in Google Chrome but unfortunately doesn't display correctly in Firefox and Internet Explorer. In these browsers, there is a visible background gradient behind the text which is not the desir ...

Center the logo between the menus in the foundation framework

Struggling to center the logo between menus using Foundation Zurb. I'm envisioning a layout similar to [menu1] [menu2] --[logo]-- [menu3] [menu4]. I believe utilizing the grid system may help achieve this: <div class="panel hide-for-small-down"&g ...

Solving the issue of .css being blocked due to MIME type while building tailwind is a common problem faced by

https://i.stack.imgur.com/nrDgJ.png While working on my tailwind CSS project, I ran npm run build. However, upon opening the built index.html file, I noticed that the CSS file was not loading properly. How can I resolve this issue? I am unsure of what st ...

I am seeking to enable a specific div when the crawler condition is met

This specific div houses the character and becomes active when the character is clicked. Upon clicking, a jQuery function is triggered to display other countries. //this particular div should remain active when the crawler condition is met. It displays th ...

Resources for Vue.js stylesheets

Vue.js is my latest discovery and I have been experimenting with the single file component architecture. A small issue I encountered was that all of my components' styles were being loaded on the page, even if they weren't currently active. Is t ...

Included adaptable background-images in the upload

Recently, I developed a RoR based app/website that allows clients to upload their own background image to the cover page. Although the current setup works well with a single image, I am aiming to enhance the site's responsiveness by enabling clients t ...

Order Android images by their timestamp

I created a wallpaper application with an image saving function, and I want to display the saved images in my collection menu with the newest ones first. Is there a way to order the images like that? Below is the code snippet I am using to retrieve images ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

I am experiencing some difficulty with the GetServerDate using the JSON protocol in JQuery; it's

I am facing an issue while trying to execute a basic ajax call to fetch data from a file on a server. Even though I can access the file via the web browser and have diligently followed tutorials related to this topic, I have hit a dead end. Here is the sn ...

Challenges arising from utilizing distinct list style types for both parent and child elements with the assistance of CSS List

I am experimenting with the CSS counter reset feature to create a numbering system on my website. The main list should be in regular decimal format (e.g. 1, 2, 3, 4) while the sub-list should be in upper Roman numerals (e.g. I, II, III, IV, etc). Below is ...

When floated to the right, the element is being pushed onto the next line in Firefox

Within a div, there are four elements. I specifically want the last element to be positioned on the far right, so I applied float: right to it. However, in Firefox, the last element gets pushed to the end of the next line instead. This issue does not occ ...

How can I send the input from a textbox to an email?

I'm looking to create a basic sign-up form where individuals can enter their email and submit it. The goal is to have this information sent via email to the site owner. I initially thought the code below would do the trick, but it doesn't seem t ...

Vue.js component unable to validate HTML input patterns

Attempting to create HTML forms with the 'pattern' input attribute has been an interesting challenge for me. When implementing this through Vue.js components, I encountered some strange behavior. Check out this fiddle to see it in action. Vue.co ...

Why does Material-UI TableCell-root include a padding-right of 40px?

I'm intrigued by the reasoning behind this. I'm considering overriding it, but I want to ensure that I'm not undoing someone's hard work. .MuiTableCell-root { display: table-cell; padding: 14px 40px 14px 16px; font-size: 0. ...