SpringMVC cannot load static resource jquery

When SpringMVC configures the front controller, the default operation is generally adopted, that is, / , which is used to match the virtual path of the project.
Insert picture description here
But the consequence of this is that when you want to load static resources, they will also be submitted to the SpringMVC framework for processing, causing static resources to be intercepted and unable to load. It is similar to this Insert picture description here
because the front controller regards jquery as a RequestMapping and matches it. When the match fails, jquery is not loaded.

method 1

At this time, you need to inform SpringMVC that those static resources need to be ignored.
Add the following content to the spring-mvc.xml file

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

Now to explain in detail, this line of code is to open the static resource access permissions under the destination path.
Mapping represents the mapping address, which path to access the file when the request occurs. The static resources in the directory of the
location code are open to the outside world. There must be / before and after the writing.
The example I gave is that jquery is placed in the js directory, so the mapping is /js/**, which means that all files in the js directory are allowed to be accessed. The location is /js/.
Generally speaking, mapping represents the address of the resource, and location is the directory where the resource is placed.

Method 2

If you think the mapping and location above are a bit unmatched, you can use this

<mvc:default-servlet-handler/>

This code means that when the RequestMapping mapping cannot find the target mapping address, it will be returned to the server for processing. For example, if my jquery fails to find the target in the SpringMVC controller, it will be returned to the Tomcat container to load the static resources.

When testing, restart the server and clear the cache.

I encountered a very strange phenomenon that my jquery version is jquery-3.5.1.min.js, no matter how I check the configuration, I still can’t load static resources. By searching for other great solutions, I’m using jquery -3.5.1.min.js removed min, that is, try again after jquery-3.5.1.js, it can be loaded, but I don’t believe in evil and added min back, clear the cache and try again, but it’s OK again. Indeed metaphysics. Hope that some friends who understand can learn and communicate.
Insert picture description here

Guess you like

Origin blog.csdn.net/interestANd/article/details/113127263