Skip to content

small java spring app breakdown

Eric F. Alsheimer edited this page Jan 23, 2018 · 3 revisions

Java Spring Web MVC application

This is based on the spring-mvc-java-config-demo project, which itself is an annotated version of the spring-mvc-demo-1 project.

This project moved all the configuration from XML-based to annotation based while maintaining the base functionality of a Hello World application, and as such is an excellent primer for Web MVC and the most necessary annotations.

"Given" code units.

The WelcomeController.java, WelcomeService.java, GenericWelcomeService.java, and WEB-INF/views/welcomeNew.jsp files are all 'stock', meaning their beans or code conduct their operation regardless of the type of container context we are trying to utilize.

Add WebMvcContext

In the .config package, you will place a blank WebMvcConfig.java class and a blank WebMvcInitializer.java class.

WebMvcConfig.java

WebMvcConfig.java implements the WebMvcConfigurer superclass and provides instructions for the project infrastructure. At this point, all we need to wire up is what technology we will use for resolving views. We will use the UrlBasedViewResolver because it is the superclass for all other view-resolving technology.

All MVC frameworks provide a way of working with views.

Spring does that via the view resolvers, which enable you to render models in the browser without tying the implementation to a specific view technology.

The ViewResolver maps view names to actual views.

And the Spring framework comes with quite a few view resolvers e.g. InternalResourceViewResolver, XmlViewResolver, ResourceBundleViewResolver and a few others.

package com.lab49.springdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration
@ComponentScan("com.lab49.springdemo")
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
	
  @Bean
  public UrlBasedViewResolver urlBasedViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }
}

So here we identify that:

  • @Configuration - this class will provide configuration information to the Spring container.
  • @ComponentScan - parse all definitions in the package "com.lab49.springdemo" and translate the @Component (and derivatives like @Service and @Controller) to Spring beans.
  • @EnableWebMvc - identifies this Spring application as a web MVC application, recognizing things like @Controller annotations as having actions instead of methods and tying @RequestMapping annotations to the DispatcherServlet.
  • implement WebMvcConfigurer - this interface provides many stock methods for tying the configuration into the servlet for a web application. This reduces your boilerplate and tags your application.
  • @Bean - this registers that the following action will return a bean. This is used in @Configuration classes to identify the beans that will be provided. In this example, when the application reads in the configuration by component scanning, it will also create a new UrlBasedViewResolver as needed by running this method and registering the resulting instance as a bean.
  • new UrlBasedViewResolver - this is the technology we have chosen for this application. UrlBasedViewResolver is the superclass for all other view resolvers. For instance, the InternalResourceViewResolver inherits from UrlBasedViewResolver and adds logic to make it easier to use beans in the view.
  • setPrefix - this says to use the following directory off the WebContent directory for finding the correct view.
  • setSuffix - this says to use the following file extensions for finding the correct view.
  • setting setPrefix and setSuffix - These are used to reduce declarations for the appropriate view needed in the controller. Identifying "WEB-INF/views/.jsp" every time can be prone to errors.
  • JstlView.class - this lets the view resolver know to process the related views as a JavaServerPages Standard Tag Library type, as opposed to Tiles or something else.

WebMvcInitializer.java

WebMvcInitializer.java implements the WebApplicationInitializer superclass and ties the configuration (above) to the web container context.

package com.lab49.springdemo.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebMvcInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
		
    rootContext.register(WebMvcConfig.class);
		
    ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    registration.addMapping("/");
    registration.setLoadOnStartup(1);
  }
}

So here we identify that:

  • No @Configuration - this class exists to wire up configuration and does not provide any bean configuration of its own.
  • ServletContext - this is the way a servlet communicates with a servlet container. There is one context per web application.
  • AnnotationConfigWebApplicationContext - this class acknowledges that the system is set for annotations to determine web functionality.
  • AnnotationConfigWebApplicationContext#register - this action applies the WebMvcConfig (defined above) to the web application, and so provides all Controller, Service, etc. beans to the web application.
  • ServletRegistration - this is the interface through which servlets can be registered with the web application
  • ServletRegistration.Dynamic - this is the way to register servlets using the servlet's #addServlet method
  • ServletContext#addServlet - tells the servlet container to register a servlet with a certain name and class type to this context.
  • registration - the handle for accessing the servlet registered with the servlet context...in this case, the DispatcherServlet.
  • addMapping - tell the DispatcherServlet to map requests for a base URL path
  • setLoadOnStartup - Sets the loadOnStartup priority on the Servlet represented by this dynamic ServletRegistration. If 1, it is available on load. If negative, the servlet will be available lazily.

Clone this wiki locally