Default-servlet-handler does not take effect, comparison of springmvc static resource interception schemes

Why does springmvc intercept static resources?


      To put it simply, in order to request the URL without similar *.action, *.do, such as http://localhost:8080/system/index.action, the spring team has a unified style, and in the web.xml of the web project configuration, all All requests must go through the DispatcherServlet, which of course includes static resources, such as http://localhost:8080/html/index.html. In order to solve this problem, spring gives two solutions. Let's discuss the next two solutions together. The use and difference of, give novice students a very confessional and clear understanding!

 

Solution


     Before talking about the solution, let’s talk about the structure of the web project. As shown in the figure below, you can see that there is a WEB-INF folder under the default webapp. This folder is to improve the file security level. If you don’t set it, yes Unable to access, so the resource files (jsp, css, jss) that you generally see are all under the WEB-INF folder.

image.png

Solution 1:

<mvc:default-servlet-handler />

     If the project is configured in this way, you cannot access the files under WEB-INF/css/, because the springmvc context defines a DefaultServletHttpRequestHandler for processing static files. What he does is forward to the Spring default processor DispatcherServlet. DispatcherServlet can Dealing with unauthorised directory files under webapp, it cannot deal with WEB-INF folders, which means that you have configured <mvc:default-servlet-handler />, you can access files under html, but you cannot access WEB-INF/ For files under css/, this may be the reason for folder permissions. According to the official documentation, this configuration can coexist with solution 2. Let's take a look at Method 2.

Solution 2:

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

       location: corresponds to the root path

       mapping: mapping is the access path

      You can access the blocked resources through http://localhost:8080/css/index.css. This method can solve the limitation of Method 1.

 

to sum up


     To summarize, I recommend this way 2 to solve the problem of blocking access to static resources. I think that method 1 can be omitted, and the configuration according to method 2 is enough. Method 2 may have more configurations, but it looks clearer and easier to understand. Thank you for watching, if you like or have doubts, please like and leave a message! I'm called practicing, while calling and practicing.

 

Guess you like

Origin blog.csdn.net/duyabc/article/details/110842889