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.



1 comment:

  1. The link you provided contains all the topics you should learn from the very beginning. In my point of view, you may need spend full time on the study if you want to be proficient with Java in 6 weeks. You don't need any knowledge of C. You can treat Java as your first programming language.
    There are many other ways to learn Java. You can search free learning resources in the Internet, buy some introduction book about Java, or take a Java programming course in your local college.

    ReplyDelete