Saturday, February 16, 2013

A Beginner's Guide for Learning Java Spring MVC Framework - Part 3


In our last article, we have learned some Java Spring MVC basic concepts and investigated the Java source code from the sample project. Also, two exercises are provided at the end of the article to extend the functionality of the sample project. In this article, we will continue to extend the sample project to include unit test code for the Java code we have written. Unit testing is very important in software development. It allows developers to check the quality of the code. It is a good practice to write unit tests for all the Java classes created in your project. In the test-driven development(TDD) process, developers are even required to write unit tests before writing the actual code.

Unit Test with JUnit


JUnit is widely used as a testing framework for Java code. It is integrated into our implementation IDE, Spring Suite Tools. The sample project also already contains test folders src/test/java and src/test/resources. We can just add files under them. The following steps show how to add a unit test for the controller class HomeController.

Right click the package name under src/test/java, and choose New -> JUnit Test Case. In the pop-up dialog, fill in the test name as HomeControllerTest, check all the method stubs you like to create and select the class under test by click Browse... button. The class we are going to test is com.mycompany.hello.HomeController.



Check the home method to test in the next dialog, and click Finish button.



A skeleton code is automatically generated. In this test file, every method has an annotation before it (a new feature for JUnit 4.x). You can read the following JUnit tutorial  for the detailed information about these annotations. Since our code is pretty simple, we only need to implement the “real” test method, testHome.

In this test method, we first create the HomeController object, then create two objects for the input parameters, locale and model. The model object is an instance of ExtendedModelMap which implements the Model interface. After we call the home method, we test whether the return string is “home” and the model object is modified correctly.

public void testHome() {
            HomeController controller = new HomeController();
            Locale locale = new Locale("en");
            ExtendedModelMap model = new ExtendedModelMap();
            String view = controller.home(locale, model);
            assertEquals(view, "home");
            assertEquals(model.size(), 1);
            assertTrue(model.containsAttribute("serverTime"));
      }

After the code is finished, right click HoemControllerTest.java and select Run As -> JUnit Test. Spring Tool Suite will then run the unit test and show the test results.

Code Coverage

We use unit tests to check the quality of the code. How can we check the quality of the unit test code? One way to measure the quality of the unit tests is to use code coverage, which measures the percentage of the source code that is tested by the unit tests.

We use EclEmma as our code coverage tool. To install EclEmma, open the Help -> Eclipse Marketplace… dialog, and search for EclEmma. In the search results, select EclEmma and then follow the instructions to install it. After the installation, open Window->Customize Perspective… dialog and enable Java Code Coverage in the Command Groups Availability tab.



After we finish adding the code coverage into our IDE, a new code coverage button  is added in the main toolbar.

EclEmma uses a metric called branch coverage to measure the coverage percentage. In general, in order to have a 100% branch coverage on a function, your unit test code must test every statement of the function, and both true and false cases of every conditional statement, such as if, switch, while, ? operator.

To run the unit test with code coverage, you can simply click the “Coverage Run” toolbar button. After the unit test is finished, you can see the results in the “Coverage” tab under the source code editor window. Also the results are intuitively shown in the source code editor window by highlighting code lines with different colors. In default, EclEmma uses green, red, and yellow to indicate different coverage states: fully covered, not covered, and partially covered respectively. A partially covered code line is normally due to the missing of branches. For example, only the true case of an if statement is tested, but the false case is not tested.



Exercise
Write unit tests for the code you added in the previous exercises. Try to get 100% code coverage for your unit test code.

Saturday, February 9, 2013

A Beginner's Guide for Learning Java Spring MVC Framework - Part 2


In a previous article, we have learned to set up a development environment to write Java Spring code, and created our first Spring MVC project. In this article, we will first introduce some basic concepts of Java Spring MVC, and take a detailed look at the sample project.

1. Java Spring MVC Basics
In Java Spring MVC framework, MVC stands for Model, View, and Control. A model can be treated as an object that contains a bunch of data. The data can come from anywhere, such as a back-end database, web server configurations, etc. A view can be treated as an object that reflects the model. For example, we can use a Java Server Page (JSP) to generate an HTML page based on the model. A controller works between the model and view. It can put necessary data into the model and then select a view to reflect the model. A typical work flow of Java Spring MVC is described as follows:
  • Receive a web request a client, and resolve the request's information, such as relative path (e.g. /help), request method (e.g. GET).
  • Use a servlet called DispatcherServlet to find a controller that is responsible for handling this request based on the resolved information.
  • The controller prepares the model, and then tells Java Spring MVC which view should be used to reflect the model.
  • Find the view to render the response based on the model and send back the response to the client.
