gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:34 25 4
gpt4 key购买 nike

我正在使用传统 war 部署使用 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;
}

}

一个简单的 Controller :

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 的“构建”命令并创建 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 的显式映射,因此您将其视为后备。

2016 年 2 月 1 日星期一 19:08:53 AZT出现意外错误(类型=未找到,状态=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'

我不明白为什么它说“映射“{[/index]}”到公共(public) java.lang.String org.aze.accountingprogram.controllers.IndexController.slash()”但在打开 URL 时不调用它/AZEAccountingProgram/index?

最佳答案

这是 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

关于java - 无法在 Spring Boot 应用程序中配置 ViewResolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com