make .html默认查看spring mvc

use*_*914 2 spring-mvc

有一个示例应用程序并创建了一个

view/HelloWorld.html
Run Code Online (Sandbox Code Playgroud)

页.从我的控制器,我返回以下内容

public String home(Locale locale, Model model) {
    return "HelloWorld";
}
Run Code Online (Sandbox Code Playgroud)

在调试模式下,我收到此警告/错误:

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/HelloWorld/WEB-INF/views/HelloWorld.html] in DispatcherServlet with name 'appServlet'
Run Code Online (Sandbox Code Playgroud)

我的src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml的内容

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".html" />
</beans:bean>
Run Code Online (Sandbox Code Playgroud)

如果我将.html重命名为.jsp并将上面的内容更改为.jsp,那么事情就可以了.

Bij*_*men 11

servlet容器为此请求所经历的流程如下:

  1. 首先,Servlet容器调用DispatcherServlet.
  2. DispatcherServlet查找映射到Controller的home方法的映射,home方法返回视图名称"HelloWorld"
  3. 现在DispatcherServlet使用View Resolver(你的InternalResourceViewResolver)来查找View以呈现模型,因为名称是"HelloWorld",它映射到/WEB-INF/view/HelloWorld.html视图.
  4. 现在基本上是打电话给 RequestDispatcher.forward("/WEB-INF/views/HelloWorld.html",....
  5. 此时的Servlet容器试图寻找它可以处理servlet的/WEB-INF/views/HellowWorld.htmlURI -如果它一直是.jsp有一个JSPServlet注册,它可以处理渲染JSP,但是,对于*.html没有注册的servlet,所以通话结束了的"default servlet",这是注册了一个servlet-mapping,/其中可能是您​​的DispatcherServlet.
  6. 现在Dispatcher servlet找不到一个控制器来处理请求/WEB-INF/views/HelloWorld.html,因此找不到你看到的消息

如果你希望这种扩展由servlet容器处理,比如tomcat,你可以注册*.html扩展以由JSPServlet处理,然后它应该干净地工作.或者返回forward:/resources/HelloWorld.html将被视为相对于您的resources文件夹的静态文件.