簡體   English   中英

無法在Spring Boot應用程序中配置ViewResolver

[英]Can't configure ViewResolver in Spring Boot application

我正在使用傳統的戰爭部署使用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

當我打開URL http:// localhost:8080 / AZEAccountingProgram / index時,它返回空白頁面(空響應)。

當我使用命令“bootRun”運行應用程序並嘗試打開頁面時,我會收到錯誤頁面:


白標錯誤頁面

此應用程序沒有/ 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 /時不要調用它指數?

這是MvcConfiguration的最后一個版本

@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        registry.viewResolver(resolver);
    }

}

另外,正如Omkar Puttagunta所說,我應該調用localhost:8080 / index而不是localhost:8080 / AZEAccountingProgram / index

URL localhost:8080/index將返回index.jsp頁面,因為/是使用spring boot時的默認context path 要向Spring引導應用程序添加自定義context-path ,只需添加屬性即可

server.context-path=AZEAccountingProgram

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

有關屬性配置,請參閱 Spring Boot文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM