View RSS Feed

Spring Framework

Building your first Spring 3 MVC application using Eclipse

Rating: 7 votes, 3.00 average.
by , 12-10-2011 at 06:51 AM (30259 Views)
Spring is one of the most popular application frameworks for Java development. The framework comes with various projects like Spring Core, Spring Data, Spring Web Services, Spring MVC…Each project suits for a particular area, and for the area of web development, Spring MVC is very well-known.
Spring MVC makes web development easier by separating the three components: Model, View, and Controller.

  • The model represents the principal data that is managed by the application.
  • The view represents the user interface, based on the model data transferred by the controller.
  • The controller connects the view and the model together and defines the work flow of the application.


You will be getting familiar with the Spring MVC framework throughout this article, by developing a simple project as explained in the next paragraph.

The Spring 3 MVC project

The project which we are going to develop is a tiny and simple web application. It presents a login form to the user. If the user submits a valid credential, he will be greeted by a welcome message. Otherwise, a warning message is displayed.
Technically, the project demonstrates implementation of some fundamental Spring MVC features to build a web application following the MVC paradigm.

Prerequisites

You are supposed to be familiar with Eclipse IDE and Tomcat web container, as this article will walk you through some Eclipse wizards and deployment with Tomcat.

  • Eclipse version: 3.3.2 or later.
  • Tomcat version: 6.0 or later.
  • Java version: Java SE 6.0 or later.


Download Libraries

Download the latest version of Spring framework at the following URL: http://www.springsource.com/download...ng%20Framework
Upon this article is written, the latest version is 3.1.0 RC2. Extract the bundle file spring-framework-3.1.0.RC2.zip and open the dist directory which contains JAR files for Spring core and Spring MVC. You will be copying some of these files into the project after creating the project.

In addition, you need to have other two libraries:



Creating new Eclipse project

Go to File -> New… -> Project… In the New Project wizard dialog, expand the Web branch, and select Dynamic Web Project:

Name:  new project 1.PNG
Views: 14577
Size:  21.3 KB
Figure: The New Project dialog

Click Next, on the New Dynamic Web Project dialog, type “HelloSpring” for the field Project name, leave other settings as default, then click Next:

Name:  screenshot1.PNG
Views: 14411
Size:  26.6 KB
Figure: The Dynamic Web Project screen

In the Project Facets dialog, make sure that you select the version for Dynamic Web Module is 2.5 and Java version is 6.0, as the following screenshot:

Name:  screenshot3.PNG
Views: 14356
Size:  26.5 KB
Figure: Select versions for the project

Then click Finish, Eclipse will generate some skeleton code for the project.
Create this package under src directory: com.spring.study. Our Java code will be going under this package.

Adding JAR libraries

Copy the following JAR files downloaded from the previous step to the directory WebContent/WEB-INF/lib:

  • commons-logging-1.x.x.jar
  • org.springframework.asm-3.x.x.jar
  • org.springframework.beans-3.x.x.jar
  • org.springframework.context-3.x.x.jar
  • org.springframework.core-3.x.x.jar
  • org.springframework.expression-3.x.x.jar
  • org.springframework.web.servlet-3.x.x.jar
  • org.springframework.web-3.x.x.jar
  • standard-1.x.jar


Right click on the project name, then select Properties. In the Properties for HelloSpring dialog, select the node Java Build Path on the right. Expend the node Web App Libraries in the list JARs and class folders on the build path, you should see a screen as following:

Name:  screenshot4.PNG
Views: 14376
Size:  45.8 KB
Figure: The Project Properties dialog

Configuring web.xml

In order to let the Spring framework intercepts all request coming to our application, we need to configure the framework’s dispatcher servlet in the web deployment descriptor file (web.xml). Open the web.xml file under WebContent/WEB-INF directory, and make sure it has the following content:

XML Code: The web deployment descriptor file
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 <display-name>HelloSpring</display-name>
 
  <servlet>
      <servlet-name>SpringDispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring-context.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>       

  <servlet-mapping>
      <servlet-name>SpringDispatcherServlet</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
     
</web-app>
In the web.xml, we declare the servlet SpringDispatcherServlet which comes from Spring’s class org.springframework.web.servlet.DispatcherServlet, and this servlet is mapped to handle all requests coming to the application, as denoted by the URL pattern “/”.
We also configure the Spring’s configuration file via a parameter of the servlet, the contextConfigLocation, so let create a file called spring-context.xml and put it under the WebContent/WEB-INF directory.

Configuring Spring

We don’t need to put much XML stuffs to configure Spring MVC working with our application, and since Spring 3, developers can use annotation in Java classes to declare Controller class, mappings… so the XML configuration is very simple. Open the spring-context.xml file, add the following lines of code:

