Spring MVC ViewResolver 未映射到 HTML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24980839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:51:14  来源:igfitidea点击:

Spring MVC ViewResolver not mapping to HTML files

springspring-mvc

提问by Mac

I cannot get spring mvc to resolve .html view files.

我无法让 spring mvc 解析 .html 视图文件。

I have the following view folder structure:

我有以下视图文件夹结构:

WEB-INF
      `-views
            |- home.jsp
            `- home.html

I have a simple hello world controller method that just prints a message and returns the view name "home". I have a home.jsp file, but would like to use the home.html instead.

我有一个简单的 hello world 控制器方法,它只打印一条消息并返回视图名称“home”。我有一个 home.jsp 文件,但想改用 home.html。

<!-- Working servlet mapping --> 
<servlet-mapping>
    <servlet-name>spaceShips</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- working servlet context -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <beans:property name="prefix" value="WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" /> 
</beans:bean>

When I hit spaceships/home the controller prints the hello world message and I see the home.jsp view without a problem.

当我点击 spaceships/home 时,控制器会打印 hello world 消息,我可以毫无问题地看到 home.jsp 视图。

The problem is when I change the suffix to .html.

问题是当我将后缀更改为 .html 时。

After changing the suffix and navigating to /home, the controller prints the message however I see a 404 error in the browser and the following in the console: WARNING: No mapping found for HTTP request with URI [/spaceships/WEB-INF/views/home.html]

更改后缀并导航到 /home 后,控制器会打印消息,但是我在浏览器中看到 404 错误,在控制台中看到以下内容:警告:未找到带有 URI [/spaceships/WEB-INF/views 的 HTTP 请求的映射/home.html]

To clarify:

澄清:

<!-- not working with .html -->
<servlet-mapping>
    <servlet-name>spaceShips</servlet-name>
    <!-- I have tried /* here as well without success -->
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- not working with .html-->
<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>

I have checked in the exploded war folder and can confirm that both home files are present.

我已经检查了爆炸的War文件夹,可以确认两个主文件都存在。

Has anyone encountered something like this before?

有没有人遇到过这样的事情?

Last chunk of console message:

最后一块控制台消息:

INFO: Server startup in 5256 ms
Hello, World!
Jul 27, 2014 12:52:01 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spaceships/WEB-INF/views/home.html] in DispatcherServlet with name 'spaceShips'

Thanks for reading.

谢谢阅读。

=========== SOLUTION ============

============ 解决方案 ============

The following (ugly) configuration solved the issue. There are probably ways to clean this up, but if you are experiencing the same problem you may be able to piece together a solution from this.

以下(丑陋的)配置解决了这个问题。可能有一些方法可以解决这个问题,但是如果您遇到同样的问题,您可以从中拼凑出一个解决方案。

Folder structure:

文件夹结构:

 WEB-INF
       `-static
              |-html
                    `-home.html
              |-css
              `-img

Controller method:

控制器方法:

 @RequestMapping(value = "/home")
 public String goHome() { 
      System.out.println("lolololololol");
      return "static/html/home";
 }

Spring config:

弹簧配置:

 <resources mapping="/static/**" location="/WEB-INF/static/" />

 <beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <beans:property name="prefix" value="" />
      <beans:property name="suffix" value=".html" />
 </beans:bean>

采纳答案by Kuntal-G

Check this out for mapping html files in Spring mvc (Details step is given in Answer):

检查这个以在 Spring mvc 中映射 html 文件(详细步骤在答案中给出):

Which spring view resolver plays nice with angularjs?

哪个 spring 视图解析器与 angularjs 配合得很好?

In simple:

简单来说:

In order to use static resource(html,css,img,js) in spring, use a directory structure that looks like the following:

为了在 spring 中使用静态资源(html,css,img,js),使用如下所示的目录结构:

src/
   package/
   LayoutController.java
WebContent/
   WEB-INF/
    static/
      html/
       layout.html
      images/
       image.jpg
      css/
       test.css
      js/
       main.js
     web.xml
    springmvc-servlet.xml


@Controller 
public class LayoutController {

 @RequestMapping("/staticPage") 
public String getIndexPage() { 
return "layout.htm"; 

} }




<!-- in spring config file -->
 <mvc:resources mapping="/static/**" location="/WEB-INF/static/" />

layout.html

布局.html

<h1>Page with image</h1>
<img src="/static/img/image.jpg"/>

回答by Biju Kunjummen

This is because normally *.jspstyle uri patterns are handled by the servlet container and in this specific instance *.htmlis not being handled by the container and instead the path is being delegated to Spring MVC which does not know how to render these extensions.

这是因为通常*.jsp样式 uri 模式由 servlet 容器处理,并且在此特定实例*.html中,容器不处理,而是将路径委托给不知道如何呈现这些扩展的 Spring MVC。

As an example, if you are using tomcat, you would see these entries under conf/web.xmlfile:

例如,如果您使用的是 tomcat,您会在conf/web.xml文件下看到这些条目:

<servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.jsp</url-pattern>
    <url-pattern>*.jspx</url-pattern>
</servlet-mapping>

i.e jsp servlet handles *.jsp, *.jspx extension.

即jsp servlet 处理*.jsp、*.jspx 扩展名。

So given this, a potential fix will be to add .html to be added to be handled by jsp servlet, as in this link:

因此,考虑到这一点,一个潜在的解决方法是添加 .html 以供 jsp servlet 处理,如下链接所示:

Using .html files as JSPs

使用 .html 文件作为 JSP

or even better ,leave the extension as .jsp and use .html as a controller pattern instead?

或者更好的是,将扩展名保留为 .jsp 并使用 .html 作为控制器模式?

回答by Animesh

I was also facing the same issue and tried various solutions to load the AngularJS html file using Spring configuration. After applying below steps it got resolved.

Step-1 in server's web.xml commemt these two lines

<!--     <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>--> 
<!--     <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
 -->

Step-2 enter following code in application's web xml

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>


Step-3

create a static controller class 

@Controller 
public class StatisController {
     @RequestMapping("/landingPage") 
    public String getIndexPage() { 
    return "CompanyInfo"; 

    }

}
Step-4 in the Spring configuration file change the suffix to .htm
        <property name="suffix">
            <value>.htm</value>
        </property>

Step-5
Rename page as .htm file and store it in WEB-INF and build/start the server 

localhost:8080/.../landingPage

回答by Abhi

//Finally a working solution both html and jsp view together 
------------------------------------------------------------------------

public class ChainableInternalResourceViewResolver extends InternalResourceViewResolver {

    private static Log logger = LogFactory.getLogger(ChainableInternalResourceViewResolver.class);

    /**
     * 
     */
    protected AbstractUrlBasedView buildView(String viewName) throws Exception {
        logger.entering("buildView");
        String url = getPrefix() + viewName + getSuffix();
        InputStream stream = getServletContext().getResourceAsStream(url);
        if (stream == null) {
            logger.log(Log.DEBUG,"-----!!!------resource not found-------!!!-----"+getPrefix() + viewName + getSuffix());
            return new NonExistentView();
        } else {
            logger.log(Log.DEBUG,"----***-------resource found-------***-----"+getPrefix() + viewName + getSuffix());
            stream.close();
        }
        return super.buildView(viewName);
    }

    /**
     * 
     * @author 
     *
     */
    private static class NonExistentView extends AbstractUrlBasedView {

        //private static Log logger = LogFactory.getLogger(NonExistentView.class);

        protected boolean isUrlRequired() {
            //logger.entering("isUrlRequired");
            return false;
        }

        public boolean checkResource(Locale locale) throws Exception {
            //logger.entering("checkResource");
            return false;
        }

        protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            //logger.entering("renderMergedOutputModel");
            // Purposely empty, it should never get called
        }
    }
}

