Ayumilove Develop a Spring Framework MVC Application using NetBeans, GlassFish and MySQL (Step by Step) Dummies Guide to Spring MVC (Chapter 1/6)


Developing a Spring Framework MVC application step-by-step using NetBeans and GlassFish
Authors Thomas Risberg, Rick Evans, Portia Tung

Modified by Ayumilove for the 3 Open Source Softwares below:
NetBeans 6.7 (IDE – Integrated Development Environment to develop web applications and software)
GlassFish (Application Server – Consists of Web Container, JavaBean Container)
MySQL (RDBMS – Relational Database Management System)

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Prerequisite software
The following prerequisite software and environment setup is assumed.
You should also be reasonably comfortable using the following technologies.
* Java SDK 1.5/1.6
* GlassFish V2 UR1 (comes with NetBeans 6.7)
* Spring Web MVC Framework (comes with NetBeans 6.7)
* NetBeans 6.7

Chapter 1 Spring Web MVC Complete Web Application ‘AyumiloveSpring1’ can be downloaded here.

Appendix A. References


Original version of this tutorial based on Eclipse and Tomcat.
Modified version of this tutorial based on Netbeans and GlassFish.
NetBeans IDE 6.7 Download
Spring Framework Download

Chapter 1 Spring Web MVC Tutorial for Newbies
1.1 Create the Netbeans Spring Project
1.2. Create ‘index.jsp’
1.3. Deploy the application to GlassFish
1.4. Check the application works
1.5. Download the Spring Framework
1.6. Modify ‘web.xml’ in the ‘WEB-INF’ directory
1.7. Spring libraries
1.8. Create the Controller
1.9. Write a test for the Controller
1.10. Create the View
1.11. Compile and deploy the application
1.12. Try out the application
1.13. Summary

Summary of Chapter 1
Chapter 1 of this tutorial walks you through on how to setup a simple spring web mvc application, which consists of a front controller (also known as dispatcher servlet), a view (hello.jsp) and a controller (HelloController.java). It also guides on how to create a testing class (HelloControllerTests.java) in order to check the logic behind HelloController whether it works smoothly or does not produce expected results.

The application we are building
The application we will be building from scratch over the course of this tutorial is a very basic inventory management system. This inventory management system is severely constrained in terms of scope; find below a use case diagram illustrating the simple use cases that we will be implementing. The reason why the application is so constrained is so that you can concentrate on the specifics of Spring Web MVC and Spring, and not the finer details of inventory management.

Chapter 1. Basic Application and Environment Setup

1.1. Create the NetBeans Spring project

Run Netbeans 6.7 -> File -> New Project (Ctrl+Shift+N)
01 Netbeans New Project

Create a new Web project from File -> New Project and click Next.
02 Netbeans Web Application Project

Enter the project name as “AyumiloveSpring1” and Enter the project location to be saved.
Tick “Use Dedicated Folder for Storing Libraries” and “Set as Main Project”. Click Next
03 Netbeans Project Name Location

Select Server: “GlassFish v2.1” (If its not listed, click ADD button and add GlassFish v2.1)
Select Java EE 5 and Click Next.
04 Netbeans Server and Settings

Tick “Spring Web MVC 2.5”. Set dispatcher name as “springapp”, and include JSTL. Click Finish.
05 Netbeans Framework Spring Web MVC 2.5

Find below a screen shot of what your project directory structure must look like after following the above instructions. (The screen shot shows the project directory structure inside the NetBeans IDE: you do not need to use the NetBeans IDE to complete this tutorial successfully, but using NetBeans will make it much easier to follow along.)
06 Netbeans Initial Project Files

1.2. Create ‘index.jsp’


Since we are creating a web application, let’s start by updating the basic JSP page ‘index.jsp’ which got created in the ‘web’ directory as part of project creation. The ‘index.jsp’ is the entry point for our application.
‘AyumiloveSpring1/web/index.jsp’: (File Directory)
‘AyumiloveSpring1/Web Pages/index.jsp’: (Project Directory)

<html>
  <head><title>Example :: Ayumilove Spring Application</title></head>
  <body>
    <h1>Example - Spring Application</h1>
    <p>Hello Ayumilove World.</p>
  </body>
