本人小白一个,不能保证博客中内容都准确,如果博客中有错误的地方,望各位多多指教,请指正。

上面的内容仅仅能解决本人遇到的错误,不一定适用于所有人,如有不适用,请多多包涵。

 

问题描述:

               使用default-servlet-handler,能通过url 直接访问静态资源,而controller层根只能访问静态资源,无法访问动态资源。

                          Controller层代码 ,以及静态资源html目录结构, 如下图:

                                               使用default-servlet-handler出现的问题/bug

                                通过 Controller层访问动态资源,报404,如下图

                                            使用default-servlet-handler出现的问题/bug

                                通过 Controller层访问静态资源,正常访问,如下图

                                              使用default-servlet-handler出现的问题/bug

                                通过 url 直接访问静态资源,正常访问,如下图

                                             使用default-servlet-handler出现的问题/bug

 

原因以及解决办法:

                       底层源码给出的原因以及解决办法是 :  别问,问就是不知道,自己去翻译

 

Configures a handler for serving static resources by forwarding to the Servlet container's default Servlet.
Use of this handler allows using a "/" mapping with the DispatcherServlet while still utilizing the Servlet
container to serve static resources.
This handler will forward all requests to the default Servlet. Therefore it is important that it remains last
in the order of all other URL HandlerMappings. That will be the case if you use the "annotation-driven" element
or alternatively if you are setting up your customized HandlerMapping instance be sure to set its "order"
property to a value lower than that of the DefaultServletHttpRequestHandler, which is Integer.MAX_VALUE.

通过转发到Servlet容器的默认Servlet,配置用于处理静态资源的处理程序。
使用此处理程序允许在DispatcherServlet中使用“ /”映射,同时仍然利用Servlet容器来提供静态资源。
该处理程序会将所有请求转发到默认Servlet。 因此,保持所有其他URL HandlerMappings的顺序最后是很重要的。 如果您使用“注释驱动”元素,或者您要设置自定义的HandlerMapping实例,请确保将其“ order”属性的值设置为小于DefaultServletHttpRequestHandler的Integer.MAX_VALUE的值。

           具体的原因,官方已经给出。

                反正我的理解就是加入default-servlet-handler这个标签后,框架就会创建控制器对象DefaultServletHttpRequestHandler(类似我们自定义的MyController),DefaultServletHttpRequestHandler这个对象把所有的接收到的请求都转发给Tomcat默认的servlet来处理。也就是说,如果controller层的@RequestMapping注解配置了一个映射路径,如果请求访问的路径是@RequestMapping注解配置映射路径,也就是想访问@RequestMapping注解下面的方法,但是, 此时由于加了default-servlet-handler这个标签,DefaultServletHttpRequestHandler这个对象把所有的接收到的请求都转发给Tomcat默认的servlet来处理,那么就不会走@RequestMapping注解下面的方法。

           具体的解决办法,官方也已经给出。那就是加 annotation-driven 标签 ,或者提高你controller的优先级。

                   使用default-servlet-handler出现的问题/bug

 

总结:

      如果以后要加载动态资源又要加载静态资源,那么就两个标签一起使用,别瞎搞。

 

 

 

相关文章:

  • 2021-09-20
  • 2022-12-23
  • 2021-04-06
  • 2021-10-06
  • 2021-08-28
猜你喜欢
  • 2021-08-01
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2021-10-25
  • 2022-12-23
相关资源
相似解决方案