Sunday, February 16, 2014

Spring WEB-MVC Project Setup (Pure Java Based Configuration) without using Database.

Introduction

Hello friends after long period of time this my new post. I hope you all like this post, if i do mistake in some where please notify me, my post is based on just share the knowledge, if any one done something good then me, please share with us. Thank you. 

Spring Provide Project configuration using java classes. Java Based Configuration have several benefits over XML configuration. But Some Developers Still have confusion with Java VS XML based Configuration. Here, WE are not discuss about Java or XML based Configuration best. I just create an example for setup Spring MVC project using Java Based Configuration. This Example is Maven Based Project. Following is the code :- 

Step 1  : Create a Maven Based Project


Step 2

Add Following Dependencies in Maven pom.xml

<properties>
<spring-version>4.0.0.RELEASE</spring-version>
</properties>

<!-- Spring Dependencies -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>

<!-- Servlet Dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

Step 3 : 

Create Java Based configuration file, for configure Spring-MVC : 
@Configuration

@EnableWebMvc

@ComponentScan("com.springjavaconfig.web")

public class WebAppConfig extends WebMvcConfigurerAdapter{
@Bean
public UrlBasedViewResolver setupViewResolver(){ /* if we pass on one vie reolver */
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
/* if we pass multiple view reolver use ContentNegotiationManager */
/*@Bean
public ViewResolver setupViewResolver(ContentNegotiationManager manager){
List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
resolvers.add(resolver);
ContentNegotiatingViewResolver resolver2 = new ContentNegotiatingViewResolver();
resolver2.setViewResolvers(resolvers);
resolver2.setContentNegotiationManager(manager);
return resolver2;
}*/
}

In this there are FOUR annotations are used. Following is the meaning of annotations : 
  1. @Configuration : This annotation indicates that, this java file contain configuration about BEANS, and tell to the Spring IOC container get the bean definition from this class. In XML this is corresponding to the <context:annotation-config/>. This annotation directly used AnnotationConfigApplicationContext
  2. @ComponentScan : This is used for Scan the package of components or beans, where i declare the component using annotations. In XML this is corresponding to <context:component-scan/>. Here is the good answer difference between <context:annotation-config /> and <context:component-scan />(Must Read)
  3. @EnableWebMvc : It enables support for @Controller Annotate classes That is @RequestMapping to map incoming request to a certain method. In XML it is equivalent to <mvc:annotation-driven/>. Here is the detail description.
  4. @Bean: This is used to create beans in an application. it is equivalent  to <bean> annotation in XML. This declare on a method that return Bean. The  annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context

Step 3:

Create an Initialize class which is used to register the dispatcher servlet with the application. The register of dispatcher servlet also declare as an inner class with same configuration file, But we think that it is a good practice to create a different class for this. This is same as we declare dispatcher servlet in web.xml. Because of servlet 3.0 the Deployment Descriptor(Web.xml) is optional and new tomcat version also run application without web.xml. So spring provide a way to register the DispatcherServelt using Java Based configuration. 
Following is the code : 

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
  @Override 
  protected Class<?>[] getRootConfigClasses() {  
  return new Class<?>[0]; 
  }

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


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

In this the AbstractAnnotationConfigDispatcherServletInitializer is used to register the dispatcher servlet using java configuration. Here is the detail description of class.

Step 4 : 

Create the controller class for handle the request and return response.  Following is the code : 

@Controller
public class FirstController {

@RequestMapping("/helloworld")
public String helloWOrld(){
System.out.println("In Controller ******* ");
return "helloworld";
}
}

Step 5 : 

Create an jsp file under webapp -> WEB-INF -> pages. Following is the code. 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>FIrst JSP</title>
</head>
<body>
<h1>HEllo JSP</h1>
</body>
</html>

Add the tomcat in your IDE if you are using and run the application easily. Hit the URL http://localhost:8080/spring-config/helloworld and say HelloWorld. 

Note: 

The web.xml is option if you want to configure something with DD, you can use it. but for this example there is no need of web.xml. it depends on you and yor requirements. 


7 comments: