Saying Hello to Java EE

To develop a scalable, distributed, well-presented, complex, and multi-layered enterprise application is complicated. The development becomes even worse if the developer is not well aware of the software development fundamentals. Instead of looking at a bigger scenario, if we cut it down into parts and later combine them, it becomes easy for understanding as well as for developing. Each technology has some basics which we cannot overlook. Rather, if we overlook them, it will be the biggest mistake; the same is applicable to Java EE. In this article by TejaswiniMandar Jog, author of the book Learning Modular Java Programming, we are going to explore the following:

  • Java EE technologies
  • Why servlet and JSP?
  • Introduction to Spring MVC
  • Creating a sample application through Spring MVC

(For more resources related to this topic, see here.)

The enterprise as an application

To withstand the high, competitive, and daily increasing requirements, it's becoming more and more difficult nowadays to develop an enterprise application. The difficulty is due to more than one kind of service, requirement of application to be robust and should support concurrency, security, and many more. Along with these things, enterprise applications should provide an easy user interface but good look and feel for different users.

In the last article, we discussed enterprise applications. The discussion was more over understanding the terminology or the aspect. Let's now discuss it in terms of development, and what developers look forward to:

  • The very first thing even before starting the development is: what we are we developing and why? Yes, as a developer we need to understand the requirements or the expectations from the application. Developers have to develop an application which will meet the requirements.
  • The application should be efficient and with high quality so as to sustain in the market.
  • The application code should be reliable and bug-free to avoid runtime problems.
  • No application is perfect; it's a continuous process to update it for new demands. Develop an application in such a way that it is easy to update.
  • To meet high expectations, developers write code which becomes complicated to understand as well as to change. Each one of us wants to have a new and different product, different from what is on the market. To achieve this, designers make an over-clumsy design which is not easy to change in the future. Try to avoid over-complexity both in design and business logic.
  • When development starts, developers look forward to providing a solution, but they have to give thought to what they are developing and how the code will be organized in terms of easy maintenance and future extension. Yes, we are thinking about modules which are doing a defined task and those which are less dependent. Try to write a module which will be loosely coupled and highly cohesive.
  • Today we are using enterprise applications through different browsers, such as Internet Explorer, Mozilla, or Firefox. We are even using mobile browsers for the same task. This demands an application that has been developed to withstand the number of platforms and browsers.

Going through all this discussion, many technologies come to mind. We will go through one such platform which covers the maximum of the above requirements: the Java Enterprise Edition (Java EE) platform. Let's dive in and explore it!!

The Java EE platform

Sun Microsystems released the Java EE platform in 2000, which was formerly known as the J2EE specification. It defines the standards for developing component-based enterprise applications easily. The concrete implementation is provided by application servers such as Weblogic and GlassFish, and servlet containers such as Tomcat. Today we have Java EE 8 on the market.

Features of the Java EE platform

The following are the various features of the Java EE platform:

  • Platform independency: Different types of information which the user needs in day-to-day life is spread all over the network on a wide range of platforms. Java EE is well adapted to support, and use this widely spread multiple format information on different platforms easily.
  • Modularity: The development of enterprise applications is complex and needs to be well organized. The complexity of the application can be reduced by dividing it into different, small modules which perform individual tasks, which allows for easy maintenance and testing. They can be organized in separate layers or tiers. These modules interact with each other to perform a business logic.
  • Reusability: Enterprise applications need frequent updates to match up client requirements. Inheritance, the fundamental aspect of an object-oriented approach, offers reusability of the components with the help of functions. Java EE offers modularity which can be used individually whenever required.
  • Scalability: To meet the demands of the growing market, the enterprise application should keep on providing new functionalities to the users. In order to provide these new functionalities, the developers have to change the application. They may add new modules or make changes in already existing ones. Java EE offers well-managed modules which make scalability easy.

The technologies used in Java EE are as follows:

  • Java servlet
  • Java Server Pages
  • Enterprise Java Bean
  • Java Messaging API
  • XML
  • Java Transaction API
  • Java Mail
  • Web Services

