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?

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("/*");
    }

}

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

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

 

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

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

 

View Jsp

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

<%@ 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>
    
       

Welcome to Spring MVC Bootstrap demo!

       

100% code-based approach, no XML at all!

   
</body> </html>

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.

 

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

 

Enjoy..

spring4_java_annotation

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

 

Eclipse : Invalid project description

Hi,

This is a headache. I am using Eclipse 3.2. I have chosen, say, c:test as my work directory, then I couldnt create a project in any of those subdirectories, If I choose c:testproject as my project folder and I click Finish, I am getting the above error:

“Invalid project description.

C:testproject overlaps the workspace location: C:test

Later I found the reason from one of the forums.

(sponsored)securePHPhosting.com
Reply
1. At 10:17 AM on Mar 14, 2006, John Arthorne wrote:
Re: Invalid project description error message returned when importing projects.
It was not valid in Eclipse 3.1 for a project to be stored in a
sub-directory under the workspace directory. The 26 project directories
need to be moved up to the “workspace” directory, or the “agprojects”
directory needs to be moved outside the workspace directory. This
restriction is being lifted in Eclipse 3.2.

He says it has been lifted. but still i am in trouble….!!

Bye Bye NetBeans

I read an interesting log at “Xyling Java Blog”. He is complaining Netbeans consumes lot of memory even in legacy systems. I dont know about this becaz i’m an obliged Eclipse user. But the article is really interesting 🙂

here is the link,
http://javablogs.xyling.com/2006/08/bye-bye-netbeans.html?rss


—————————————————
*Free* software is a matter of liberty not price. You should think of “free” as in “free speech”.