无法在Spring Boot应用程序中配置ViewResolver

时间:2016-02-01 15:12:56

标签: java spring spring-mvc tomcat spring-boot

我正在使用传统的战争部署使用Spring Boot开发Spring Web应用程序。现在我有主配置文件:

package org.aze.accountingprogram;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.filter.CharacterEncodingFilter;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

    @Bean
    public FilterRegistrationBean encodingFilter() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter("UTF-8", true);
        FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
        filterRegBean.setUrlPatterns(getRootPathUrls());
        filterRegBean.setFilter(encodingFilter);
        filterRegBean.setOrder(1);
        return filterRegBean;
    }

    private List<String> getRootPathUrls() {
        List<String> urlPatterns = new ArrayList<String>();
        urlPatterns.add("/*");
        return urlPatterns;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

MVC配置:

package org.aze.accountingprogram;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver setupViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);

        return resolver;
    }

}

一个简单的控制器:

package org.aze.accountingprogram.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @RequestMapping("/index")
    public String slash() {
        return "index";
    }

}

和一个名为“index.jsp”的简单jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head><title>Simple jsp page</title></head>
  <body>Place your content here</body>
</html>

Gradle文件:

group 'org.aze.accountingprogram'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'spring-boot'

allprojects {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

repositories {
    mavenCentral()
}

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.2.RELEASE")
    }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter")
    compile("org.springframework.boot:spring-boot-starter-web")
//    compile("org.springframework.boot:spring-boot-starter-jdbc")
//    runtime("mysql:mysql-connector-java")
    compile("org.springframework.boot:spring-boot-starter-logging")
    compile("javax.servlet:jstl")
    providedRuntime("org.apache.tomcat.embed:tomcat-embed-jasper")
    providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
    testCompile("org.springframework.boot:spring-boot-starter-test")
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

configurations {
    compile.exclude group: 'commons-logging'
    compile.exclude group: 'org.apache.logging.log4j'
    compile.exclude group: 'log4j'
    providedRuntime
}

war {
    archiveName = 'AZEAccountingProgram.war'
    destinationDir = file('dist')
}

idea {
    project {
        //if you want to set specific jdk and language level
        jdkName = '1.8'
        languageLevel = '1.8'
    }
    module {
        //if you love browsing Javadoc
        downloadJavadoc = true
        jdkName = '1.8'
        excludeDirs += file('.nb-gradle')
        excludeDirs += file('.gradle')
        excludeDirs += file('out')
        excludeDirs += file('gradle')
        excludeDirs += file('build')
        excludeDirs += file('dist')
    }
}

当我通过Tomcat运行应用程序时(IDE调用Gradle的“build”命令并创建war文件,然后IDE将此war文件部署到Tomcat并运行它)我收到以下日志:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.2.RELEASE)

