Java Config with Spring MVC

Spring MVC Java Config settings

I will describe the basic WEB application setting method of Spring MVC as a memorandum. With this setting, I think you can create an app like Hello World.

I myself have experience in creating apps for Spring Boot during in-house training. I didn't create an app by setting it from scratch with Spring MVC, so I created it. This was a very good opportunity, as most of my work was done with things that were already set up and working.

By the way, xml-based setting is possible, but this time we will set it based on Java. First, I will introduce some examples of the basic setting classes.

WebAppInitializer

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {


	@Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] {ApplicationConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
	protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
		return new DispatcherServlet(servletAppContext);
	}

}

The setting class (ApplicationConfig) to be created later and the raw DispatcherServlet are registered. If you have added your own implementation, you can set it by changing this setting.

ApplicationConfig

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackageClasses = Application.class)
class ApplicationConfig {

	@Bean
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}
	
}

It mainly sets the application interface that is the target of component scanning. Create Application.class set in the basePackageClasses attribute as an interface in the package to be scanned. Also, @EnableAspectJAutoProxy is required to use AspectJ.

WebMvcConfig

@Configuration
class WebMvcConfig extends WebMvcConfigurationSupport {

	private static final String CHARACTER_ENCODING = "UTF-8";

	private static final String VIEW_LOCATION = "/WEB-INF/view/";

	private static final String[] PROPERTIES_LIST = { "classpath:/MessageResources" };

	@Bean(name = "messageSource")
	public MessageSource messageSource() {
		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		messageSource.setBasenames(PROPERTIES_LIST);
		messageSource.setCacheSeconds(5);
		messageSource.setDefaultEncoding(CHARACTER_ENCODING);
		return messageSource;
	}

	@Bean(name = "messageResources")
	public MessageResources messageResources() {
		return new MessageResources();
	}

	@Override
	protected void configureViewResolvers(ViewResolverRegistry registry) {
		registry.jsp().prefix(VIEW_LOCATION).suffix("");
	}

}

Here, the message resource and ViewResolver are mainly set. Change the setting value as appropriate.

If you are using jsp, there is no problem with the above setting format, but if you use a template engine such as Thymeleaf, you need to change the setting. File upload related (Multipart Resolver) and tiles settings are also possible here, but this time it is not a mast so I will omit it. (Let's write in separate article)

This is the main setting on the Java side. After that, I will write web.xml as much as I feel.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>Spring-MVC</display-name>

	<error-page>
		<error-code>404</error-code>
		<location>/WEB-INF/view/error/404.jsp</location>
	</error-page>
	<error-page>
		<error-code>405</error-code>
		<location>/WEB-INF/view/error/405.jsp</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/WEB-INF/view/error/500.jsp</location>
	</error-page>

</web-app>

It's simple just by setting the error page. I think that you can add filter and listener settings, taglib customizing, etc. here as needed. (The filter / listener can also be set in Java Config)

With the above settings, Hello World can be created by implementing a simple Controller and jsp.

Hello World!!.png

I'm happy. I hope it will be helpful when creating apps with Spring MVC.

That's it.

Recommended Posts

Java Config with Spring MVC
Using Mapper with Java (Spring)
Spring Java
Implement file download with Spring MVC
[Java] LINE integration with Spring Boot
[Java Spring MVC] Controller for development confirmation
Implement image input / output with Spring MVC
[Java] Spring DI ③
Just input and output images with Spring MVC
Test controller with Mock MVC in Spring Boot
Understanding the MVC framework with server-side Java 1/4 View
Understanding the MVC framework with server-side Java 3/4 Controller
Request parameter log output sample Java & Spring MVC
[Java] Hello World with Java 14 x Spring Boot 2.3 x JUnit 5 ~
[JAVA] [Spring] [MyBatis] Use IN () with SQL Builder
[Java] Article to add validation with Spring Boot 2.3.1.
Understanding the MVC framework with server-side Java 2/4 Model
Create Spring Cloud Config Server with security with Spring Boot 2.0
Install java with Homebrew
Change seats with java
Install Java with Ansible
Spring with Kotorin --- 5. Actuator
Comfortable download with JAVA
Switch java with direnv
Download Java with Ansible
Self-made Validation with Spring
Let's scrape with Java! !!
Build Java with Wercker
Spring with Kotorin ―― 1. SPRING INITIALIZR
Download with Spring Boot
Endian conversion with JAVA
I tried to implement file upload with Spring MVC
[Java] [Spring Boot] Specify runtime profile --Spring Boot starting with NetBeans
[Java] How to omit spring constructor injection with Lombok
Spring Security usage memo: Cooperation with Spring MVC and Boot
Java + Spring development environment construction with VirtualBox + Ubuntu (Xfce4)
Java multi-project creation with Gradle
Getting Started with Java Collection
MOCK constructors of other classes with Spring MVC + PowerMock + Junit
[Java / Kotlin] Escape (sanitize) HTML5 support with unbescape [Spring Boot]
Generate barcode with Spring Boot
Basic Authentication with Java 11 HttpClient
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
Spring RedisTemplate Config Timeout setting
[Java] JSON communication with jackson
Implement GraphQL with Spring Boot
Java to play with Function
Try DB connection with Java
Spring + Gradle + Java Quick Start
Spring with Kotorin --8 Repository layer
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Spring RestTemplate Config Timeout setting
Enable Java EE with NetBeans 9
Get started with Spring boot
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!