The world of dotcoms

In the 1990s, many people started using computers for a number of reasons. For personal use, it was really good. When it came to enterprise use, it was helpful to speed up the work. But one main drawback was; how to share files, data or information? The computers were in a network but if someone wanted to access the data from any computer then they had to access it personally. Sometimes, they had to learn the programs on that computer, which is not only very time-consuming but also unending.

What if we can use the existing network to share the data remotely?? It was a thought put forward by a British computer scientist, Sir Tim Berners-Lee. He thought of a way to share the data through the network by exploring an emerging technology called hypertext. In October 1990, Tim wrote three technologies to fulfill sharing using Hyper Text Markup Language (HTML), Uniform Resource Identifier (URI), and Hyper Text Transfer Protocol (HTTP):

  • HTML is a computer language which is used in website creation. Hypertext facilitates clicking on a link to navigate on the Internet. Markups are HTML tags defining what to do with the text they contain.
  • URIs defines a resource by location or name of resource, or both. URIs generally refer to a text document or images.
  • HTTP is the set of rules for transferring the files on the Web. HTTP runs on the top of TCP/IP.

He also wrote the first web page browser (World Wide Webapp) and the first web server (HTTP). The web server is where the application is hosted. This opened the doors to the new amazing world of the "dotcom". This was just the beginning and many more technologies have been added to make the Web more realistic. Using HTTP and HTML, people were able to browse files and get content from remote servers. A little bit of user interaction or dynamicity was only possible through JavaScript. People were using the Web but were not satisfied; they needed something more. Something which was able to generate output in a totally dynamic way, maybe displaying the data which had been obtained from the data store. Something which can manipulate user input and accordingly display the results on the browser.

Java developed one technology: Common Gateway Interface (CGI). As CGI was a small Java program, it was capable of manipulating the data at the server side and producing the result. When any user made a request, the server forward the edit to CGI, which was an external program. We got an output but with two drawbacks:

  • Each time the CGI script was called, a new process was created. As we were thinking of a huge number of hits to the server, the CGI became a performance hazard.
  • Being an external script, CGI was not capable of taking advantage of server abilities.

To add dynamic content which can overcome the above drawbacks and replace CGI, the servletwas developed by Sun in June 1997.

Servlet – the dynamicity

Servlets are Java programs that generate dynamic output which will be displayed in the browser and hosted on the server. These servers are normally called servlet containers or web servers. These containers are responsible for managing the lifecycle of the servlets and they can take advantage of the capabilities of servers. A single instance of a servlet handles multiple requests through multithreading. This enhances the performance of the application. Let's discuss servlets in depth to understand them better.

The servlet is capable of handling the request (input) from the user and generates the response (output) in HTML dynamically. To create a servlet, we have to write a class which will be extended from GenericServlet or HttpServlet. These classes have service() as a method, to handle request and response. The server manages the lifecycle of a servlet as follows:

The servlet will be loaded on arrival of a request by the servers.

The instance will be created.

The init() will be invoked to do the initialization.

The preceding steps will be performed only once in the life cycle of the servlet unless the servlet has not been destroyed.

After initialization, the thread will be created separately for each request by the server, and request and response objects will be passed to the servlet thread.

The server will call the service() function.

The service() function will generate a dynamic page and bind it to the HttpResponse object.

Once the response is sent back to the user, the thread will be deallocated.

From the preceding steps, it is pretty clear that the servlet is responsible for:

  • Reading the user input
  • Manipulating the received input
  • Generating the response

A good developer always keeps a rule of thumb in mind that a module should not have more than one responsibility, but here the servlet is doing much more. So this has addressed the first problem in testing the code, maybe we will find a solution for this. But the second issue is about response generation. We cannot neglect a very significant problem in writing well-designed code to have a nice look and feel for the page from the servlet. That means a programmer has to know or adapt designing skills as well, but, why should a servlet be responsible for presentation?

The basic thought of taking presentation out of the servlet leads to Java Server Page (JSP). JSP solves the issue of using highly designed HTML pages. JSP provides the facility of using all HTML tags as well as writing logical code using Java. The designers can create well-designed pages using HTML, where programmers can add code using scriptlet, expression, declaration, or directives. Even standard actions like useBean can be used to take advantage of Java Beans. These JSP's now get transformed, compiled into the servlet by the servers.

Now we have three components:

  • Controller, which handles request and response
  • Model, which holds data acquired from handling business logic
  • View, which does the presentation

Combining these three we have come across a design pattern—Model-View-Controller (MVC). Using MVC design patterns, we are trying to write modules which have a clear separation of work. These modules can be upgradable for future enhancement. These modules can be easily tested as they are less dependent on other modules. The discussion of MVC is incomplete without knowing two architectural flavors of it:

  • MVC I architecture
  • MVC II architecture

MVC I architecture

In this model, the web application development is page-centric around JSP pages. In MVC I, JSP performs the functionalities of handling a request and response and manipulating the input, as well as producing the output alone. In such web applications, we find a number of JSP pages, each one of them performing different functionalities. MVC I architecture is good for small web applications where less complexity and maintaining the flow is easy. The JSP performs the dual task of business logic and presentation together, which makes it unsuitable for enterprise applications.


MVC I architecture

MVC II architecture

In MVC II, a more powerful model has been put forward to give a solution to enterprise applications with a clear separation of work. It comprises two components: one is the controller and other the view, as compared to MVC I where view and controller is JSP (view). The servlets are responsible for maintaining the flow (the controller) and JSP to present the data (the view). In MVC II, it's easy for developers to develop business logic- the modules which are reusable. MVC II is more flexible due to responsibility separation.


MVC II architecture

The practical aspect

We have traveled a long way. So, instead of moving ahead, let's first develop a web application to accept data from the user and display that using MVC II architecture. We need to perform the following steps:

Create a dynamic web application using the name Ch02_HelloJavaEE.

Find the servlet-api.jar file from your tomcat/lib folder. Add servlet-api.jar to the lib folder.

Create index.jsp containing the form which will accept data from the user.

Create a servlet with the name HelloWorldServlet in the com.packt.ch02.servlets package.

Declare the method doGet(HttpServletRequestreq,HttpServletResponsers) to perform the following task:

Read the request data using the HttpServletRequest object.

Set the MIME type.

Get an object of PrintWriter.

Perform the business logic.

Bind the result to the session, application or request scope.

Create the view with name hello.jsp under the folder jsps.

Configure the servlet in deployment descriptor (DD) for the URL pattern.

Use expression language or Java Tag Library to display the model in the JSP page.

Let's develop the code.

The filesystem for the project is shown in the following screenshot:

We have created a web application and added the JARs. Let's now add index.jsp to accept the data from the user:

<form action="HelloWorldServlet">

<tr>

<td>NAME:</td>

<td><input type="text" name="name"></td>

</tr>

<tr>

<td></td>

<td><input type="submit" value="ENTER"></td>

</tr>

</form>

When the user submits the form, the request will be sent to the URL HelloWorldServlet.

Let's create the HelloWorldServlet which will get invoked for the above URL, which will have doGet(). Create a model with the name message, which we will display in the view. It is time to forward the request with the help of the RequestDispatcher object. It will be done as follows:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // TODO Auto-generated method stub

    //read the request parameter

    String name=request.getParameter("name");

    //get the writer

PrintWriter writer=response.getWriter();

 

    //set the MIME type

response.setContentType("text/html");

 

    // create a model and set it to the scope of request

request.setAttribute("message","Hello "+name +" From JAVA Enterprise");

RequestDispatcher dispatcher=request.getRequestDispatcher("jsps/hello.jsp");

dispatcher.forward(request, response);

 

  }

Now create the page hello.jsp under the folder jsps to display the model message as follows:

<h2>${message }</h2>

The final step is to configure the servlet which we just have created in DD. The configuration is made for the URL HelloWorldServlet as follows:

<servlet>

<servlet-name>HelloWorldServlet</servlet-name>

<servlet-class>com.packt.ch02.servlets.HelloWorldServlet

</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorldServlet</servlet-name>

<url-pattern>/HelloWorldServlet</url-pattern></servlet-mapping>

Let's deploy the application to check the output:


Displaying the home page for a J2EE application

The following screenshot shows the output when a name is entered by the user:


Showing the output when a name is entered by the user

After developing the above application, we now have a sound knowledge of how web development happens, how to manage the flow, and how navigation happens. We can observe one more thing: that whether it's searching data, adding data, or any other kind of operation, there are certain steps which are common, as follows:

  • Reading the request data
  • Binding this data to a domain object in terms of model data
  • Sending the response

We need to perform one or more of the above steps as per the business requirement. Obviously, by only performing the above steps, we will not be able to achieve the end effect but there is no alternative. Let's discuss an example.

We want to manage our contact list. We want to have the facilities for adding a new contact, updating a contact, searching one or many contacts, and deleting a contact. The required data will be taken from the user by asking them to fill in a form. Then the data will be persisted in the database.

Here, for example, we just want to insert the record in the database. We have to start the coding from reading request data, binding it to an object and then our business operation. The programmers have to unnecessarily repeat these steps. Can't they get rid of them? Is it possible to automate this process?? This is the perfect time to discuss frameworks.

What is a framework?

A framework is software which gives generalized solutions to common tasks which occur in application development. It provides a platform which can be used by the developers to build up their application elegantly.

Advantages of frameworks

The advantages of using frameworks are as follows:

  • Faster development
  • Easy binding of request data to a domain object
  • Predefined solutions
  • Validations framework

In December 1996, Sun Microsystems published a specification for JavaBean. This specification was about the rules, using which developers can develop reusable, less complex Java components. These POJO classes are now going to be used as a basis for developing a lightweight, less complex, flexible framework: the Spring framework. This framework is from the thoughts of Rod Johnson in February 2003. The Spring framework consists of seven modules:


Spring modules

Though Spring consists of several modules, the developer doesn't have to be always dependent on the framework. They can use any module as per the requirement. It's not even compulsory to develop the code which has been dependent upon Spring API. It is called a non-intrusive framework. Spring works on the basis of dependency injection (DI), which makes it easy for integration. Each class which the developer develops has some dependencies. Take the example of JDBC: to obtain a connection, the developer needs to provide URL, username, and password values. Obtaining the connection is dependent on these values so we can call them dependencies, and injection of these dependencies in objects is called DI. This makes the emerging spring framework the top choice for the middle tier or business tier in enterprise applications.

Spring MVC

The spring MVC module is a choice when we look forward for developing web applications. The spring MVC helps to simplify development to develop a robust application. This module can also be used to leave common concerns such as reading request data, data binding to domain object, server-side validation and page rendering to the framework and will concentrate on business logic processes.

That's what, as a developer we were looking for. The spring MVC can be integrated with technologies such as Velocity, Freemarker, Excel, and PDF. They can even take advantage of other services such as aspect-oriented programming for cross-cutting technologies, transaction management, and security provided by the framework.

The components

Let's first try to understand the flow of normal web applications in view of the Spring framework so that it will be easy to discuss the component and all other details:

On hitting the URL, the web page will be displayed in the browser.

The user will fill in the form and submit it.

The front controller intercepts the request.

The front controller tries to find the Spring MVC controller and pass the request to it.

Business logic will be executed and the generated result is bound to the ModelAndView.

The ModelAndView will be sent back to the front controller.

The front controller, with the help of ViewResolver, will discover the view, bind the data and send it to the browser.


Spring MVC

The front controller

As already seen in servlet JSP to maintain each flow of the application the developer will develop the servlet and data model from servlet will be forwarded to JSP using attributes. There is no single servlet to maintain the application flow completely. This drawback has been overcome in Spring MVC as it depends on the front controller design pattern.

In the front controller design pattern, there will be a single entry point to the application. Whatever URLs are hit by the client, it will be handled by a single piece of the code and then it will delegate the request to the other objects in the application.

In Spring MVC, the DispatcherServlet acts as front controller. DispatcherServlet takes the decision about which Spring MVC controller the request will be delegated to. In the case of a single Spring MVC controller in the application, the decision is quite easy. But we know in enterprise applications, there are going to be multiple Spring MVC controllers. Here, the front controller needs help to find the correct Spring MVC controller. The helping hand is the configuration file, where the information to discover the Spring MVC controller is configured using handler mapping. Once the Spring MVC controller is found, the front controller will delegate the request to it.

Spring MVC controller

All processes, such as the actual business logic, decision making or manipulation of data, happen in the Spring MVC controller. Once this module completes the operation, it will send the view and the model encapsulated in the object normally in the form of ModelAndView to the front controller. The front controller will further resolve the location of the view. The module which helps front controller to obtain the view information is ViewResolver.

ModelAndView

The object which holds information about the model and view is called as ModelAndView. The model represents the piece of information used by the view for display in the browser of different formats.

ViewResolver

The Spring MVC controller returns ModelAndView to the front controller. The ViewResolver interface helps to map the logical view name to the actual view. In web applications, data can be displayed in a number of formats, from as simple as JSP to complicated formats like JasperReport. Spring provides InternalResourceViewResolver, JspViewResolver, JasperReportsViewResolver, VelocityLayoutViewResolver, and so on, to support different view formats.

The configuration file

DispatcherServlet needs to discover information about the Spring MVC controller, ViewResolver, and many more. All this information is centrally configured in a file named XXX-servlet.xml where XXX is the name of the front controller. Sometimes the beans will be distributed across multiple configuration files. In this case, extra configuration has to be made, which we will see later in this article.

The basic configuration file will be:

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

   http://www.springframework.org/schema/beans    

   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

   http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!—mapping of the controller -->

<!—bean to be configured here for view resolver  - ->

</beans>

The controller configuration file will be named name_of_servlet-servlet.xml. In our project, we will name this HelloWeb-servlet.xml.

Let's do the basics of a web application using Spring MVC to accept the data and display it. We need to perform the following steps:

Create a web application named Ch02_HelloWorld.

Add the required JAR files for Spring (as shown in the following screenshot) and servlets in the lib folder.

Create an index page from where the data can be collected from the user and a request sent to the controller.

Configure the front controller in DD.

Create a SpringMVCcontroller as HelloWorldController.

Add a method for accepting requests in the controller which performs business logic, and sends the view name and model name along with its value to the front controller.

Create an XML file in WEB-INF as Front_Controller_name-servlet.xml and configure SpringMVCcontroller and ViewResolver.

Create a JSP which acts as a view to display the data with the help of Expression Language (EL) and Java Standard Tag Library (JSTL).

Let's create the application.

The filesystem for the project is as follows:

We have already created the dynamic web project Ch02_HelloSpring and added the required JAR files in lib folder. Let's start by creating index.jsp page as:

<form action="hello.htm">

<tr>

<td>NAME:</td>

<td><input type="text" name="name"></td>

</tr>

<tr>

<td></td>

<td><input type="submit" value="ENTER"></td>

</tr>

</form>

 

When we submit the form, the request is sent to the resource which is mapped for the URL hello.htm. Spring MVC follows the front controller design pattern. So all the requests hitting the application will be first attended by the front controller and then it will send it to the respective Spring controllers.

The front controller is mapped in DD as:

<servlet>

<servlet-name>HelloSpring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet

</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloSpring</servlet-name>

<url-pattern>*.htm</url-pattern>

</servlet-mapping>

Now the controller needs help to find the Spring MVC controller. This will be taken care of by the configuration file. This file will have the name XXX-servlet.xml where XXX is replaced by the name of the front controller from DD. Here, in this case HelloSpring-servlet.xml will have the configuration. This file we need to keep in the WEB-INF folder. In the Configuration files section, we saw the structure of the file. In this file, the mapping will be done to find out how the package in which the controllers are kept will be configured. This is done as follows:

<context:component-scan base-package="com.packt.ch02.controllers" />

