<mvc:default-servlet-handler/> causes the controller to fail and reports a 404 error

When I was working on a small project integrating the ssm framework recently, there was always a 404 error in the page jump, and there was no error message. Then I searched step by step, and finally found the reason for <mvc:default-servlet-handler/>.

As shown in the figure above, if the springmvc configuration file is written like this, an error will be reported.

<mvc:default-servlet-handler/> This line of code means to use the default Servlet to respond to static files, because DispatcherServlet is used in web.xml to intercept all requested urls, including the introduction of js, css, etc. from jsp pages . Since these static files cannot be found, a 404 error will be reported. And when the configuration file adds this default servlet, the servlet will look for static content when it can't find it.

However, after this line of code is introduced, the Controller will fail. To be precise, the method under RequestMapping will fail, so the interface cannot be jumped. After reading some reasons on the Internet, the summary is:

<mvc:default-servlet-handler/> will define a DefaultServletHttpRequestHandler in the SpringMVC context. The function of this Handler is to go to the servlet container to find the default servlet to respond to static files, which will lead to the processing mapper and processing of the configuration file above. The adapter fails, and thus the Controller fails.


 

The solution is as follows

The function of this line of code <mvc:annotation-driven/> is to automatically register the two beans, RequestMappingHandlerMapping and RequestMappingHandlerAdapter, so I annotated them.

That is to say, the order of these two beans must be in front of <mvc:default-servlet-handler/>. The DefaultServletHttpRequestHandler defined by <mvc:default-servlet-handler/> executes the mapping matched by the handler when no other mapping can process the request, so as to find static content.

In the same way, you can also put the line of code <mvc:default-servlet-handler/> in my first picture behind the two beans to solve the problem.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325231537&siteId=291194637