XML Code: The Spring configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
       [url]http://www.springframework.org/schema/mvc[/url] [url]http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd[/url]
       [url]http://www.springframework.org/schema/beans[/url] [url]http://www.springframework.org/schema/beans/spring-beans-3.0.xsd[/url]
       [url]http://www.springframework.org/schema/context[/url] http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.spring.study" />

   <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
The tag <context:component-scan /> tells Spring autodect all classes under the specified package and register them as corresponding beans. We will write a controller class by using annotation, and Spring will autodetect the controller and register it as controller bean.
The tag <mvc:annotation-driven /> tells Spring to do a number things but for MVC, the framework should dispatch all incoming requests to the registered controllers.

We define only one bean in the configuration file, the InternalResourceViewResolver bean, to map the logical names of views requested from the controller with the actual JSP files. The property prefix and suffix will add prefixes and suffixes to the view’s names. Our JSP files will be put under WEB-INF/jsp directory, so let’s create that directory now.

Writing the model

The goal of our application is to authenticate user, so let’s create a new Java class, User.java. This class defines a user and its code looks like the follow:


Java Code: The User.java class
package com.spring.study;

public class User {
    private String login;
    private String password;
   
    public String getLogin() {
        return login;
    }
    public void setLogin(String login) {
        this.login = login;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }  
}


The User class has only two private members, login and password. They are both declared appropriate setters and getters.

Writing the controller

The goal of a controller is to manage the flows of the application. An incoming request is analyzed by the MVC framework before being dispatched to the controller. The MVC framework parses the request’s URL to find a match with the URL patterns which are managed by the controller’s methods. If a match is found, the appropriate method of the controller is invoked. The method may perform some operations such as querying database, aggregate result ... if it needs to pass some data to the view, it will add the data object to the model. Finally, the method should return a logical name of view will be rendered. The MVC framework uses the resolver to locate the corresponding JSP file, mixes the data passed in the model with the JSP tags to produce the HTML response which can be rendered by a web browser.
Back to our application, there are two flows that we are going to implement:

  • Access to the login screen: when the user requests the application’s default URL (/), he will be presented with the login form.
  • Submit the login form: when the user submits the login form, the controller will grasp the login and password and redirect him to a result page. If the password is letmein, the result page will show a message “Welcome <user_name>!”, otherwise a message “You are unauthorized to access!” will be shown.


Create a new Java class, MainController.java with the following code:



Java Code: The controller class
package com.spring.study;

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

@Controller
public class MainController {
   
    @RequestMapping(value = "/")
    public String home(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        return "login";
    }
   
    @RequestMapping(value = "/handleLogin", method = RequestMethod.POST)
    public String handleLogin(@ModelAttribute("user") User user, Model model) {
        String message = "";
        if (user.getPassword().equals("letmein")) {
            message = "Welcome " + user.getLogin() + " !";
        } else {
            message = "You are unauthorized to access!";
        }
        model.addAttribute("message", message);
        return "result";
    }
}


We use the annotation @Controller to tell the framework that this class is a MVC controller and the incoming requests should be dispatched to the controller’s method if URL pattern is matched.
The controller class contains two methods to implement the two flows you have talked about, home and handleLogin. The annotation @RequestMapping indicates that the method is capable of handling a request that has URL pattern matches the string specified in the value attribute.

The home method is annotated with @RequestMapping(value = "/") which means that it handles the default URL such as http://localhost/MyApp/. Let’s look at the body of the method, we creates a new instance of User class and put it as an attribute of the model with a key named “user”:

Java Code:
        
        User user = new User();
        model.addAttribute("user", user);
this User object will be available to the view which is specified by the statement:

Java Code:
        return "login";
According to the resolver we have configured, the framework will pick up a corresponding JSP page, llogin.jsp under WEB-INF/jsp and generate HTML output to the browser.

The method handleLogin is annotated with:

Java Code:
    @RequestMapping(value = "/handleLogin", method = RequestMethod.POST)
This means that it handles the URL /handleLogin with POST method. We will create a form which submits to this URL, from the login.jsp page. The code in the body of this method will be explained when we are writing the JSP pages.

Writing the view

Create a JSP page named login.jsp under WEB-INF/jsp directory with the following content:

XML Code: The JSP page login.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<form:form action="handleLogin" method="post" commandName="user">
    <table border="0" align="center">
        <tr>
            <td>User Name: </td>
            <td><form:input path="login" /></td>
        </tr>
        <tr>
            <td>Password: </td>
            <td><form:password path="password" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Submit"/></td>
        </tr>
    </table>
</form:form>   
</body>
</html>
We declare to use Spring’s tag library by the directive:

XML Code:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
A form is implemented by the Spring’s form tag:

XML Code:
<form:form action="handleLogin" method="post" commandName="user">
You can realize that the form’s action is pointing to the URL which is handled by the controller’s method, handleLogin. The method is POST, obviously. The form tag has a new attribute, commandName. This attribute specifies the name of an object in the model, the User object. Remember the home method of the controller that adds a User object to the model? Its attributes are mapped to the form’s fields:

XML Code:
<form:input path="login" /> And:
<form:password path="password" />
So the value of the commandName should match an object’s name in the model which is passed by the controller to the view (this JSP page).
The login form is quite simple with two text fields, one for login name, one for password, and a submit button.

Upon submitting the form, the method handleLogin of the controller will be invoked. This method has been declared as follow:

Java Code:
    public String handleLogin(@ModelAttribute("user") User user, Model model)
The annotation @ModelAttribute("user") User user means that an object in the model, the user object is available to the method. We can use this object to access the values of the form’s fields passed along with the request. The Model model is the model object that we can access its objects or add new objects to it.

The method checks that if user’s password is “letmein” then to build a welcome message:

Java Code:
        if (user.getPassword().equals("letmein")) {
            message = "Welcome " + user.getLogin() + " !";
        }
Otherwise, a warning message is built:

Java Code:
        } else {
            message = "You are unauthorized to access!";
        }
Then the message object is added to the model:

Java Code:
        model.addAttribute("message", message);
Finally the method returns a logical view name:

Java Code:
        return "result";
This means that we have to create another JSP page, result.jsp. The content of this JSP page is quite simple:

XML Code: The JSP page result.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<html>
<head>
<title>Login Result</title>
</head>
<body>
    <center>
        <h1><c:out value="${message}"></c:out></h1>
    </center>
</body>
</html>
We declare to use JSP standard tag library by the directive:

XML Code:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Because we use <c:out/> tag to display the value of the object message which is passed from the controller to the model:

XML Code:
<c:out value="${message}"></c:out>
This JSP page is displayed after user submits the login form.


Running the application

Make sure you have Tomcat 6.0 installed on your computer. In Eclipse, open the Servers view window, right click and select New -> Server:

Name:  new server 1a.PNG
Views: 14343
Size:  6.7 KB
Figure: Add a new server in the Servers view

In the New Server dialog, expand the branch Apache, then select Tomcat v6.0 Server:

Name:  new server 2.PNG
Views: 14395
Size:  22.8 KB
Figure: Select a version of Tomcat server

Click Next, you are asked to select Tomcat’s installation directory:

Name:  new server 3a.PNG
Views: 14384
Size:  42.5 KB
Figure: Select Tomcat's installation directory

Click Browse to select the directory where Tomcat installed on your computer. Click OK. Click Next, the screen Add and Remove Projects will ask you to select an available project to be configured:

Name:  screenshot5.PNG
Views: 14345
Size:  21.3 KB
Figure: The Add and Remove Projects dialog

Select HelloSpring from the left, then click Add. Finally click Finish, your server is now configured.

Name:  screenshot6.PNG
Views: 14321
Size:  7.4 KB
Figure: The project HelloSpring is added to Tomcat server

Right click on the server’s name, select Start to start the server, you will see some logging information outputted in the Console View.

Open a new browser window, type the following URL into the address bar:
http://localhost:9898/HelloSpring/

Notice the port of your Tomcat maybe different. The login form will be displayed, as following:

Name:  screenshot7.PNG
Views: 14360
Size:  66.4 KB
Figure: The login screen

Type “Admin” into the User Name field, and “letmein” into the Password field, and click Submit, the following message should be displayed:

Name:  screenshot8.PNG
Views: 14409
Size:  67.2 KB
Figure: The welcome message if login succeeded

If you type the password other than “letmein”, you should see the following screen:

Name:  screenshot9.PNG
Views: 14350
Size:  67.6 KB
Figure: The error message if login failed

Great! That does exactly what we are expecting. And you got a Spring MVC application up and running.
AAJ likes this.

Submit "Building your first Spring 3 MVC application using Eclipse" to Facebook Submit "Building your first Spring 3 MVC application using Eclipse" to Digg Submit "Building your first Spring 3 MVC application using Eclipse" to del.icio.us Submit "Building your first Spring 3 MVC application using Eclipse" to StumbleUpon Submit "Building your first Spring 3 MVC application using Eclipse" to Google

Tags: eclipse, mvc, spring 3 Add / Edit Tags
Categories
MVC , Spring 3 , Eclipse

Comments