Spring MVC ViewResolver无法映射到HTML文件

时间:2014-07-27 12:13:43

标签: spring spring-mvc

我无法获得spring mvc来解析.html视图文件。

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

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

我有一个简单的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>

当我点击太空飞船/家中时,控制器打印出hello world消息,我看到了 home.jsp视图没有问题。

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

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

澄清:

<!-- 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>

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

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

最后一块控制台消息:

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'

感谢阅读。

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

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

文件夹结构:

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

控制器方法:

 @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>

4 个答案:

答案 0 :(得分:9)

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

Which spring view resolver plays nice with angularjs?

简单来说:

为了在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

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

答案 1 :(得分:3)

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

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

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

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

所以考虑到这个,一个潜在的修复方法是添加.html来添加jsp servlet来处理,如下所示:

Using .html files as JSPs

甚至更好,将扩展名保留为.jsp并使用.html作为控制器模式?

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

//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