Now the front controller will find the controller from the package specified as a value of base-package attribute. The front controller will now visit HelloController. This class has to be annotated by @Controller:

@Controller

public class HelloController {

//code here

}

Once the front controller knows what the controller class is, the task of finding the appropriate method starts. This will be done by matching the values of @RequestMapping annotation applied either on the class or on the methods present in the class. In our case, the URL mapping is hello.htm. So the method will be developed as:

@RequestMapping(value="/hello.htm")

publicModelAndViewsayHello(HttpServletRequest request)

  {

    String name=request.getParameter("name");

ModelAndView mv=new ModelAndView();

mv.setViewName("hello");

    String message="Hello "+name +" From Spring";

mv.addObject("message",message);

return mv;

  }

This method will return a ModelAndView object which contains a view name, model name and value for the model. In our code the view name is hello and the model is presented by message. The Front Controller now again uses HelloSpring-servlet.xml for finding the ViewResolver to get the actual name and location of the view. ViewResolver will provide the directory name (location) where the view is placed with a property prefix. The format of the view is given by the property suffix. Using the view name, prefix and suffix, the front controller gets the page. The ViewResolver will bind the model to be used in the view:

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/jsps/" />

<property name="suffix" value=".jsp" />

</bean>

In our case, it will be /WEB-INF/jsps/ as prefix, hello as the name of page, and .jsp is the suffix value. Combining them, we will get /WEB-INF/jsps/hello.jsp, which acts as our view.

The Actual view is written as prefix+view_name from ModelAndView+suffix, for instance:

/WEB-INF/jsps/+hello+.jsp

The data is bounded by the front controller and the view will be able to use it:

<h2>${message}</h2>.

This page is now ready to be rendered by the browser, which will give output in the browser as:

Displaying the home page for a Spring application

Entering the name in the text field (for example, Bob) and submitting the form gives the following output:


Showing an output when a name is entered by the user

Now we understand the working of spring MVC, let's discuss a few more things required in order to develop the Spring MVC controller.

Each class which we want to discover as the controller should be annotated with the @Controller annotation. In this class, there may be number of methods which can be invoked on request. The method which we want to map for URL has to be annotated with the annotation @RequestMapping.

There can be more than one method mapped for the same URL but it will be invoked for different HTTP methods. This can be done as follows:

@RequestMapping(value="/hello.htm",method= RequestMethod.GET)

publicModelAndViewsayHello(HttpServletRequest request)

  {

 

    }

@RequestMapping(value="/hello.htm",method= RequestMethod.POST)

publicModelAndViewsayHello(HttpServletRequest request)

  {

 

   }

These methods normally accept Request as parameter and will return ModelAndView. But the following return types and parameters are also supported.

The following are some of the supported method argument types:

  • HttpServletRequest
  • HttpSession
  • Java.util.Map/ org.springframework.ui.Model/ org.springframework.ui.ModelMap
  • @PathVariable
  • @RequestParam
  • org.springframework.validation.Errors/ org.springframework.validation.BindingResult

The following are some of the supported method return types:

  • ModelAndView
  • Model
  • Map
  • View
  • String
  • void

Sometimes the bean configuration is scattered in more than one file. For example, we can have controller configuration in one file and database, security-related configuration in a separate file. In that case, we have to add extra configuration in DD to load multiple configuration files, as follows:

<servlet>

<servlet-name>HelloSpring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/beans.xml</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>HelloSpring</servlet-name>

<url-pattern>*.htm</url-pattern>

</servlet-mapping>

Summary

In this article, we learned how the application will be single-handedly controlled by the front controller, the dispatcher servlet. The actual work of performing business logic and giving the name of the view, data model back will be done by the Spring MVC controller. The view will be resolved by the front controller with the help of the respective ViewResolver. The view will display the data got from the Spring MVC controller. To understand and explore Spring MVC, we need to understand the web layer, business logic layer and data layer in depth using the basics of Spring MVC discussed in this article.

Resources for Article:

 


Further resources on this subject:


You've been reading an excerpt of:

Learning Modular Java Programming

Explore Title
comments powered by Disqus