Spring MVC获取HTTP 500而不是HTTP 404

时间:2015-06-03 17:16:13

标签: java spring spring-mvc thymeleaf

尝试访问不存在的资源时出现以下错误。

HTTP状态500 - 请求处理失败;嵌套异常是org.thymeleaf.exceptions.TemplateInputException:解析模板" pages / inexistentResource"时出错,模板可能不存在,或者任何已配置的模板解析器都无法访问

我希望在这些情况下获得HTTP状态404,以便我的web-xml可以将用户重定向到我的应用程序中未找到的正确页面。看起来我的模板引擎有点太过触发式的快乐,并且在不存在的资源上被调用。

这是我的配置:

public class WebConfigSupport extends WebMvcConfigurationSupport {

    @Autowired
    private Environment env;

    @Autowired
    private ServletContext servletContext;


    /**
     * Builds a template resolver, the one who translates template names into template objects.
     */
    @Bean
    public ServletContextTemplateResolver defaultTemplateResolver() {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
        resolver.setPrefix("/");
        resolver.setSuffix(".html");
        //resolver.setTemplateMode("XHTML");
        resolver.setTemplateMode("LEGACYHTML5");
        resolver.setOrder(1);
        resolver.setCacheable(false);
        return resolver;
    }

    /**
     * Builds the template engine for Spring MVC.
     */
    @Bean
    public SpringTemplateEngine templateEngine() {
        Set<IDialect> dialects = Sets.newHashSet();
        dialects.add(new SpringSecurityDialect());

        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(defaultTemplateResolver());
        engine.addDialect(new LayoutDialect());
        engine.setAdditionalDialects(dialects);
        return engine;
    }

    /**
     * Builds the thymeleaf view resolver.
     */
    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        return resolver;
    }
    ...
}

我的web.xml:

  ...
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>httpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>httpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <error-page>
    <error-code>404</error-code>
    <location>/portal/errors/404</location>
  </error-page>
  ...

我不是春季职业选手,所以我对自己的错误感到很沮丧,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

把你所有的html或jsp文件,在你的情况下,你被提到.html扩展名。

希望如此,看起来像WEB-INF/folderName/.html files

在resolver.setPrefix中添加如下内容,根据您的html folderName

    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".html");