----------------------------------------------------------------------------
@EnableWebMvc
@Configuration
@ComponentScan({ "com.*" })
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    //Be careful while changing here
    private static final String VIEW_DIR_HTML = "/WEB-INF/static/";
    private static final String VIEW_EXTN_HTML = ".html";

    private static final String VIEW_DIR_JSP = "/WEB-INF/";
    private static final String VIEW_EXTN_JSP = ".jsp";

    private static final String RESOURCE_URL_PATTERN_1 = "/resources/**";
    private static final String RESOURCE_URL_PATTERN_2 = "/WEB-INF/static/**";
    private static final String RESOURCE_PATH_1 = "/resources/";
    private static final String RESOURCE_PATH_2 = "/WEB-INF/static/";

    private static Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);

    /**
     * 
     * @return
     */
    @Bean
    public ViewResolver htmlViewResolver() {
        logger.info(" htmlViewResolver method ");
        InternalResourceViewResolver viewResolver= new ChainableInternalResourceViewResolver();
        viewResolver.setPrefix(VIEW_DIR_HTML);
        viewResolver.setSuffix(VIEW_EXTN_HTML);
        viewResolver.setOrder(0);
        return viewResolver;
    }

    @Bean
    public ViewResolver jspViewResolver() {
        logger.info(" jspViewResolver method ");
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix(VIEW_DIR_JSP);
        viewResolver.setSuffix(VIEW_EXTN_JSP);
        viewResolver.setOrder(1);
        return viewResolver;
    }

--------------------------------------------------------------------------------
return "pages/login"; // for login.html resides inside /WEB-INF/static/pages/login.html

return "jsp/login"; // for login.jsp resides inside /WEB-INF/jsp/login.jsp