Scriptico

Clean Spring MVC Web Application

As a base for the future blog entries, I have created a simple web application based on the Spring Web MVC framework and checked it in to the git repository. If you just want to take a look at the application (or maybe use it for your specific purposes), please use the github repository; however, if your are interested to create an application on your own, the following steps may be beneficial for you.

How to create a java based web application in Eclipse

The application is a simple java web application, ready to run in any application container, and it has a maven nature (do not worry if you have no idea about Maven, and just keep reading). There are a few steps to create the app:
Open the Eclipse IDE and navigate to File -> New -> Other… or try to click Control + n. In the opened window, select the Maven Project wizard and click the next button.
create a new maven project

The new maven project wizard window should not be changed, so just click the next button.
create a new maven project

The next window requires to select the maven archetype for the new application. For our application, the right archetype is maven-archetype-webapp
select the maven archetype

Now, it is time to define the archetype parameters, such as the group id (it identifies the project uniquely across all other projects), artifact id (the name of the war without version), version, and package (more information about the maven naming conventions is available on the maven official site). So, fill up the values and click the next button.
define the maven archetype parameters

As a result of this step, a new application should be successfully created and added to your workspace. The following screenshot shows the application structure in the eclipse project explorer.
maven project in eclipse

Technically, the application is created and ready for use, but I would like to make a small adjustment. The created application has a dependency to the junit library (it is defined in the selected archetype) and at this point, it may just confuse some readers. So, let me just get rid of it for now.

How to add the spring web mvc framework to the web application

As a first step, the spring mvc library is required. So, open the pom.xml from the project root, navigate to the dependencies tab and click on the “add” button. In the “select dependency” window, define the dependency parameters as shown below and click on the ok button. Finally, save the pom.xml changes and the spring mvc library, and its dependencies will be downloaded to your local repository automatically. That’s it about libraries.

According to the spring documentation, the DispatcherServlet class is a central dispatcher for HTTP request handlers/controllers in the framework, and it dispatches to registered handlers for processing a web request, providing convenient mapping and exception handling facilities. The DispatcherServlet servlet must be registered in the web.xml file  (this guy is located in the WEB-INF directory) as shown below:



	
		springmvc
		org.springframework.web.servlet.DispatcherServlet
		0
	

	
		springmvc
		/
	


The way how DispatcherServlet works is a bit out of this article scope, but if you are interested, please take a look at the oracle article “Core J2EE Patterns – Front Controller“. The very last point for this step is to create the servlet configuration file. Basically, it is a xml file located in the WEB-INF folder with the [servlet_name]-servlet.xml name. For our  springmvc servlet, the configuration file default name is springmvc-servlet.xml and its content is shown below:




	

	
		
			/WEB-INF/pages/
		
		
			.jsp
		
	

In this configuration file two things are defined – the base package to scan for components (in our case, a simple controller) and the view resolver to serve views for the application controllers; there is nothing special, and we are ready to jump to the last step.

Finally, the application supports the spring mvc framework! To test three steps taken previously, let’s create a simple controller and its view. The controller is a class marked with the @Controller annotation, and according to the official documentation, it is responsible for preparing a model Map with data and selecting a view name, but it can also write directly to the response stream and complete the request. The following code snippet demonstrates a simple controller that adds current date to the model (you will see how it works a bit later) and handles all GET requests to the site root and “index.html” url.

package com.scriptico.blog.sw.controllers;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExampleController {

	@RequestMapping(value={"/", "index.html"})
	public String index(final Model model) {

		model.addAttribute("currentDate", new Date());

		return "index";
	}
}

Now, we need to define a view for the created handler method. All views have to be located in the /WEB-INF/pages directory (as we defined it for InternalResourceViewResolver in the previous step), thus, the index.jsp file has to be placed into the location. For now, the index.jsp file from the webapp folder can be removed (if you are confused, please take a look at the eclipse project explorer screenshot at the beginning of the article).  As you may see, the index method returns a string “index” and in fact, this is the name of our view file. Since the file extension (i.e. .jsp) is defined as a suffix parameter for InternalResourceViewResolver, there is no need to return the full file name. The view file is shown below:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




Index Page


	This is a simple view for ExampleController#index
	
Today date is ${currentDate}

Now a few words about the model object. Simply speaking, the model object is a carrier from the controller to the view. As you can see, in the index method I add a date object to the model object and call this variable as “currentDate” and on the view page, I just fire the variable as ${currentDate}. You may play with the code on your own and check how you can use it.

Finally, the application is finished. To run the application, you need any application container, and by default, the application context root /springmvc-webapp/ (for instance, in my local environment the application’s complete url is http://localhost:8080/springmvc-webapp/.

Resources

Category: Development, Java, Servlets. JSP, Spring, Spring MVC, Web, WebApp

Tagged:

Comments are closed.