无法映射静态资源,即在Spring MVC中的JS、CSS和图像。

huangapple go评论76阅读模式
英文:

Not able to map static resources i.e. JS, CSS, images in spring MVC

问题

以下是您要翻译的内容:

I'm not sure how these static resources were loading earlier but after I added one new controller mapping I see no mapping found for static resources warning message in logs.

No mapping for GET /testproject/org/css/style.css

Let me explain my project configuration first so that it will be easy to understand the problem.

All JSP location (view have different folders to separate JSP for different modules)

src/main/java/webapp/views/org/.jsp
src/main/java/webapp/views/
.jsp

Static resource location

src/main/java/resources/static/css/.css
src/main/java/resources/static/js/
.js
src/main/java/resources/static/images/.jpg
src/main/java/resources/static/fonts/
.ttf

Application.properties

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
server.servlet.contextPath=/testproject

After adding last config in application.properties now my application URL for any view page will be like

http://localhost:8080/testproject/dashboard

Controller mapping for the above URL is:

@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public String dashboard(ModelMap map) {return "org/dashboard";}

With the above configuration, the static resource path is getting formed as below

http://localhost:8080/testproject/css/style.css

With the above config, I was able to load CSS files using the below code

<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<link href="<core:url value="css/style.css"/>" rel="stylesheet" type="text/css" media="all">

Now as I have dashboard page defined under separate folder org so I thought to change my controller mapping to match exactly as folder structure & also it will help me to assign different roles/Access_ROLE for diff modules in spring security.

Spring security config for defining USER_ROLE who can access org module pages

.antMatchers("/org/**").access("hasRole('ROLE_ORG')").anyRequest()

After changing my controller mapping (from /dashboard to /org/dashboard)

@RequestMapping(value = "/org/dashboard", method = RequestMethod.GET)
public String dashboard(ModelMap map) {return "org/dashboard";}

Now spring security works fine. It is not allowing direct access of dashboard without login or if logged-in user is having different ROLE.

But now my static resource URL is changes now

http://localhost:8080/testproject/org/css/style.css

Earlier this URL was

http://localhost:8080/testproject/css/style.css (working)

Things I tried to fix this

