Can't configure ViewResolver in Spring Boot application

12,847

Solution 1

The URL localhost:8080/index will return index.jsp page becaues / is the default context path when using spring boot. To add a custom context-path to a spring boot application, you can simply add a property

server.context-path=AZEAccountingProgram

in application.properties under src/main/resources folder.

See this Spring Boot documentation for the properties configuration.

Solution 2

This is a last version of 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);
    }

}

also, as Omkar Puttagunta said, I should call localhost:8080/index instead of localhost:8080/AZEAccountingProgram/index

Share:
12,847
Tural
Author by

Tural

Updated on August 21, 2022

Comments

  • Tural
    Tural over 1 year

    I'm developing Spring Web application using Spring Boot using traditional war deployment. Now I have main configuration file:

    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 configuration:

    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;
        }
    
    }
    

    one simple 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";
        }
    
    }
    

    and one simple jsp named "index.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 file:

    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')
        }
    }
    

    When I run application via Tomcat (IDE calls "build" command of Gradle and creates war file, then IDE deploys this war file into Tomcat and run it) I receive the following log:

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: 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
    

    When I open URL http://localhost:8080/AZEAccountingProgram/index it returns blank page (empty response).

    When I run application using command "bootRun" and try to open page, I receive and error page:


    Whitelabel Error Page

    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    Mon Feb 01 19:08:53 AZT 2016 There was an unexpected error (type=Not Found, status=404). No message available


    and log:

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: 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'
    

    I don't understand why it says "Mapped "{[/index]}" onto public java.lang.String org.aze.accountingprogram.controllers.IndexController.slash()" but do not call it when opening URL /AZEAccountingProgram/index?