</html>

Ayumilove Note:
If you use Netbeans 6.7 Spring Web MVC 2.5 (in-built), the index.jsp will be located within:
AyumiloveSpring1/web/WEB-INF/jsp/index.jsp (move this file to same directory as redirect.jsp)
Delete redirect.jsp (Below is the pic of the index.jsp initial location)
07 Ayumilove Note Chapter 1

Just to have a complete web application, let’s update the ‘web.xml’ located in ‘WEB-INF’ directory inside the ‘web’ directory with the content shown below.
‘AyumiloveSpring1/web/WEB-INF/web.xml’: (File directory)
‘AyumiloveSpring1/Web Pages/WEB-INF/web.xml’: (Project directory)

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
    <welcome-file-list>
	<welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
    
</web-app>

Click the Files tab in the project to view the web directory and its contents.
web.xml and index.jsp files are located in this directory.
08 Netbeans Files Tab Web.xml

1.3. Deploy the application to GlassFish


Ayumilove Note: Before we deploy, we need to start our GlassFish (Web Server)
09 Netbeans GlassFish Start Server

Notice a green triangle icon beside the fish icon? This means it has started/active/enabled.
Your web applications will be deployed in the web application folder.
To undeploy the deployed applications, expand that folder and right-click on it, select undeploy.
10 Netbeans GlassFish Server Enabled

Right click the project and click Build. It builds the web application.
11 Netbeans Clean and Build

After the Clean and Build or Build, right click the project and click Deploy.
12 Netbeans Deploy Web Application

If you receive error message Failed Build (as the diagram shown below). It’s due to Deploy On Save.
13 Netbeans Build Failed Deploy On Save

The solution is to disable Deploy On Save. This is done by right-clicking the project (AyumiloveSpring1) and click Properties. Under the Run category, untick Deploy On Save and Click OK.
14 Netbeans Project Properties Disable Deploy on Save

1.4. Check the application works


The server is already started when the application was deployed in the previous step.
You can now open up a browser and navigate to the starting page of our application at the following URL: http://localhost:8080/AyumiloveSpring1/index.jsp
15 Netbeans Hello Ayumilove World

1.5. Download the Spring Framework


Note: This task is handled by the Spring Netbeans Module. So, plugin users can ignore this section. When you create a web project in Netbeans 6.7 and using Spring Web MVC Framework, this is automatically done for you. You do not need to download any Spring Framework.

For those who are not using Netbeans 6.7 (using other IDE), you will need to download.
If you have not already downloaded the Spring Framework, now is the time to do so. We are currently using the ‘Spring Framework 2.5’ release that can be downloaded from http://www.springframework.org/download. Unzip this file somewhere as we are going to use several files from this download later on.

This completes the setup of the environment that is necessary, and now we can start actually developing our Spring Framework MVC application.

1.6. Modify ‘web.xml’ in the ‘WEB-INF’ directory

Go to the ‘springapp/web/WEB-INF’ directory.
Modify the minimal ‘web.xml’ file that we updated earlier.
We will define a DispatcherServlet (also known as a ‘Front Controller’ (Crupi et al)).

It is going to control where all our requests are routed based on information we will enter at a later point. This servlet definition also has an attendant entry that maps to the URL patterns that we will be using. We have decided to let any URL with an ‘.htm’ extension be routed to the ‘springapp’ servlet (the DispatcherServlet).

‘AyumiloveSpring1/web/WEB-INF/web.xml’: (File Directory)
‘AyumiloveSpring1/Web Pages/WEB-INF/web.xml’: (Project Directory)

Before

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <welcome-file-list>
	<welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>

</web-app>

After

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <welcome-file-list>
	<welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
	<servlet-name>springapp</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
	<servlet-name>springapp</servlet-name>
	<url-pattern>*.htm</url-pattern>
    </servlet-mapping>

</web-app>

Ayumilove Note:
Any visitor request (the website visitor) who request any page on your website that has an extension of .htm will be handled by the Front Controller (Dispatcher Servlet). For example: Visitor A types inside the Address Box” http://my_website.com/abc.htm. The request for abc.htm page is received by the Front Controller (springapp-servlet.xml). The Front Controller will then figure out to whom this request should be handled. In the next lessons, we will be learning about Handlers (those .java class that handles those user request).