WebMvcConfig.java

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // TODO Auto-generated method stub
        registry.addResourceHandler("/res/**").addResourceLocations("/resources/static/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}

Added this property in application.properties

spring.mvc.static-path-pattern=/resources/**

Now in JSP, I'm trying to access CSS with below code, none of them worked

<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<link href="<core:url value="css/style.css"/>" rel="stylesheet" type="text/css" media="all">
<link href="<core:url value="resources/css/style.css"/>" rel="stylesheet" type="text/css" media="all">
<link href="<core:url value="res/css/style.css"/>" rel="stylesheet" type="text/css" media="all">

So I checked in developer tool to see the path created for all above code PFB

<link href="<core:url value="css/style.css"/>" rel="stylesheet" type="text/css" media="all">
http://localhost:8080/testproject/org/css/style.css

<link href="<core:url value="resources/css/style.css"/>" rel="stylesheet" type="text/css" media="all">
http://localhost:8080/testproject/org/resources/css/style.css

<link href="<core:url value="res/css/style.css"/>" rel="stylesheet" type="text/css" media="all">
http://localhost:8080/testproject/org/res/css/style.css

Let me know what exactly I'm doing wrong here. I know above code will work but some configuration I'm missing or configured wrong.

I've tried to capture all possible details which may cause this issue. Let me know if need more details.

# **Update 2**

I created simple spring MVC project which can be downloaded form below link

https://drive.google.com/file/d/1-WqLnuEH2BffvcwBil7QcKcxqPay214Y/view?usp=sharing

few doubts

static resource loads normally with below code, with or without resource handler mapping in MvcWebConfig.java just uncomment line 4 & comment line 5 in welcome.jsp css will load.

the only change i made is "/" in value parm before **css/test.css**.

```html
<link href="<core:url value="/css/test.css"/>" rel="stylesheet" type="text/css" media="all">

but after adding resource handler , i see 404 error, help me to resolve this issue

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    // TODO Auto-generated method stub
    WebMvcConfigurer.super.addResourceHandlers(registry);
    
    registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/css");
}

JSP CHANGES

<link href="<core:url value="/resources/test.css"/>" rel="stylesheet" type="text/css" media="all">

can any one please explain what is the difference between all these mapping or let me know if any of them are wrong.

assuming src/main/java/resources/static/css/*.css is static folder structure.

registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/css");

registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");

registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");

below will work as i've changed handler mapping (**myresources**) other than folder structure

```java
registry.addResourceHandler("/myresources/**").addResourceLocations("classpath:/resources/static/css");

when i should use classpath in locations ?

registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/css");
英文:

I'm not sure how these static resources were loading earlier but after I added one new controller mapping I see no mapping found for static resources warning message in logs.

No mapping for GET /testproject/org/css/style.css

Let me explain my project configuration first so that it will be easy to understand the problem.

All JSP location (view have different folders to separate JSP for different modules)

src/main/java/webapp/views/org/*.jsp  
src/main/java/webapp/views/*.jsp

Static resource location

src/main/java/resources/static/css/*.css  
src/main/java/resources/static/js/*.js  
src/main/java/resources/static/images/*.jpg  
src/main/java/resources/static/fonts/*.ttf

Application.properties

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
server.servlet.contextPath=/testproject

After adding last config in application.properties now my application URL for any view page will be like

http://localhost:8080/testproject/dashboard

Controller mapping for the above URL is:

@RequestMapping(value = &quot;/dashboard&quot;, method = RequestMethod.GET)
	public String dashboard(ModelMap map) {return &quot;org/dashboard&quot;;}

With the above configuration, the static resource path is getting formed as below

http://localhost:8080/testproject/css/style.css

With the above config, I was able to load CSS files using the below code

&lt;%@ taglib prefix=&quot;core&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot;%&gt;
&lt;link href=&quot;&lt;core:url value=&quot;css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

Now as I have dashboard page defined under separate folder org so I thought to change my controller mapping to match exactly as folder structure & also it will help me to assign different roles/Access_ROLE for diff modules in spring security.

Spring security config for defining USER_ROLE who can access org module pages

.antMatchers("/org/**").access("hasRole('ROLE_ORG')").anyRequest()

After changing my controller mapping (from /dashboard to /org/dashboard)

@RequestMapping(value = &quot;/org/dashboard&quot;, method = RequestMethod.GET)
	public String dashboard(ModelMap map) {return &quot;org/dashboard&quot;;}

Now spring security works fine. It is not allowing direct access of dashboard without login or if logged-in user is having different ROLE.

But now my static resource URL is changes now

http://localhost:8080/testproject/org/css/style.css

Earlier this URL was

http://localhost:8080/testproject/css/style.css (working)

Things I tried to fix this

WebMvcConfig.java

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// TODO Auto-generated method stub
		registry.addResourceHandler(&quot;/res/**&quot;).addResourceLocations(&quot;/resources/static/&quot;);
		WebMvcConfigurer.super.addResourceHandlers(registry);
	}
}

Added this property in application.properties

spring.mvc.static-path-pattern=/resources/**

Now in JSP, I'm trying to access CSS with below code, none of them worked

&lt;%@ taglib prefix=&quot;core&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot;%&gt;
&lt;link href=&quot;&lt;core:url value=&quot;css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;
&lt;link href=&quot;&lt;core:url value=&quot;resources/css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;
&lt;link href=&quot;&lt;core:url value=&quot;res/css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

So I checked in developer tool to see the path created for all above code PFB

&lt;link href=&quot;&lt;core:url value=&quot;css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

http://localhost:8080/testproject/org/css/style.css

&lt;link href=&quot;&lt;core:url value=&quot;resources/css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

http://localhost:8080/testproject/org/resources/css/style.css

&lt;link href=&quot;&lt;core:url value=&quot;res/css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

http://localhost:8080/testproject/org/res/css/style.css

Let me know what exactly I'm doing wrong here. I know above code will work but some configuration I'm missing or configured wrong.

I've tried to capture all possible details which may cause this issue. Let me know if need more details.

Update 2

I created simple spring MVC project which can be downloaded form below link

https://drive.google.com/file/d/1-WqLnuEH2BffvcwBil7QcKcxqPay214Y/view?usp=sharing

few doubts

static resource loads normally with below code, with or without resource handler mapping in MvcWebConfig.java just uncomment line 4 & comment line 5 in welcome.jsp css will load.

the only change i made is "/" in value parm before css/test.css.

&lt;link href=&quot;&lt;core:url value=&quot;/css/test.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

but after adding resource handler , i see 404 error, help me to resolve this issue

@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// TODO Auto-generated method stub
		WebMvcConfigurer.super.addResourceHandlers(registry);
		
		registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;classpath:/resources/static/css&quot;);
	}

JSP CHANGES

&lt;link href=&quot;&lt;core:url value=&quot;/resources/test.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

can any one please explain what is the difference between all these mapping or let me know if any of them are wrong.

assuming src/main/java/resources/static/css/*.css is static folder structure.

registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;classpath:/resources/static/css&quot;);

registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;classpath:/resources/&quot;);

registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;/resources/&quot;);

below will work as i've changed handler mapping (myresources) other than folder structure

registry.addResourceHandler(&quot;/myresources/**&quot;).addResourceLocations(&quot;classpath:/resources/static/css&quot;);

when i should use classpath in locations ?

registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;classpath:/resources/static/css&quot;);

答案1

得分: 1

以下是已经翻译好的内容:

[![文件夹结构][1]][1]

  [1]: https://i.stack.imgur.com/ALM1s.png

下面的代码对我有效:

    registry.addResourceHandler("/res/**").addResourceLocations("classpath:/static/");

    <link href="<core:url value="/res/css/test.css" />" rel="stylesheet" type="text/css">

或者

    registry.addResourceHandler("/resource/**").addResourceLocations("classpath:/static/");

    <link href="<core:url value="/resource/css/test.css" />" rel="stylesheet" type="text/css">

以下任何一种都没有生效:

    registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/css/");
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    registry.addResourceHandler("/res/**").addResourceLocations("/static/");
    registry.addResourceHandler("/res/**").addResourceLocations("/resources/");
英文:

无法映射静态资源,即在Spring MVC中的JS、CSS和图像。

below code worked for me

registry.addResourceHandler(&quot;/res/**&quot;).addResourceLocations(&quot;classpath:/static/&quot;);

&lt;link href=&quot;&lt;core:url value=&quot;/res/css/test.css&quot; /&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;

or

registry.addResourceHandler(&quot;/resource/**&quot;).addResourceLocations(&quot;classpath:/static/&quot;);

&lt;link href=&quot;&lt;core:url value=&quot;/resource/css/test.css&quot; /&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;

none of them worked given below

registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;classpath:/resources/static/css&quot;);
registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;/resources/&quot;);
registry.addResourceHandler(&quot;/res/**&quot;).addResourceLocations(&quot;/static/&quot;);
registry.addResourceHandler(&quot;/res/**&quot;).addResourceLocations(&quot;/resources/&quot;);

答案2

得分: 0

你必须定义一个全局静态资源处理程序。查看你的 web.xml,添加一个与你的安全配置链接的过滤器(或不链接,根据你的需求)。或者在你的 WebMvcConfig.class 文件中。

编辑:从 https://www.baeldung.com/spring-mvc-static-resources 添加示例

方法1) 在你的 web.xml 或 app.xml 配置中:

&lt;mvc:resources mapping=&quot;/assets/**&quot; location=&quot;/assets/&quot; /&gt;

在你的 views.jsp 中:

&lt;c:url value=&quot;/assets/myCss.css&quot; /&gt;

方法2)

spring.mvc.static-path-pattern=/assets/**

然后在之前加上 "/",解析器将处理这个任务。

&lt;%@ taglib prefix=&quot;core&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot;%&gt;
&lt;link href=&quot;&lt;core:url value=&quot;/assets/css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

方法3) 更改默认静态资源位置

spring.resources.static-locations=classpath:/assets/,classpath:/static-files

方法4) WebMvcConfigurer

    @Configuration
	@EnableWebMvc
	public class MvcConfig implements WebMvcConfigurer {
	    @Override
	    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	        registry
	          .addResourceHandler(&quot;/assets/**&quot;)
	          .addResourceLocations(&quot;/assets/&quot;);	
	    }
	}

重要:使用Spring Security(以及其他安全库)时,必须为你的静态资源提供一个安全的访问路径:

&lt;intercept-url pattern=&quot;/assets/**&quot; access=&quot;permitAll&quot; /&gt;

以前的回答:
也许你的路径必须是绝对路径,以解析你的静态资源。否则,你的处理程序配置将无法解析它们:

&lt;%@ taglib prefix=&quot;core&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot;%&gt;
&lt;link href=&quot;&lt;core:url value=&quot;/res/css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;
英文:

You must define a global static resources handler. Look at your web.xml adding a filter chained with your security config (or not, as you need to). Or inside your WebMvcConfig.class file.

Edit: Added Examples from https://www.baeldung.com/spring-mvc-static-resources

Method 1) In your web.xml or app.xml config :

&lt;mvc:resources mapping=&quot;/assets/**&quot; location=&quot;/assets/&quot; /&gt;

In your views.jsp :

&lt;c:url value=&quot;/assets/myCss.css&quot; /&gt;

Method 2)

spring.mvc.static-path-pattern=/assets/**

then you just put "/" before and the resolver will handle the job.
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<link href="<core:url value="/assets/css/style.css"/>" rel="stylesheet" type="text/css" media="all">

Method 3) Change default static resources locations

spring.resources.static-locations=classpath:/assets/,classpath:/static-files

Method 4) WebMvcConfigurer

    @Configuration
	@EnableWebMvc
	public class MvcConfig implements WebMvcConfigurer {
	    @Override
	    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	        registry
	          .addResourceHandler(&quot;/assets/**&quot;)
	          .addResourceLocations(&quot;/assets/&quot;);	
	    }
	}

IMPORTANT : With Spring Security (and with other security libs too) you must provide a safe pass-away to your static resources :

&lt;intercept-url pattern=&quot;/assets/**&quot; access=&quot;permitAll&quot; /&gt;

Previous answer :
Maybe your path must be absolute to resolve your static resources. Otherwise your handler config will not resolve them :

&lt;%@ taglib prefix=&quot;core&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot;%&gt;
&lt;link href=&quot;&lt;core:url value=&quot;/res/css/style.css&quot;/&gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot;&gt;

huangapple
  • 本文由 发表于 2020年8月9日 23:21:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63328056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定