There are many other technical terms for Java Spring MVC and the general Java Spring framework. A good place to learn these terms is the Wikipedia page for Java Spring and Spring Framework Reference Documentation. As a beginner, you don't need to learn more details about these terms. You can just think Java Spring MVC is a magic box. All you need to do is to write a controller and a view together working with a model for each web request URL, and Java Spring MVC will handle all the rest stuff.

2. An Overview of the Sample Project.
There are four important files in this sample projects: web.xml, servlet-context.xml, HomeController.java, and home.jsp.






web.xml

This file is called Web Application Deployment Descriptor. It provides configuration information to the web server to run your web application. For example, in the sample project, the web.xml defines a servlet with name appServlet (in the <servlet> tag), whose detailed information is defined in the file servlet-contex.xml. Also it tells the web server that appServlet should be invoked for the request on the root URL (in the <servlet-mapping> tag).

<servlet>
   <servlet-name>appServlet</servlet-name>
   <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
   </servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml
      </param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
   <servlet-name>appServlet</servlet-name>
   <url-pattern>/</url-pattern>
</servlet-mapping>



servlet-context.xml

This file provides detailed information of appServlet defined in the web.xml. In the sample project, it has a Java bean object which is used to resolve the view names selected by controllers. If a controller return a view name, it will put the prefix string before the view name and put the suffix after the view name to make a string that indicate the complete path of the view file. For example, if a controller returns a view name “home”, it will resolve it to “/WEB-INF/views/home.jsp”.

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

  <beans:property name="prefix" value="/WEB-INF/views/" />
  <beans:property name="suffix" value=".jsp" />
</beans:bean>

HomeController.java

This file contains a controller class called HomeController. This file can be treated as a template to write Java Spring MVC controller classes. It uses an important technology called Spring Annotation. An annotation can be put before a class or method to describe properties of the class or method. It is started with the character @, e.g. @Controller, @RequestMapping, etc.

There are two annotations in this file. Before the class definition, there is an annotation @Controller. This annotation defines that this class is a Controller class. Before the home function, there is an annotation @RequestMapping(value = "/", method = RequestMethod.GET). This annotation defines that the home method is responsible for handling the HTTP GET request of the root “/” URL.

The home method has two input parameters, locale and model. You can put more parameters in this method if you need them. Please read Spring Framework Reference on what kind of parameters you can put in the handler method.

The home method uses a logger to log the locale information and put the current date into the model, then returns the view name “home”. From the configuration in the servlet-context.xml, Java Spring MVC will resolve the view to the file “/WEB-INF/views/home.jsp. The method can also return other types of object. Please read Spring Framework Reference for the possible return types.

This is another “magic” of Java Spring MVC. You can put a bunch of input parameters in the handler method, and return different types of objects. Java Spring MVC can resolve them “magically” when the method is called.

@Controller

public class HomeController {
     
      private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
     
      /**
       * Simply selects the home view to render by returning its name.
       */
      @RequestMapping(value = "/", method = RequestMethod.GET)
      public String home(Locale locale, Model model) {
            logger.info("Welcome home! The client locale is {}.", locale);
           
            Date date = new Date();
            DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
           
            String formattedDate = dateFormat.format(date);
           
            model.addAttribute("serverTime", formattedDate );
           
            return "home";
      }
}

home.jsp

This file is the view part of the sample project. It contains a variable ${serverTime}, which is defined in the model passed from the controller.


3. Exercises

Now you should see that how easy it is to implement in Java Spring MVC framework. Let's do some exercises to expand the basic sample projects. I will leave them to you to start writing your own Java Spring MVC code.

3.1. Extend HomeController method to check the client's locale information, and in the home view,   display "Your language is English" if the locale language is English, or "Your language is not English" otherwise .
3.2. Create a new controller which can handle GET request on the /browserinfo url, In the view of the controller, it displays the client's web browser information, such as browser type (IE, Firefox, Chrome, Safari, etc) and version.



Friday, February 1, 2013

A Beginner's Guide for Learning Java Spring MVC Framework

This tutorial is for the programmers who have little knowledge of Java Spring MVC framework and want to learn this technology from scratch. It shows you how to write Java Spring code from the very beginning.

