Spring 4 MVC – 100% annotation based configuration

We have seen different Hello World for Spring 4 earlier posts.

I am trying to minimise the XML config as much as possible. Here is the way for a Spring 4 MVC environment purely based on java annotations.

Have the following ready –

  1. JDK 8 x64 (1.5 may not work as expected)
  2. Tomcat 8 x64
  3. Spring 4 – Maven dependencies are given in this post.
  4. STS or Eclipse latest version

WebApplicationInitializer

We are not using web.xml boss. So lets make write the WebApplicationInitializer first!

Create a dynamic web project in STS or Eclipse. Write the initializer code first. This defines the web application initializer for Tomcat. This defines our spring controller servlet “SpringDispatcher”.  Happy?

[code language=”java”]
package org.grassfield.conf;

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 SpringWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
        appContext.register(ApplicationContextConfig.class);

        ServletRegistration.Dynamic dispatcher = container.addServlet(
                "SpringDispatcher", new DispatcherServlet(appContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }

}
[/code]

WebMvcConfigurerAdapter

Friends, write your view logic here. Lets use simple viewResolver for this purpose. My controllers will send me the name of the view. I’ll choose the right jsp inside the /WEB-INF/views. Here you go! Please note the annotations @Configuration @EnableWebMvc @ComponentScan

[code language=”java”]
package org.grassfield.conf;
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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"org.grassfield.conf"})
public class ApplicationContextConfig extends WebMvcConfigurerAdapter{

    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}[/code]

Request Handler

Let’s have a simple servlet first!  This controller will handle the request pattern / and redirects the request to the view ‘home’. Please note the annotations @Controller @RequestMapping

[code language=”java”]
package org.grassfield.conf;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @RequestMapping("/")
    public ModelAndView handleRequest(HttpServletRequest arg0,
            HttpServletResponse arg1) throws Exception {
        return new ModelAndView("home");
    }
}
[/code]

View Jsp

Lets write the jsp to show the output in /WEB-INF/views/home.jsp

[code language=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Bootstrap</title>
</head>
<body>
<div align="center">
<h1>Welcome to Spring MVC Bootstrap demo!</h1>
<h3>100% code-based approach, no XML at all!</h3>
</div>
</body>
</html>
[/code]

Dependencies

Convert this project to a maven project. Following will be the dependency specification. This will include all the libraries, I’m going to add to the same module in the future.

[code language=”xml”]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>vriksha05</groupId>
    <artifactId>vriksha05</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src</sourceDirectory>

        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <spring.version>4.1.6.RELEASE</spring.version>
        <spring.security.version>4.0.0.RELEASE</spring.security.version>
        <spring.security.config.version>4.0.0.RELEASE</spring.security.config.version>
        <cglib.version>2.2.2</cglib.version>
        <hibernate.version>4.3.8.Final</hibernate.version>
        <mysql.connector.version>5.1.34</mysql.connector.version>
        <dbcp.version>2.1</dbcp.version>
        <servlet.version>1.2</servlet.version>
        <jsp.version>2.3.1</jsp.version>
        <commons.logging.version>1.1.3</commons.logging.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!– Security –>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.config.version}</version>
        </dependency>

        <!– ORM –>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!– Hibernate –>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!– DBCP –>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${dbcp.version}</version>
        </dependency>

        <!– MySQL –>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>

        <!– Servlet/JSP –>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${servlet.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>

        <!– Logging –>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>${commons.logging.version}</version>
        </dependency>

        <!– CGLib for @Configuration –>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>${cglib.version}</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>
</project>
[/code]

Enjoy..

spring4_java_annotation

Apache-Tomcat-logo image00110 java8-logo spring-tool-suite-project-logo

4 thoughts on “Spring 4 MVC – 100% annotation based configuration”

  1. Pingback: Spring 4 MVC and Spring Security 100% java annotation based configuration | JavaShine

  2. Pingback: Spring 4 MVC and JDBC authenticated Spring Security – 100% java annotation based configuration | JavaShine

  3. Pingback: Spring 4 MVC + Spring 3 Security + Hibernate 4 – integration with java annotations | JavaShine

  4. Hi,
    I got this error.

    Dec 13, 2017 4:06:56 PM org.springframework.web.servlet.PageNotFound noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/Jessica-shared-services/WEB-INF/views/home.jsp] in DispatcherServlet with name ‘SpringDispatcher’

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top