2016-02-01 18:59:55.684  INFO 3360 --- [on(2)-127.0.0.1] org.aze.accountingprogram.Application    : Starting Application on ICT-255L with PID 3360 (started by ittural in C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin)
2016-02-01 18:59:55.692  INFO 3360 --- [on(2)-127.0.0.1] org.aze.accountingprogram.Application    : The following profiles are active: dev
2016-02-01 18:59:55.786  INFO 3360 --- [on(2)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@69f965da: startup date [Mon Feb 01 18:59:55 AZT 2016]; root of context hierarchy
2016-02-01 18:59:57.893  INFO 3360 --- [on(2)-127.0.0.1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2107 ms
2016-02-01 18:59:59.261  INFO 3360 --- [on(2)-127.0.0.1] b.a.w.TomcatWebSocketContainerCustomizer : NonEmbeddedServletContainerFactory detected. Websockets support should be native so this normally is not a problem.
2016-02-01 18:59:59.326  INFO 3360 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'errorPageFilter' to: [/*]
2016-02-01 18:59:59.327  INFO 3360 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-02-01 18:59:59.327  INFO 3360 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Filter characterEncodingFilter was not registered (possibly already registered?)
2016-02-01 18:59:59.327  INFO 3360 --- [on(2)-127.0.0.1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
01-Feb-2016 18:59:59.556 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\manager
2016-02-01 18:59:59.973  INFO 3360 --- [on(2)-127.0.0.1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/index]}" onto public java.lang.String org.aze.accountingprogram.controllers.IndexController.slash()
2016-02-01 19:00:00.007  INFO 3360 --- [on(2)-127.0.0.1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-02-01 19:00:00.008  INFO 3360 --- [on(2)-127.0.0.1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-02-01 19:00:00.222  INFO 3360 --- [on(2)-127.0.0.1] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@69f965da: startup date [Mon Feb 01 18:59:55 AZT 2016]; root of context hierarchy
2016-02-01 19:00:00.258  INFO 3360 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
01-Feb-2016 19:00:00.296 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\manager has finished in 739 ms
2016-02-01 19:00:01.419  INFO 3360 --- [on(2)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-02-01 19:00:01.454  INFO 3360 --- [on(2)-127.0.0.1] org.aze.accountingprogram.Application    : Started Application in 7.461 seconds (JVM running for 14.918)
[2016-02-01 07:00:01,487] Artifact AZEAccountingProgram.war: Artifact is deployed successfully
[2016-02-01 07:00:01,487] Artifact AZEAccountingProgram.war: Deploy took 11 792 milliseconds

当我打开网址http://localhost:8080/AZEAccountingProgram/index时,它会返回空白页面(空响应)。

当我使用命令“bootRun”运行应用程序并尝试打开页面时,我会收到错误页面:

Whitelabel错误页面

此应用程序没有/ error的显式映射,因此您将此视为后备。

Mon Feb 01 19:08:53 AZT 2016 出现意外错误(type = Not Found,status = 404)。 没有可用的消息

并记录:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.2.RELEASE)

2016-02-01 19:08:18.194  INFO 4424 --- [           main] org.aze.accountingprogram.Application    : Starting Application on ICT-255L with PID 4424 (D:\Projects\AZEAccountingProgram\build\classes\main started by ittural in D:\Projects\AZEAccountingProgram)
2016-02-01 19:08:18.194  INFO 4424 --- [           main] org.aze.accountingprogram.Application    : The following profiles are active: dev
2016-02-01 19:08:18.303  INFO 4424 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4dbb42b7: startup date [Mon Feb 01 19:08:18 AZT 2016]; root of context hierarchy
2016-02-01 19:08:21.040  INFO 4424 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-02-01 19:08:21.071  INFO 4424 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-02-01 19:08:21.071  INFO 4424 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.30
2016-02-01 19:08:21.607  INFO 4424 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2016-02-01 19:08:21.607  INFO 4424 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-02-01 19:08:21.607  INFO 4424 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3319 ms
2016-02-01 19:08:21.795  INFO 4424 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-02-01 19:08:21.795  INFO 4424 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Filter characterEncodingFilter was not registered (possibly already registered?)
2016-02-01 19:08:21.795  INFO 4424 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-02-01 19:08:22.068  INFO 4424 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/index]}" onto public java.lang.String org.aze.accountingprogram.controllers.IndexController.slash()
2016-02-01 19:08:22.083  INFO 4424 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-02-01 19:08:22.083  INFO 4424 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-02-01 19:08:22.208  INFO 4424 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4dbb42b7: startup date [Mon Feb 01 19:08:18 AZT 2016]; root of context hierarchy
2016-02-01 19:08:22.758  INFO 4424 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-02-01 19:08:22.852  INFO 4424 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-02-01 19:08:22.852  INFO 4424 --- [           main] org.aze.accountingprogram.Application    : Started Application in 5.319 seconds (JVM running for 5.994)
2016-02-01 19:08:52.995  INFO 4424 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-02-01 19:08:52.995  INFO 4424 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-02-01 19:08:53.028  INFO 4424 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 33 ms
2016-02-01 19:08:53.057  WARN 4424 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/AZEAccountingProgram/index] in DispatcherServlet with name 'dispatcherServlet'

我不明白为什么它将“Mapped”{[/ index]}“写入公共java.lang.String org.aze.accountingprogram.controllers.IndexController.slash()”但是在打开URL时不要调用它/ AZEAccountingProgram /索引?

2 个答案:

答案 0 :(得分:3)

这是MvcConfiguration的最后一个版本

AutoExpandReplicas.java:44 : cannot assign to the final variable min
min = Integer.parseInt(sMin);

另外,正如Omkar Puttagunta所说,我应该调用localhost:8080 / index而不是localhost:8080 / AZEAccountingProgram / index

答案 1 :(得分:2)

网址localhost:8080/index将返回index.jsp页面,因为/是使用spring boot时的默认context path。 要将自定义context-path添加到Spring启动应用程序,只需添加属性

即可
server.context-path=AZEAccountingProgram

application.properties文件夹下的src/main/resources

有关属性配置,请参阅this Spring Boot文档。