1.Installation
First, you need to install necessary software to start writing code in Java Spring. You need an IDE to write Java code, a JDK to build your Java code, and a web server to run your code. Also you need a database if your code have database operations. Since Java is a cross platform programming language, you can work under different platforms. In the following, we are using Windows as our development environment.

1.1. JDK
Get the latest Java Platform (JDK) from Oracle (http://www.oracle.com/technetwork/java/javase/downloads/index.html) and install it. After the installation, set JAVA_HOME system environment variable to the JDK installation path.

1.2. Web server (Apache Tomcat)
We use Apache Tomcat as the web server to run our Java Spring code. You can get the latest Apache Tomcat from Apache (http://tomcat.apache.org/) and extract it to a folder. To have a smoke test on the web server, go to the bin folder of the Apache Tomcat installation folder and run startup.bat. Then open a web browser and test the web address http://localhost:8080 to see if you can see the homepage.

1.3. IDE (Spring Tool Suite)
Get the latest Spring Tool Suites from SpringSource (http://www.springsource.org/sts) and install it. The first time you run the Spring Tool Suite, it will ask you to select a workspace. You can input a folder as your workspace and set this folder as the default workspace. In the welcome screen, click Open Dashboard button, and you can start using this nice IDE.


1.4. Database
We can first start development without a database. We will discuss database options in the future articles.

2. Add Apache Tomcat server to Spring Tool Suite
You can run your Java Spring code directly on the web server in the Spring Tool Suite. To achieve that, you first need to add the web server into Spring Tool Suite.

  • Right click Servers, and select New -> Others in the context menu. In the pop-up dialog, choose Server and click Next button.
  • Choose the Tomcat server name that matches installed version of our web server, e.g. Apache -> Tomcat v7.0 Server, and click Next button.
  • Input the Tomcat installation directory, e.g. C:\apache-tomcat-7.0.35, and click Next button.
  • In the resources dialog, you can select the project you want to run on the server. Since we don't have any project in the workspace currently, you can click Finish button to finish the process.
  • Expand the Servers category in the Package Explorer tab, you can see that there is a new server, Tomcat v7.0 Server at localhost-config, added under this category. Also the Apache Tomcat server is listed in the Servers tab.

3. Run a sample Spring MVC project in Spring Tool Suite
Spring Tool Suite provides a template Spring MVC project for programmers to start with. To open the template project, go to File -> New -> Spring Template Project, and select Spring MVC Project in the pop-up dialog.
In the Project Settings dialog, input the project name and the top-level package name, and click Finish button.


A new project is created and shown in the Package Explorer tab. This template project was configured to build upon JRE 6. If you have a newer version of JRE installed, like what we have with JRE 7, there will be a build error (Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core”) and warning (Build path specifies execution environment JavaSE-1.6...) after the project is automatically built.


To fix this problem, right click the project name, and choose the Properties. In the properties dialog, select Java Build Path. In Libraries tab, remove JRE System Library [JavaSE-1.6]. Then click Add Library... button and add JRE System Library. See the following figure on what the project’s Java Build Path should be.



To run the project, right click the project name, Select Run As -> Run on Server. In the Run On Server dialog, choose the Tomcat server we created previously.


After you click Finish button, you now have a Java Spring MVC Hello World application running on your Tomcat web server!



In default, the Hello World application is deployed into the Tomcat web server under the project folder, i.e. $ProjectFolder\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps. You can right click the Tomcat server name under Servers tab, and select Browse Deployment Location...  to see the deployment directory.


To deploy the whole web application into our installed Tomcat server, we need to first export the web application into a WAR file, and then deploy the WAR file into the Tomcat server.
  • Right click the Hello project name in the Package Explorer tab, and select Export...
  • In the Export dialog, choose web -> WAR file, and click Next button



  • Input the web project name and destination (put the file into the webapps folder of the Tomcat installation folder) . You can also check the Optimize for Apache Tomcat v 7.0 option.

  •  Restart the Tomcat web server and the WAR file should be automatically deployed into the Hello folder. You can visit http://localhost:8080/Hello/ to test the deployment.



4. Summary
In this tutorial, we set up an implementation environment for Java Spring and run a sample Java Spring MVC project on the implementation environment. In the next tutorial, we will introduce some basic concepts of Java Spring MVC framework by analyzing this Hello World sample project and make some changes on the project.