The servlet-name, servlet-class, load-on-starup. Those are to define the Front Controller Servlet.
This front controller (springapp-servlet.xml) will be the middleman to handle request.
It grabs request from the supplier (user) and send to the handlers, and vice versa.
(When handlers complete its task, it returns back the webpage to Front Controller,
The Front Controller will then pass the page back to the user. (user finally views the page! abc.htm)

Next, update the file ‘springapp-servlet.xml’ located in the ‘springapp/web/WEB-INF’ directory.
This file contains the bean definitions (plain old Java objects) used by the DispatcherServlet.
It is the WebApplicationContext where all web-related components go.

The name of this file is determined by the value of the element from the ‘web.xml’,
with ‘-servlet’ appended to it (hence ‘springapp-servlet.xml’).
This is the standard naming convention used with Spring’s Web MVC framework.
Now, add a bean entry named ‘/hello.htm’ and specify the class as springapp.web.HelloController.

This defines the controller that our application will be using to service a request with the corresponding URL mapping of ‘/hello.htm’. The Spring Web MVC framework uses an implementation class of the interface called HandlerMapping to define the mapping between a request URL and the object that is going to handle that request (the handler).

Unlike the DispatcherServlet, the HelloController is responsible for handling a request for a particular page of the website and is also known as a ‘Page Controller’ (Fowler). The default HandlerMapping that the DispatcherServlet uses is the BeanNameUrlHandlerMapping; this class will use the bean name to map to the URL in the request so that the DispatcherServlet knows which controller must be invoked for handling different URLs.

‘AyumiloveSpring1/web/WEB-INF/springapp-servlet.xml’: (File Directory)
‘AyumiloveSpring1/Web Pages/WEB-INF/springapp-servlet.xml’: (Project Directory)

Before

<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    
    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    
</beans>

After

<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    
    <bean name="/hello.htm" class="springapp.web.HelloController"/>

</beans>

1.7. Spring libraries

The spring libraries are copied when the project is first created.
These jars will be deployed to the server and they are also used during the build process.

16 Netbeans Spring Libraries Jar

1.8. Create the Controller

Create your Controller class – we are naming it HelloController,
and it is defined in the ‘springapp.web’ package.
Right click ‘Source Packages’ and create a Java class ‘HelloController.java’
with the package name ‘springapp.web’.

17 Netbeans Creating New Folder Packages

18 Netbeans HelloController Java Class

‘AyumiloveSpring1/src/java/springapp/web/HelloController.java’: (File Directory)
‘AyumiloveSpring1/src/java/springapp/web/HelloController.java’: (Project Directory)

Before

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package springapp.web;

/**
 *
 * @author Ayumi
 */
public class HelloController {

}

After

package springapp.web;
 
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
import java.io.IOException;
 
public class HelloController implements Controller {
 
    protected final Log logger = LogFactory.getLog(getClass());
 
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        logger.info("Returning hello view");
 
        return new ModelAndView("hello.jsp");
    }
 
}

This is a very basic Controller implementation.
We will be expanding this later on as well as extending
some of the base controller implementations provided by Spring.

In Spring Web MVC, the Controller handles the request and returns a ModelAndView –
in this case, one named ‘hello.jsp’ which is also the name of the JSP file we will create next.

The model that this class returns is actually resolved via a ViewResolver.
Since we have not explicitly defined a ViewResolver,
we are going to be given a default one by Spring that simply forwards
to a URL matching the name of the view specified. We will modify this later on.
We have also specified a logger so we can verify that we actually got into the handler.

1.9. Write a test for the Controller

Testing is a vital part of software development.
It is also a core practice in Agile development.

We have found that the best time to write tests is during development, not after,
so even though our controller doesn’t contain complex logic, we’re going to write a test.
This will allow us to make changes to it in the future with confidence.

Let’s use the ‘Test Packages’ for this.
This is where all our tests will go in a package structure
that will mirror the source tree in ‘springapp/src/java’.

Create a test class called ‘HelloControllerTests’
and make it extend JUnit’s test class TestCase.
It is a unit test that verifies the view name returned by handleRequest()
matches the name of the view we expect: ‘hello.jsp’.

19 Netbeans HelloControllerTests

‘AyumiloveSpring1/test/spring/web/HelloControllerTests.java’: (File Directory)
‘AyumiloveSpring1/Test Packages/spring.web/HelloControllerTests.java’: (Project Directory)

Before

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package spring.web;

/**
 *
 * @author Ayumi
 */
public class HelloControllerTests {

}

After

package springapp.web;
 
import org.springframework.web.servlet.ModelAndView;
 
import springapp.web.HelloController;
 
import junit.framework.TestCase;
 
public class HelloControllerTests extends TestCase {
 
    public void testHandleRequestView() throws Exception{       
        HelloController controller = new HelloController();
        ModelAndView modelAndView = controller.handleRequest(null, null);         
        assertEquals("hello.jsp", modelAndView.getViewName());
    }
}

We can use the IDE to run the JUnit test (and all the tests we’re going to write).
Make sure the junit jars are present in the ‘Test Libraries’ location of the project.
Now run the JUnit by right clicking the testcase and select ‘Run File’ and the test should pass.

20 Netbeans Test Libraries JUnit

Another of the best practices of Agile development is Continuous Integration.
It’s a good idea to ensure your tests are run with every build (ideally as automated project builds)
so that you know your application logic is behaving as expected as the code evolves.

1.10. Create the View

Now it is time to create our first view.
As we mentioned earlier, we are forwarding to a JSP page named ‘hello.jsp’.
To begin with, we’ll put it in the ‘web’ directory.

‘AyumiloveSpring1/web/hello.jsp’: (File Directory)
‘AyumiloveSpring1/Web Pages/hello.jsp’: (Project Directory)

Before

<%-- 
    Document   : hello
    Author     : Ayumi
--%>

<%@page contentType="text/html" 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>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

After

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head><title>Hello :: Spring Application</title></head>
  <body>
    <h1>Hello - Spring Application</h1>
    <p>Greetings.</p>
  </body>
</html>

1.11. Compile and deploy the application

Refer section 1.3 for building and deploying the web application from an IDE.

1.12. Try out the application

Let’s try this new version of the application.
Open a browser and browse to http://localhost:8080/AyumiloveSpring1/hello.htm

21 Netbeans Hello Spring Application

1.13. Summary

Let’s take quick look at the parts of our application that we have created so far.
Part 1: index.jsp
An introduction page, ‘index.jsp’, the welcome page of the application.
It was used to test our setup was correct.
We will later change this to actually provide a link into our application.
Part 2: springapp-servlet.xml
A DispatcherServlet (front controller) with a corresponding ‘springapp-servlet.xml’ configuration file.
Part 3: Hello Controller
A page controller, HelloController, with limited functionality – it just returns a ModelAndView.
We currently have an empty model and will be providing a full model later on.
Part 4: HelloControllerTests.java
A unit test class for the page controller, HelloControllerTests,
to verify the name of the view is the one we expect.
Part 5: Hello.jsp
A view, ‘hello.jsp’, that again is extremely basic.
The good news is the whole setup works and we are now ready to add more functionality.

Find below a screen shot of what your project directory structure must look like after following the above instructions.
22 Netbeans Chapter 1 Spring MVC Summary

Advertisements

About ayumilove

I am Ayumilove, if you see some impersonators its not me.

2 responses to “Ayumilove Develop a Spring Framework MVC Application using NetBeans, GlassFish and MySQL (Step by Step) Dummies Guide to Spring MVC (Chapter 1/6)”

  1. cheap pearl jewelry,cheap body jewelry, free shipping says :

    Hi there, just became aware of your weblog thru Google, and located that it is really informative. I?m gonna watch out for brussels. I?ll be grateful if you happen to proceed this in future. Lots of other folks might be benefited from your writing. Cheers!

  2. Replica Clothing says :

    I do trust all of the ideas you have presented to your post. They’re really convincing and will definitely work. Nonetheless, the posts are too quick for starters. May just you please extend them a bit from subsequent time? Thank you for the post.

%d bloggers like this: