Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

To do database programming with Spring Framework following packages/Software are

required:

1. MySQLWorkBench: It is front end Administration tool to manage underlying


MySQL Database
2. MySQL Database: Where tables are created and maintained
3. Jar Files such as commons-dbcp2-2.1.1.jar, commons-pool2-2.4.2.jar, mysql-
connector-java-5.1.37-bin.jar, spring-jdbc-3.2.1.RELEASE.jar which
4. Above jars should be part of current project. For this, Right click on project name
and click on Build Path-> Configure Build Path Click on Libraries Tab and Click
on Add External Jars button and add all jar files to the corresponding package.
5. Assume that following table is created on MySQL database.

6. Following Bean class named Offer.java is created.

1
7. Database information is maintained inside a property file

8. Application context file accesses above property values using property


placeholder for building connection pool within a bean having an id "dataSource"
as shown below:

2
Note: In order for placeholder to work, <context:property-placeholder> tag
should be set.
9. We can execute SELECT, UPDATE, DELETE, INSERT query into database
using either JDBC Template or NamedParameterJdbcTemplate
10. Values from the database can be accessed through a Data Access Object class
as shown below:

3
Container class interacts with above DAO as following:

ClassPathXmlApplicationContext context = new


ClassPathXmlApplicationContext("ch4/xmls/lab1.xml");
OffersDAO offersDao = (OffersDAO)context.getBean("offersDao");
List<Offer> offers = offersDao.getOffers();
System.out.println("Size of List="+offers.size());
for(Offer offer: offers) {
System.out.println(offer);}

4
Using NamedParameterJdbcTemplate

Database values can also be accessed using NamedParameterJdbcTemplate as shown


below:

Corresponding Container code is:


NamedParameters offersDao =
(NamedParameters)context.getBean("namedParameters");
Offer offers = offersDao.getOffers(1);
System.out.println("ID="+offers.getId());
System.out.println("Name="+offers.getName());
System.out.println("Email="+offers.getEmail());

Update/Delete Statement
Update/Delete Statements can also be executed using NamedParameterJdbcTemplate
as shown below:

5
Corresponding Container Code is:
if(offersDao.delete(1))
{
System.out.println("Deleted Successfully");
}
else
{
System.out.println("Record Not Deleted....");
}
Insert Statement

Insert statement can be executed by adding code to our existing DAO


class(NamedParameters.java) as shown below:

public boolean insert(Offer offer)


{
BeanPropertySqlParameterSource params=new
BeanPropertySqlParameterSource(offer);
return jdbc.update("insert into offers values(:id,:name,:email,:text)", params)==1;
}

Corresponding Container code is:

Offer offer1 =new Offer(1, "Gunjan","[email protected]","gbohara");


Offer offer2 =new Offer(2, "Harvajan","[email protected]","hbohara");
offersDao.insert(offer1);
offersDao.insert(offer2);

UPDATE Statement

UPDATE statement can also be executed in slightly different ways as shown below:

Corresponding Container Code is:

6
Batch Statement:

We can execute batch statement using following code:

public int[] insertbatch(List<Offer> offers)


{
SqlParameterSource [] params=SqlParameterSourceUtils.createBatch(offers.toArray());
return jdbc.batchUpdate("insert into offers values(:id,:name,:email,:text)", params);

Corresponding Container code is shown below:

List<Offer> offerlist=new ArrayList<Offer>();


offerlist.add(new Offer(3, "Gunjan","[email protected]","gbohara"));
offerlist.add(new Offer(4, "Gunjan","[email protected]","gbohara"));
int results[]=offersDao.insertbatch(offerlist);
for (int val:results)
{
System.out.println("Inserted "+ val +" Row...");
}

Using Transaction in Spring

Following code fragment needs to be kept on Application Context:


<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

Following code needs to be kept on DAO class


@Transactional
public int[] insertbatch(List<Offer> offers)
{
SqlParameterSource []
params=SqlParameterSourceUtils.createBatch(offers.toArray());
return jdbc.batchUpdate("insert into offers values(:id,:name,:email,:text)",
params);

In above example:either all of the insert statements on the list will be executed or none
because of @Transactional annotation.

7
Java Spring MVC

Spring MVC

Spring MVC framework provides MVC ready components to provide loose coupling
among User Interface, Database and Business logic. It provides a standard way of
organizing JSP and servlet codes.

 Model is represented using POJO classes and it encapsulates application data.


 View is used to display model data as an output in web browser.
 Controller is responsible for facilitating the communication between model and
view. It processes user request and build appropriate model and passes it to
view for display purpose.

First Non MVC Web App

Eclipse needs to have Web Tool Platform(WTP) in order for MVC to work. To install
WTP, Go to Help-> Install new Software and Select All Available Sites; wait for a
moment and tick on Web, XML,Java EE and OSGi Enterprise Development and include
Eclipse Java EE Developer Tools and JST Server Adapters Extensions.

Create a Project:Click on File->New->Other->Web-> Dynamic Web Project( You will


have to select web server to run the project during this stage)

Right Click on Project Name and Create a new JSP page. Including some text in
<body> element. Right click on JSP File and Click Run As and Run JSP App.

Note:

i)A web server such as Tomcat needs to be installed before running this APP and do
not forget to set Dynamic Web Module version 2.5 while creating the project.

8
Spring MVC Application

1Adding DispatcherServlet

DispatcherServlet:

All requests are processed through DispatcherServltet.

All web request will got to DS and DS will pass the request to appropriate controller
which will then decide which view to display using what kind of datas.

To add dispatcher servlet to your project, Right Click Project->New->Other->Web-


>Servlet->Tick on Use an existing class and Servlet->Click Browse and select
DispatcherServlet

DispatcherServlet is configured in web application deployment descriptor(web.xml)

[ Note: You should have added jar files as mentioned below in note section]

After adding DipatcherServlet to your project, then if you open up your web.xml file, then
there you can find <servlet> and <servletmapping> tag been automatically created
there. We are going to change the <display-name> property and <servlet-name>
property both equals to "offers". <url-pattern> to "/" and add <load-on-startup> property
to equal to 1 as we want the servlet to get started automatically as soon as the project
starts up.

The web.xml file is shown below:

9
The URL request that the DispatcherServlet handles is mapped in the web.xml file. In
above example, inside web.xml file we have defined DispatcherServlet named offers
and we have defined mapping for it as well. <servlet-mapping> tag specifies what URLS
will be handled by which DispatcherServlet. In our case, all HTTP requests that starts
with / will be handled by offers DispatcherServlet.

The URL request that the DispatcherServlet handles is mapped in the web.xml file. In
above example, inside web.xml file we have defined DispatcherServlet named offers
and we have defined mapping for it as well. <servlet-mapping> tag specifies what URLS
will be handled by which DispatcherServlet. In our case, all HTTP requests that starts
with / will be handled by offers DispatcherServlet.

Web Application Context

WebApplicationContext is integrated with DispatcherServlet and manages various


entities like Controller, ViewResolver, HandlerMapping etc which are essential parts of
WebApplicationContext, which is an extension of a plain ApplicationContext with some
extra features necessary for web applications.

DispatcherServlet inspects WebApplicationContext to find all bean definitions that maps


incoming requests to controllers. Some of these beans are default and some of them
you need to provide.

Upon Initialization of offers DispatcherServlet, Spring Framework will load application


context from Web Application Context file named offers-servlet.xml in our case.

Changing Default Name and Location of Web Application Context File

Inside <WEB-INF>, we need to add another servlet xml file whose name should start
with the same name that you give to dispatcher servlet i.e <servlet name-servlet.xml>
So, we are going to name this xml file as offers-servlet.xml from where all beans are
loaded.

By Default, Web Application Context file name must have to start with <servletname-
servlet.xml> and is stored on WebContent/WEB-INF directory. However, we can
customize the file name and location by adding following code inside <web.xml> file :

10
In above example, the default name of Web Application Context File is changed to
mycontext.xml and it is shifted in new location /Web-Inf/xmls folder. Previously, its name
was offers-servlet.xml and was stored on /WEB-INF folder.

Adding a Controller

DispatcherServlet will forward requests to Controller and Controller will select one of the
views and provide it to DispatcherServlet for the display.

Let us create a normal Java file named as OffersController which will play the role of
controller within a package named ch2.lab1.spring.web.controllers[ Right Click Project-
>New-Class] as shown below:

In above code, @Controller Annotation denotes that the class OffersController is going
to play the role of controller. @RequestMapping annotation indicates that all request
goes through the /test folder.

showHome method just returns the name of the view, that we want to display.

We need not have to define OffersController in offers-servlet.xml file that we had


already created because we have used <component-base-scan> which will scan all files
located on the specified folder and finds a file that has @Controller annotation and
confirms that this file is a Controller. @RequestMapping("/test") indicates handler
method that will handle all the URL request that starts with ./test.

Note: The above web app can be executed using URL:


http://localhost:8080/mvctest11/test

However, if we had used @ReequestMapping("/"), then we should have to type


following

http://localhost:8080/mvctest11/

11
Adding View Resolver

ViewResolver is responsible for mapping logical view names to actual views such as JP
page, Velocity Template or XSL Stylesheets to apply to the contents of model.

DispatcherServlet dispatches the request to base URL to OffersController which will


then return logical view named "home" . ViewResolver will capture that name and
translate it into actual view to display i.e. jsp file in our case.

Right Click on Web-inf directory and create a sub folder named jsps and move home.jsp
file into this directory.

Now, Dispatcher Servlet should be provided ViewResolver to work with. We are going
to use InternalViewResolver.class which is located inside
org.springframework.web.servlet.view package. This view resolver taks is to resolve
view name "home" to a jsp file. So, we need to add this view resolver class as our view
resolver in DispatcherServlet context file(offers-servlet.xml) so that DispatcherServlet
will know how to resolve the name "home" into appropriate jsp file.

A logical view named home is delegated to a view implementation located at /WEB-


INF/jsps/home.jsp

Note:

i) Do not forget to add following Jars by right clicking the Project->Build Path->
ConfigureBuild Bath-> Add External jars and add following Jars

ii) Moreover, we need to tell eclipse to find all above jars. For that, Right Click Project->
Properties-Deployment Assembly-> Add->Java Build Path Entries->Next->Finish.

iii) Clean your project if errors come by clicking on Project->Clean Project

iv) Make sure that the version of JRE used by Tomcat and Eclipse are same. To set
JRE version do not forget, set JRE_HOME environment variable.

12
v) Right Click Prject->Run As->Run on Server->Manually Define a new Server->Add-
>Select Right version of JRE from below-> Click on Finish and use this server if there
are not any web server you have previously created. Moreover, you can click configure
run time environments to edit configuration of pre-defined server.

vi) Do not add any jars on Tomcat lib directory, it might create various painful errors
only.

vii) Make sure that while executing project on Right Clicking->Run As->Run Server-
>Click on Next and make sure that there is only one project in Configured section; and
then click on Finish button.

Spring MVC WorkFlow Steps:

1. DispatcherServlet receives request based on the url-pattern mentioned inside


servlet mapping tag in web.xml Application context file. Control is first passed to
web.xml
2. As we have defined dispatcher servlet name as "offers" and hence control goes
through offers-servlet.xml file.
3. Based on HandlerMapping(map of URL and Controller), DispatcherServlet
delegates the responsibility to the matching controller controller.
4. Handler method of the matching controller is responsible for processing the
delegated request and returns ModeAndView to the DispatcherServlet.
5. DispatcherServlet resolves the logical view name to actual view using
ViewResolver and passes the Model object to the view.
6. Response is prepared using the Model and actual view. Then the control goes
back to the DispatcherServlet
7. DispatcherServlet returns the response which gets rendered in the browser.

Note:

i) <component-base> will cause control to go through Controller, which returns


view name which is resolved into concrete view file named hello.jsp[ located
in web-inf/jsps folder by View Resolver(InternalViewResolver).
ii) <component-base> instructs spring to scan the package and its children to
detect and auto configure components. For instance, we can annotate a class
with @Controller annotation and spring will automatically configure it as a
controller class. Due to this auto scanning feature, there is no need to
configure controller classes in xml files.

13
Basic Layout of Spring MVC Web Application

The processing flow of Spring MVC from receiving the request till the response is
returned is shown in the following diagram.

1. DispatcherServlet receives the request.


2. DispatcherServlet dispatches the task of selecting an appropriate controller to
HandlerMapping. HandlerMapping selects the controller which is mapped to the
incoming request URL and returns the (selected Handler) and Controller to
DispatcherServlet.
3. DispatcherServlet dispatches the task of executing of business logic of Controller
to HandlerAdapter.
4. HandlerAdapter calls the business logic process of Controller.
5. Controller executes the business logic, sets the processing result in Model and
returns the logical name of view to HandlerAdapter.
6. DispatcherServlet dispatches the task of resolving the View corresponding to the
View name to ViewResolver. ViewResolver returns the View mapped to View
name.
7. DispatcherServlet dispatches the rendering process to returned View.
8. View renders Model data and returns the response.

14
Handler Mappings:

This is responsible for determining the appropriate controller to dispatch a request to.
Which controller should be called is decided by URL request. After HandlerMapping
returns a handler or controller, Controller returns ModelAndView and the ViewResolver
provides a concrete view instance after which Spring lets the view to do its job i.e.
render a response to the client.
Handler Mapping will determine path of execution. The path of execution comprises of
zero or more interceptors and one handler.
All URLs matching <url-pattern> defined in web.xml will be routed to DispatcherServlet
and pickedup by the HandlerMapping. HandlerMapping will determine the path of
execution. The execution path comprises of one handler and one or more interceptors.
The path of execution is most commonly determined by URL of the request.
Note: If after querying all vailable HandlerMapping, a HandlerExecutonChain is still not
found i.e. not matching handler is found, then Spring will inform the client by sending it
HTTP 404 response.

BeanNameUrlHandlerMapping

This maps URL requests coming from client directly to Controller bean names. The
matching bean is then used as the controller for the request. It is the default handler
mapping class and hence whenever DispatcherServlet cannot find any handler mapping
class being define in Spring's application context , DispatcherServlet by default uses
this.

The URL path of a web page is mapped into corresponding Controller using this
mapping. It means when we enter a particular URL, then which particular controller
should handle the corresponding URL request is decided by this mapping. In order for
this to work, we need to do following:

1. Add bean for BeanNameUrlHandlerMapping in <servletname-servlet.xml> i.e.<


offers-servlet>.xml file
2. Add URL mapping entry as shown below:

15
3. Add Corresponding Controller Code as shown below:

In above code, we can find two beans, the first one's name is: helloworld.html and its
class is the HelloWorldController. Hence, BeanNameUrlHandlerMapping will map any
helloworld.html request to this Controller. The second bean's name is hello*.htm and its
class is also the HelloWorldController. Hence, BeanNameUrlHandlerMapping will map
any URL requests that starts with hello( such as helloWorld,helloAll) to the
HelloWorldController.

In above code, whenever user types URL whose name starts with helloworld.html or
starts with hello and ends with html, then such request is forwarded to HelloWorld
controller. HelloWorldController will return ModelAndView object. In model, we have
added data and in view name is "helloworld". Similalry, view name is "helloworld". This
view name is returned by controller and is resolved into /WEB-INF/jsps/helloworld.jsp
file by InternalResourceViewResolver.

16
Similarly, <context:component-scan> will go through specified package name and will
scan all files over there and in our case will also locate OffersController file and as there
is @Controller annotation over there, Spring will determine this as a Controller class. All
the URL request that ends with "/test" is handled by "showHome()" method of
Controller; which will return view file named "/WEB-INF/jsps/home.jsp". All the URL
request that ends with "/abc" is handled by "showPage()" method of Controller; which
will return view file named "/WEB-INF/jsps/secondpage.jsp"

SimpleUrlHandlerMapping

This maps URL to Handler or Controller class using property mappings. The
SimpleUrlHandlerMapping can be declared in two different ways:

1.Method 1:prop key

In this method, property keys are URL patterns and property values are handler IDs or
names.

17
We can put above code in <servletname-servlet.xml> file to map above URL request to
HelloWorldController.

2. Method 2: value

The left side are the URL patterns and the right side are handler IDs or Names
separated by equal symbol "=" whithin <value> element.

CommonPathMapperUrlHandlerMapping

This is a rarely used Handler Mapping in which case, the name of the Url to which the
Controller has to be mapped is specified directly in the Source file of the Controller.
mapping information must be specified in the form of meta-data in the source files inside
the Javadoc comments.

/**

*@@ org.springframework.web.servlet.handler.commonsattributes.

*PathMap('/showAllMails.jsp')

*/

public class ShowAllMailsController{

More than One Handler Mapping

DispatcherServlet consults URL handler mappings in the order of priority. On finding a


match, it delegates control to the appropriate controller.

If same URL refers to or is mapped to two different controllers or handlers, then the
controller with higher priority is server first. The lower the priority value, the higher its
priority is.

Example:

18
In above example, controller having an id of "hlwCntrllr"( i.e. HelloWorldController)
is mapped for URL /welcomepage*. Similarly, as we have used
ControllerClassNameHandlerMapping, /welcomepage* is mapped for
WelComePageController as well. So, /welcomepage* is mapped to two controller.
So, here question might come in your mind "URL request for /welcoepage*" will be
serverd by which particular controller among these two. The answer is
"WelcomePageController" and the reason is its oder property value is 0 whereas the
order property value of hlwContllr is 1. Hence, data.jsp will be displayed not
helloworld.jsp since WelComePageController will return view named "data" and
HelloWorldController will return view named "helloworld".

Note: ControllerClassNameHandlerMapping maps URL request directly to


ControllerName. Hence, in above case, if any page has URL request for
/wecomepage*, then it is mapped automatically to WelComePageController. The
name preceding Controller is taken as part of URL request, which in above case is
welcomepage

HandlerInterceptors

They intercept all incoming HTTP requests. These are useful for adding additional
crosscutting behaviors to your web apps such as security, logging, auditing etc.

Interceptos upon intercepting the request are allowed to execute a piece of code before
and after handler does its work i.e. just before Spring starts rendering a response and
also right after rendering has finished. They allows us to add an additional logic to the
path of execution, without affecting the handler itself.

19
After a request has been pre-processed by the interceptors that were found, Spring
hands over the control to the handler associated with the request. Such a handler will
return ModelAndView object if there does not occur any Exceptions.

If an exception occurs, then Exception Resolvers will determine an appropriate


ModelAndView relevant to the exception. If one of the resolvers results in a
ModelAndView, this will be used to render to a response to the client. For example: if a
database connection could not be established or something similar. If the Exception
Resolver(s) could not come up with appropriate ModelAndView, the exception will be re-
thrown and handled by standard exception-mapping mechanisms defined on servlet
descriptor file(web.xml)

However, if no exception is thrown, Spring will use ModelAndView returned by the


handler to render a response to the client.

20
Handles and Adapters

Handlers are also called as Controllers. Handlers are the actual components
responsible for executing logic in our web application or delegating to another
component executing the logic. Handlers fulfill an incoming request and return
org.springframework.web.servlet.ModelAndView object containing the logical name of
view and the model the view will render. Handlers will either implement Controller or
ThrowawayController interface.

HandlerAdapter

Handlers fulfill an incoming request and return


org.springframework.web.servlet.ModelAndView object containing the logical name of
view and the model, the view will render.

With the help of Handler Adapters (represented by


org.springframework.web.servlet.SimpleControllerHandlerAdapter), which will do the job
of the Forwarding the Request from the Dispatcher to the Controller object), the
Dispatcher Servlet will dispatch the Request to the Controller.

Other types of Handler Adapters are Throwaway Controller HandlerAdapter


(org.springframework.web.servlet.ThrowawayControllerHandlerAdapter) and
SimpleServlet HandlerAdapter
(org.springframework.web.servlet.SimpleServletHandlerAdapter).

The Throwaway Controller HandlerAdapter, for example, carries the Request from the
Dispatcher Servlet to the Throwaway Controller and Simple Servlet Handler Adapter will
carry forward the Request from the Dispatcher Servlet to a Servlet thereby making the
Servlet.service() method to be invoked.

If, for example, you don’t want the default Simple Controller Handler Adapter, then you
have to redefine the Configuration file with the similar kind of information as shown
below:

Even, it is possible to write a Custom Handler Adapter by implementing the


HandlerAdapter interface available in the org.springframework.web.servlet package

21
Adapter is a bridge between two different objects. HandlerAdapter is a bridge between
handler object and dispatcher servlet.

The org.springframework.web.servlet.HandlerAdapter is a system level interface


allowing for low coupling between different request handlers and the DispatcherServlet.
It is used for an easy integration between the DispatcherServlet and third-party
frameworks. This interface and its implementations are normally hidden from the
developer. The DispatcherServlet will also chain multiple adapters if found in the
ApplicationContext and will order them based on the Ordered interface. Using this
interface, the DispatcherServlet can interact with any type of handler, as long as
HandlerAdapter is configured.

Configuring the DispatcherServlet to use this HandlerAdapter is quite easy as the


DispatcherServlet by default looks into the ApplicationContext for all HandlerAdapters. It
will find all adapters by their type. It does not matter what the name of the
HandlerAdapter is, because the DispatcherServlet will look for beans of type
HandlerAdapter.

If our application only uses controller then we can avoid using HandlerAdapters.

ModelAndView and ViewResolvers

Handlers( a.k.a. Contollers) will return ModelAndView Object to the client.


ModelAndView contains both model and view name together. View name contained
inside ModelAndView object is resolved by ViewResolver into concrete view file and
Model data will also be displayed in the view file.

HandlerExecutionChain

When an appropriate URL mapping found for a controller in application context, the
handler mapping returns HandlerExecutionChain which instructs the dispatcher servlet
on how to progress. The HandlerExecutionChain comprises of interceptors and exactly
one handler(or controller), together providing all you need when it comes to access

22
business logic and other supporting services such as authentication, logging and
filtering.

Interceptors

Interceptors are similar to servlet filter. The major difference is that Servlet Fileters are
configured in web.xml file whereas Interceptors are configured in a framework
configuration file. The HandlerInterface is an interface that contains method for
intercepting the execution of handler before its execution(preHandle), after
execution(postHandle) and after rendering the view(afterCompletion).

Interceptors work as following:

1. Call to preHandle(HttpServletRequest, HttpServletResponse, Object) on any


HandlerInterceptor available in the chain of execution. The Object in this case is
the handler from the chain. This call allows to you execute any logic before the
actual handler is allowed to do its job. Here you can check whether or not a user
is allowed to issue this request, for example (this could be done using a
UserRoleAuthorizationInterceptor explained a bit further on). Based on the return
value of the call, Spring will decide to proceed with handling the request. When
returning false, the dispatcher assumes the interceptor has handled the request
itself (for example, when security constraints should prevent a user from issuing
the request). In such a case Spring will immediately stop handling the request,
which means the remaining interceptors, on which preHandle() hasn't been
called, won't be consulted, just as the handler itself won't be consulted. Any
interceptor, however, that did successfully return true before this moment will
receive an afterCompletion() call.
2. Retrieve the handler from the HandlerExecutionChain and start looking for a
HandlerAdapter. All available HandlerAdapters (registered in the
WebApplicationContext or provided by default) will be inspected to see if one of
them supports such a handler (usually determined, based on the class of the
handler). In all except some complex and maybe rare situations there is no need
to worry about the HandlerAdapter, its implementations, and the way they work.
Spring's default behavior works just fine.
3. The next step is the actual execution of the handler. This will execute your actual
business logic, or better; after some initial preparation such as data-binding,
delegate the request to the middle tier. After the execution of the request has
completed, you should prepare a ModelAndView, containing data that a JSP or,
for example, a Velocity template needs to render an HTML page or a PDF
document.
4. Next, all interceptors will be called again, using the
postHandle(HttpServletRequest, HttpServletResponse, Object, ModelAndView)
method. Here you can modify the ModelAndView (maybe add extra attributes to
it or maybe even remove things). This is your last chance to execute logic before
the view gets rendered.

23
5. Next, the view will be resolved and rendered. We will cover view resolving and
rendering later in this chapter.
6. The last step involves calling afterCompletion(HttpServletRequest,
HttpServletResponse, Object, Exception) on any interceptor available. The object
is the handler that took care of the logic involved with this request. If an exception
has occurred during the completion of the request, it will be passed in there as
well.

Interceptors allow us to intercept the HTTP request and do some processing before
handing it over to the controller handler methods. We can create our own interceptor by
either implementing org.springframework.web.servlet.HandlerInterceptor interface or by
overriding abstract class org.springframework.web.servlet.handler.HandlerInterceptorAdapter .

We must have to override following three methods in our App if we want to implement
HandlerInterceptor interface.

1. boolean preHandle(HttpServletRequest request, HttpServletResponse response,


Object handler): This method is used to intercept the request before it’s handed over to
the handler method. This method should return ‘true’ to let Spring know to process the
request through another interceptor or to send it to handler method if there are no
further interceptors.

If this method returns ‘false’ Spring framework assumes that request has been handled
by the interceptor itself and no further processing is needed. We should use response
object to send response to the client request in this case.

The handler object is the object from HandlerExecutionChain.

2. void postHandle(HttpServletRequest request, HttpServletResponse response, Object


handler, ModelAndView modelAndView): This interceptor method is called when
HandlerAdapter has invoked the handler but DispatcherServlet is yet to render the view.
This method can be used to add additional attribute to the ModelAndView object to be
used in the view pages. We can use this interceptor to determine the time taken by
handler method to process the client request.

3. void afterCompletion(HttpServletRequest request, HttpServletResponse response,


Object handler, Exception ex): This is a callback method that is called once the handler
is executed and view is rendered.

Example:

Let us develop an application program that calculates the timings of handler method
execution and total time taken in processing the request including rendering view page.

24
Inside our <servletname-servlet.xml> file; which is mycontext.xml( since we have
modified its name and location already), we need to add following codes

In above code, MyWorldInterceptor will only intercept two URL request namely /hello
and /. The code for MyWorldInterceptor is as shown below:
package ch2.mvc.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyWorldInterceptor implements HandlerInterceptor {


@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {

long startTime = System.currentTimeMillis();


request.setAttribute("startTime", startTime);
System.out.println("Pre-handle");

return true;
}

@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
long startTime = (Long) request.getAttribute("startTime");
request.removeAttribute("startTime");

long endTime = System.currentTimeMillis();


modelAndView.addObject("totalTime", endTime - startTime);

System.out.println("Request Prcessing Time :: " + (endTime - startTime));


System.out.println("Post-handle");
}

@Override
public void afterCompletion(HttpServletRequest request,

25
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("After completion handle");
System.out.println("View Rendered !!");
}
}

Code for MyWorldController is:

package ch2.mvc.controllers;

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

@Controller
public class MyWorldController {

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


public String sayHello() {
return "myworld";
}
}

A handler interceptor is registered to the DefaultAnnotationHandlerMapping bean,


which is charged with applying interceptors to any class marked with

a @Controller annotation.

In Spring 2.5 and better, since handler mapping is handled via @RequestMapping
annotations, the interceptor must be added to the DefaultAnnotationHandlerMapping. In
Spring 2.5 and beyond, the DispatcherServlet enables the
DefaultAnnotationHandlerMapping by default, which looks for @RequestMapping
annotations on @Controllers. However, the DefaultAnnotationHandlerMapping can still
be added to the Spring configuration file and the interceptors added to this handler
mapping as shown below.

<bean id="testInterceptor" class="com.intertech.controllers.TestInterceptor" />

<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">

<property name="interceptors">

<list><ref bean="testInterceptor"/></list>

</property>

</bean>

26
WebContentInterceptor

HandlerInceptors functionality targeted especially for web applications are called


WebContentInterceptor. It provides functionalities such as easy modification of caching
behavior of web application and useful generic tasks such as limiting the
methods(GET,POST) that are supported by web application. We can keep following
codes in our context file i.e. (servletname-servlet.xml) file for this to work:

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>

/welcomepage*=hlwCntrllr
/xyz.html=hlwCntrllr
/*/xyz.html=hlwCntrllr
/xyz*.html=hlwCntrllr
/=hlwCntrllr

</value>
</property>
<property name="interceptors">
<list>
<ref bean="contentInterceptor" />
</list>
</property>
<property name="order" value="1" />

</bean>
<bean id="contentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds"><value>30</value></property>
<property name="supportedMethods"><value>GET</value></property>
</bean>
Following table shows the various properties that can be configured for
WebInterceptor.

27
UserRoleAuthorizationInterceptor

This interceptor is used for simple security solutions only. It does not provide a powerful
security solution. It is used to prevent certain roles from accessing certain URLs.
When user issuing the request is not in a role mentioned in the configuration of the
interceptor, an HttpServletResponse.SC_FORBIDDEN is sent to the client,
corresponding to status code 403. Using error mapping in web.xml file descriptor, we
can direct user to appropriate error page. We can also subclass the interceptor and
override handlerNotAuthorized() method to perform custom actions.

Example:
We can add following highlighted codes in our mycontext.xml file

28
In above code, access to URLS such as /welcomepage, /xyz.html and rest of other 3
URLs requires access from user having manager role only. As zauser defined on
tomcat-users.xml file has manager role, if we log from such user and type
http://localhost:8080/mvctest11/xyz.html, then only we can access corresponding
URL( mvctest11 is project folder name).
If we have <url-pattern> /* </url-pattern> entry on web .xml file as shown below, then all
URLs will be prompted for username and password. However, if we do not have <url-
patten> /* </url-pattern> entry on web.xml file and we have only <url-pattern> /abc.html
</url-pattern> entry on web.xml file, then when we type
http://localhost:8080/mvctest11/abc.html , then only username and password dialog box
displayed. If we type http://localhost:8080/mvctest11/xyz.html then no username and
password dialog box displayed, rather page forbidden error page will be displayed
because s we are trying to access xyz.html without specifying user name and
password that has manager role.
So, if we have <url-pattern> /* </url-pattern> entry on web .xml file, then no matter what
resource we want to access or type any URL after localhost:8080/mvctest11, always
and always username and password dialog box opens up. Opening up the Username
and Password dialog box is done by code written inside web.xml file not mycontext.xml
file. And desired URL access restrictions is made by code written inside mycontext.xml
file.

In above mycontext.xml file, if we define a bean for


ControllerClassNameHandlerMapping as shown below, then it will map all declared
beans with its corresponding Controller. For e.g. if We have a WelComePageController
bean then /welcomepage[i.e. bean name without controller word] will be automatically
mapped into WelComePageController. Similalry, if we have HelloWorldController, then
it will map automatically /helloworld to HelloWorldController. Hence, do not get
surprised even if you do not manually define Handler for /hellworld and /welcomepage
[ as we have defined in SimpleHandlerUrlMapping inside mycontext.xml] and you notice
29
corresponding Controller Code i.e. HelloWorldController and WelComePageController
being called automatically.

Similarly, add following lines of text in web.xml file.

Add following lines of codes in tomcat's conf/tomcat-users.xml directory

In above Application, if we run the project then it will ask to enter username and
password. Note that user "zause" having password "password" is only allowed to enter
inside the system because it has manager role. See, in web.xml file, visit on URLs /*
and /abc.html is only allowed to users which has managers role.

i) Note: Sometimes tomcat's conf/tomcat-users.xml is not loaded on Tomcat's


Running Server file and hence it is recommended to add above codes by
Clicking Server and Tomcat Server version and then tomcat-user.xml fil
ii) If you will not get the result as expected , then it is better recommended to
stop the eclipse, start again, clean the project etc.

30
ViewResolvers

ViewResolvers map logical view names to their concrete View object counterparts.
There are different types of ViewResolvers that Spring provides.

 UrlBasedViewResolvers: There are various URLBasedViewResolvers for e.g.


VelocityViewResolver,
FreeMakerViewResolver,XsltViewResolver,ThymeleafViewResolver etc.
 It provides a direct mapping between URL and logical view name. every controller
return a view after that the view resolver append the prefix and suffix in this view and show the
view as response. This is to be used if the logical view name returned by controller matches the
names of your view resources, without the need of mappings. We register
UrlBasedViewResolvers in your spring web application context file as shown below:

Note:You should have to add jstl.jar file in your project BuildPath and Tomcat
Installation Directory lib path in order for UrlBasedViewResolver to work.
 InternalResourceViewResolver: It is subclass of UrlBasedViewResolver. The
ModelAndView returned from Controller will come to spring application context
xml file( which is mycontext.xml file in our case). The "jsp file name" gets
resolved to appropriate jsp page by InternalResoreceViewResolver into jsp file.
We register InternalResourceViewResolver in our spring web application context
file as shown below:

If we have any view named "helloworld" returned by Controller then Spring will
resolve it in following ways:

Prefix + view name + suffix = /WEB-INF/jsps/helloworld.jsp

Moreover, if we have a view named "admin/home", then it will be resolved


into /WEB-INF/jsps/admin/home.jsp and if we have a view named report/main,
then it will be resolved into /WEB-INF/jsps/report.jsp

31
InternalResourceViewResolver supports internal resources(Recall that the resources
that are put inside the WEB-INF are private resources that are not exposed to URLs
directly we need to tell spring to use InternalResourceViewResolver to use them.The
advantage of using internal resources is to hide direct access of the resources via a
manually entered URL).

UrlBasedViewResolver supports Straightforward url symbol mapping to view.

Important feature of UrlBasedViewResolver : Redirect URLs can be specified via the


“redirect:” prefix in the controller class. E.g.: “redirect:submitPage.do” will redirect to the
given controller URL. This is used for redirecting to a controller URL after processing
form.

Furthermore, forward URLs can be specified via the “forward:” prefix in the controller
class. E.g.: “forward:submitPage.do” will forward to the given URL.It is not supposed to
be used for JSP URLs – use logical view names there.

BeanNameViewResolver

It maps the logical view name to the bean names in the web application context to
resolve the view. When the Dispatcher Servlet requests this resolver to resolve the
view, this resolver will look for bean name in the web application context file that
matches with the logical view name in the given ModelAndView object. We define
BeanNameViewResolver in web application context file as shown below:

XmlViewResolver
It accepts a configuration file written in XML, where the view implementation and
the url of the jsp file are set. We can create XML file named views.xml inside
/Web-INF directory and define URL for jsp file as shown below:

32
We can add code in web application context file as shown below:

The resolver is defined in mvc-dispatcher-servlet.xml. It provides a property to


configure, which is the location property, and there the path of the configuration
file is set.Now, when the Controller returns the "helloworld" view, the
XmlViewResolver will look inside views.xml file to get the view class and the url
of the view that will be mapped to the name "helloworld".

Mapping between bean id and View URL is defined inside XML file. We can
define location of this XML file inside our web application context file by setting its
location property.
When DispatcherServlet requests this resolver to resolve view, this resolver will
look for a bean name in the /WEB-INF/views.xml file that matches the logical
view name in the given ModelAndViewObject.

ResourceBundleViewResolver

URL mapping code is specified inside properties file. Name of the property file is
decalred using basename property property in web application context file. In the
following code, property file name is views.properties because the basename property
value is "views". Example of declaring ResourceBundleViewResolver in Web
Application Context file is shown below:

Corresponding code of views.properties file is shown below:

Note: You have to create a directory named "classes" inside WEB-INF directory
and keep views.properties file inside this classes directory.

33
LogicalView name returned by Conttroller is "helloworld". Hence, this logical view name
"helloworld" is mapped to view name /WEB-INF/myworld.jsp as shown above

The ResourceBundleViewResolver uses bean definitions in a ResourceBundle, that is


specified by the bundle basename. The bundle is typically defined in a properties file,
located in the classpath. Below is the views.properties file. The
ResourceBundleViewResolver is defined in mvc-dispatcher-servlet.xml, and in its
definition the basename property is set to view.properties file. So, in this case, when the
Controller returns the "helloworld" view, the ResourceBundleViewResolver will make
use of the views.properties file to get the view class and the url of the view that will be
mapped to the name "helloworld".

Chaining View Resolvers

In order to set multiple Resolvers together in the same configuration file, you can set the
order property in all definitions, so that the order that they are used will be defined as
shown below. We can turn off this priority feature by writing codes in web.xml file

HandlerExceptionResolvers

When an unknown exception occurs then application server usually displays the entire
exception stack trace to the user in webpage itself. In this case, users have nothing to
do with this stack trace and complain that your application is not user friendly.
Moreover, it can also prove a potential security risk, as you are exposing the internal
method call hierarchy to users. Though a web application’s web.xml can be configured
to display friendly JSP pages in case an HTTP error or class exception occur, Spring
MVC supports a more robust approach to managing views for class exceptions.

In a Spring MVC application, you can register one or more exception resolver beans in
the web application context to resolve uncaught exceptions. These beans have to
implement the HandlerExceptionResolver interface for DispatcherServlet to auto-detect
them. Spring MVC comes with such a simple exception resolver i.e.
SimpleMappingExceptionResolver to map each category of exceptions to a view in a
configurable way.

Let us say, we have an Exception class ExampleException. We want this exception to


be thrown when user browses URL:
http://localhost:8080/exceptionresolverdemo/product , product.jsp should be displayed
and whenever user presses Submit button, we want to show a pre-determined view
page /WEB-INF/jsps/ExceptionPage.jsp in case if product name is less than 5 character
long. If the product length is not less than 5 character long, then we want to display
result.jsp page. Corresponding codes that we have to keep inside controller is shown
below:

34
Corresponding codes of Product and ExampleException classes are shown below:

Let us say, we have another Exception class AuthException. We want this exception to
be thrown when user browses URL:
http://localhost:8080/exceptionresolverdemo/getAllEmployees;then Exception page
/WEB-INF/jsps/authExceptionView.jsp to get printed and whenever user enters
http://localhost:8080/exceptionresolverdemo/checkOther, then in this case NULL
POINTER EXCEPTION should have to be thrown and in this case error.jsp should be
displayed out. Corresponding code that we need to keep inside controller class is:

35
Corresponding code of AuthException.java is:

Codes that we need to keep inside our web application context file is shown below:

36
37
Controllers

Spring provides a variety of controllers that will meet our needs when implementing
important common requirement in web applications. Some of the important controllers
that Spring offers are as following:
 WebContentGenerator
 AbstractController
 UrlFileNameViewController
 ParameterizableViewController
 MultiActionController
 DataBindingController

@ModelAttribute

This annotation can be used as a method argument or before the method declaration.
The primary objective this annotation is to bind the request parameters or form fields to
an model object. The model object can be formed using the request parameter or
already stored in the session object. It has to be noted that @ModelAttribute methods
are invoked before the controller methods with @RequestMapping are invoked because
the model object has to be created before any processing starts inside the controller
methods.

The way Spring processes this annotation is,

1. Before invoking the handler method, Spring invokes all the methods that have
@ModelAttribute annotation. It adds the data returned by these methods to a
temporary Map object. The data from this Map would be added to the final Model
after the execution of the handler method.
2. Then it prepares to invoke the the handler method. To invoke this method, it has
to resolve the arguments. If the method has a parameter with @ModelAttribute,
then it would search in the temporary Map object with the value of
@ModelAttribute. If it finds, then the value from the Map is used for the handler
method parameter.
3. It it doesn't find it in the Map, then it checks if there is a SessionAttributes
annotation applied on the controller with the given value. If the annotation is
present, then the object is retrieved from the session and used for the handler
method parameter. If the session doesn't contain the object despite of the
@SessionAttributes, then an error is raised.
4. If the object is not resolved through Map or @SessionAttribute, then it creates an
instance of the parameter-type and passes it as the handler method parameter.
Therefore, for it to create the instance, the parameter type should be a concrete-
class-type (interfaces or abstract class types would again raise an error).
5. Once the handler is executed, the parameters marked with @ModelAttributes are
added to the Model.

38
Example:

Let us assume we have following POJO class called UserDetails

Above class has corresponding bean definition on our web application context file as shown below:
[since we are auto wiring it]

Let us further assume that we have following Controller class

39
To run above example correctly, we need to type following URL on our web browser

http://localhost:8080/exceptionresolverdemo/modelexample?
user=mukesh&[email protected]

After typing above URL, getAccount() method is called before getMethod() since we
have placed @ModelAttribute annotation before this method name. Since we have
used @RequestParam annotation before String user and String emailId variable,
whatever value we assign to user variable and emailId variable in above URL will be
captured by user and emailID parameter variable of above getAccount() method.
Since we have used AutoWiring by reference for userDetails object and hence it is
automatically created as soon web application context file is loaded and before
getAccount() method is called and hence we can call setUserName and setEmailId
method of UserDetails class through userDetails object. In this way, userDetails object
is constructed and returned and saved into the temporary map object.

After getAccount() method is called, getMethod() method will be called and since we
have used @ModelAttribute annotation just before parameter name and hence the
previously temporarily saved userDetails object will be retrieved from map and will be
assigned here and we can retrieve its user and emailId property and print it in the
console. Moreover, this method will return view named called "example" which in turn
will be resolved into example.jsp by ViewResolver later and example.jsp will be
displayed out at last.

40
Web View Technologies

Model data can be displayed by Views using Variety of technologies e.g. JSP, Veleocity
template, Freemarker, PDF etc. Web View Technologies are used to render views
based on models Controllers return. Controller returns logical view name which in turn is
resolved by View Resolver into Concrete view and Concrete View displays model data.
View Resolver resolves logical view name into different types of view e.g. JSP,
FreeMarker template( depending on view technologies).

Types of View Technologies

 Java Server Pages(JSPs)


 Freemarker
 Velocity Templates
 PDF using iTEXT
 Excel
 XMS and XSLT
 JSTL Templates

Java Server Pages(JSPs)

In order to use JSP views, Controller class should return logical view name, which
should be resolved by view resolver defined on web application context file. For e.g.

In above example, logical view name returned by Controller class will be resolved into
concrete jsp view file located inside /WEB-INF/jsps directory.

FreeMarker

Freemarker is another View Technologies like JSP. This view technology requires a
configure to be set up the templating engine rendering the pages. FreeMarker can be
configured using the FreeMarkerConfigurer.

To use FreeMarker you have to configure it in your web application context file
(viewServlet-servlet.xml) as shown below:

FreeMarker Configuraion in web application context file:

41
You have to specify ViewResolver in your web application context file as shown below:

Corresponding Controller code is:


package ch2.mvc.viewtemplates;

import java.util.ArrayList;
import java.util.List;

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

@Controller
public class UserController {
/**
* Static list of users to simulate Database
*/
private static List<User> userList = new ArrayList<User>();

//Initialize the list with some data for index screen


static {
userList.add(new User("Bill", "Gates"));
userList.add(new User("Steve", "Jobs"));
userList.add(new User("Larry", "Page"));
userList.add(new User("Sergey", "Brin"));
userList.add(new User("Larry", "Ellison"));
}

/**
* Saves the static list of users in model and renders it
* via freemarker template.
*
* @param model
* @return The index view (FTL)
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(@ModelAttribute("model") ModelMap model) {

model.addAttribute("userList", userList);

return "index";
}

/**
* Add a new user into static user lists and display the
* same into FTL via redirect
*

42
* @param user
* @return Redirect to /index page to display user list
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@ModelAttribute("user") User user) {

if (null != user && null != user.getFirstname()


&& null != user.getLastname() && !user.getFirstname().isEmpty()
&& !user.getLastname().isEmpty()) {

synchronized (userList) {
userList.add(user);
}

return "redirect:index.html";
}

Similalry, corresponding Free marker view template(index.ftl) is shown below:

Note: i) You must have to add spring-context-support.jar file in your class path to run
above example:

43
ii)You have to add freemarker.jar file in your Java Build Path and Deployment Assembly
Configurations.

To run above example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: UserController
4. Modal Classes: User
5. View File Location: /WEB-IN/ftl/
6. View File Name: index.ftl
7. Web Application Context File Name: viewServlet-servllet.xml
8. DispatcherServlet Name:viewServlet
9. Application Context File Name: web.xml
10. Web Application Context and Application Context File Location: /WEB-INF

Velocity Template

Velocity Template is another View Technologies like JSP and Freemarker. This view
technology requires a configure to be set up the templating engine rendering the pages.
Velocity Template can be configured using the VelocityTemplateConfigurer.

To use Velocity you have to configure it in your web application context file
(viewServlet-servlet.xml) as shown below:

Velocity Configuraion in web application context file:

You have to specify ViewResolver in your web application context file as shown below:

Corresponding Controller code is:


package ch2.mvc.viewtemplates;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

44
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

@RequestMapping(value="/")
public ModelAndView test(HttpServletResponse response) throws IOException{

User user1 = new User();


user1.setFirstname("Mahesh");
user1.setLastname("Lohia");

User user2 = new User();


user2.setFirstname("Kishan");
user2.setLastname("Dugar");

List<User> lstUser = new ArrayList<User>();


lstUser.add(user1);
lstUser.add(user2);

Map<String, List<User>> model = new HashMap<String, List<User>>();


model.put("users", lstUser);

return new ModelAndView("home", model);


}
}

Similalry, corresponding Velocity view template(home.vm) is shown below:

Note: You have to add velocity-1.7-dep.jar file in your Java Build Path and Deployment
Assembly Configurations.

To run above example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: HomeController
4. Modal Classes: User

45
5. View File Location: /WEB-IN/vtl/
6. View File Name: home.vm
7. Web Application Context File Name: viewServlet-servllet.xml
8. DispatcherServlet Name:viewServlet
9. Application Context File Name: web.xml
10. Web Application Context and Application Context File Location: /WEB-INF

Generating PDF using iTEXT

iTEXT is another View Technologies like JSP,Freemarker and velocity. This view
technology requires itextpdf-5.5.8.jar to be included on class path library( both Java
Build Bath and Deployment Assembly)
We are implementing ResourceBundelViewResolver here where we define location of
views.properties file where we mention the definition of class file which is responsible
for displaying PDF outuput(i.e. PDFBuilder.java)

ResourceBundleViewResolver configuration in web application context file is shown


below:

views.properties file configuration is shown below:

Logical view name returned by Controller class is "mypdf" and this logical view name is
mapped to view class file called PDFBuilder which is responsible for generating PDF
output.
So, the main class responsible for generating PDF output is PDFBulder.java. Controller
will construct model data in ArrayList which in turn is fetched by PDFBuilder class and
PDF document is constructed by it.
PDFBuilder class file extends AbstractITextPdfView. AbstractITextPdfView class
extends AbstractView class.

To run above example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: MainController
4. Modal Classes: None
5. View Class:PDFBuilder
6. View File Location: /WEB-IN/jsps/
7. View File Name: pdfview.jsp
8. Web Application Context File Name: viewServlet-servllet.xml
9. DispatcherServlet Name:viewServlet

46
10. Application Context File Name: web.xml
11. Web Application Context and Application Context File Location: /WEB-INF

Generating Excel Document using Apache POI

Excel is another View Technologies like JSP,Freemarker, velocity and PDF. This view
technology requires poi-3.14-beta1-20151223.jar to be included on class path
library( both Java Build Bath and Deployment Assembly)
We are implementing ResourceBundelViewResolver here where we define location of
views.properties file where we mention the definition of class file which is responsible
for displaying Excel outuput(i.e. ExcelBuilder.java)

ResourceBundleViewResolver configuration in web application context file is shown


below:

views.properties file configuration is shown below:

Logical view name returned by Controller class ( MainController) is "excelView" and this
logical view name is mapped to view class file called ExcelBuilder which is responsible
for generating Excel output.
So, the main class responsible for generating Excel output is ExcelBulder.java.
Controller will construct model data in List which in turn is fetched by ExcelBuilder class
and Excel document is constructed by it.
ExcelBuilder class file extends AbstractExcelView class

To run above example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: MainController
4. Modal Classes: Student
5. View Class:ExcelBuilder
6. View File Location: /WEB-IN/jsps/
7. View File Name: pdfview.jsp
8. Web Application Context File Name: viewServlet-servllet.xml
9. DispatcherServlet Name:viewServlet
10. Application Context File Name: web.xml
11. Web Application Context and Application Context File Location: /WEB-INF

47
Views Based on XML and XSLT

XSL stands for eXtensible Stylesheet Language. XSLT is used to transform XML
documents into another type of document that is recognized by browser e.g.
HTML ,XHTML etc. Normally, XSLT does this transformation by transforming each XML
element into an (X)HTML element.

Let us assume that we have an XML file named citizens.xml as shown below:

Note: We have to create a directory named resources inside our projecr directory(i.e.
viewtemplates) in our case and place this citizens.xml file inside
viewtemplates/resources directory. Sometimes, Spring normally does not find this xml
file and hence you have to create manually resources directory in your project
deployment workspace folder i.e. inside following directory otherwise there might occur
error.
C:\Users\user\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\
wtpwebapps\viewtemplates\resources

48
Next, Let us assume that we have following XSLT template file named xsltview.xsl
which is located inside /WEB-INF/xsl directory which will transform above
customers.xml file into HTML form to be displayed on web browser.

Above file xsltview.xml should be placed inside /WEB-INF/xsl/directory after creating xsl
sub-directory inside WEB-INF directory. /WEB-INF/xsl directory must be included in
Java Build Path and Deployment Assembly. For that, Right Click
Project(viewtemplates)->Build Path-> Configure Build Path->Java Build Path->Add
Class Folder->Locate and Select xsl sub directory that was earlier created inside WEB-
INF directory-> Click Apply. Similalry, You have to add this xls subdirectory to
Deployment Assembly as well.

After this, you need to add following method in your controller file:

49
Similalry, you need to define XSLTViewResolver inside your web application context file
as shown below:

To run above example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: MainController
4. Modal Classes: None
5. View Class:None
6. View File Location: /WEB-IN/jsps/
7. XSL File Location: /viewtemplates/WEB-INF/xsl
8. XML File Location /viewtemplates/resources/
9. XSL File Name:xsltview.xsl
10. XML File Name:citizens.xml
11. View Resolver Used: XSLTViewResolver and InternalResourceViewResolver
12. View File Name: pdfview.jsp
13. Web Application Context File Name: viewServlet-servllet.xml
14. DispatcherServlet Name:viewServlet
15. Application Context File Name: web.xml
16. Web Application Context and Application Context File Location: /WEB-INF

Implementing Custom Views

50
 To implement a custom views, your class must have to inherit AbstractView
class.
 In the following example: we have created a class called AbstractCsvView which
inherits AbstractView class. In this AbstractCsvView class, we have defined an
abstract method named buildCsvDocument, the purpose of this method is to
create an excel file. This method is implemented by another class called
CsvViewImpl which implements body for this method to construct Excel File.
 buildCsvDocument method retrieves header information and data information
from data models created within a controller (MainController) viewCSV method
and thereby create an Excel Document.
 We have used supercsv for creating excel document and hence super-csv-
2.4.0.jar file needs to be included in Java Build Path and Deployment Assembly.

To run example running custom views example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: MainController
4. Modal Classes: Book.java
5. View Class: CsvViewImpl. This class inherits from AbstractCsvView class.
6. View File Location: /WEB-IN/jsps/
7. Properties File Location: /viewtemplates/WEB-INF/classes/views.properties
8. View Resolver Used: ResourceBundleViewResolver
9. View File Name: pdfview.jsp
10. Web Application Context File Name: viewServlet-servllet.xml
11. DispatcherServlet Name:viewServlet
12. Application Context File Name: web.xml
13. Web Application Context and Application Context File Location: /WEB-INF
14. Type: http://localhost:8080/viewtemplates/pdf and click Custom CSV link.

51
JSTL Templates

JSTL stands for Java Standard Tag Library. It allows JSP programmers to program
using tags rather than scriptlet code that most JSP programmers were already
accustomed to. We can create jsp views that implements JSTL tags.
Let us create a jsp page that prints value from 1 to 10 first using scriplet code and
secondly using JSTL tgs.
We have created two different jsp files namely cntjsp.jsp and cntjstl.jsp inside /WEB-
INF/jsps directory and created two different methods named viewCntJSP and
viewCntJSTL respectively within MainController class for accessing these two files.
1. To run cntsjp.jsp file, type URL http://localhost:8080/viewtemplates/jspview in
browser, which will display number from 1 to 10. Cntjsp.jsp implements javacode
to display the values.
2. To run cntjstl.jsp file. Type URL http://localhost:8080/viewtemplates/jstlview in
browser, which will display number from 1 to 10. Cntjstl.jsp implements JSTL
tags to display the values.

HTTP Request Data binding to multiple domain objects


Let us create following two POJO classes

1. Increment.java: It will accept person ID, PersonName and Salary as three


parameter. If a person's salary is less than 10000, then it will increase the salary
by 20 % . If a person's salary is greater than or equals to 10000, it will increment
the salary by 100 Rupees only
2. Decrement.java: It will accept person ID, PersonName and Salary as three
parameter.If a person's salary is greater than or equals to 15000 than it will
decrease the salary by 20%. If person's salary is not greater than or equal to
15000 then it will increment the salary by 3000.
http://localhost:8080/viewtemplates/test?id=11&pname=Mukesh&salary=10000

In above example, We binded id,pname and salary variable value[URL] to two domain
objects namely incr and decr of Domain classes namely Increment and Decrement
respectively.

showperson() method implemented inside MainController class is responsible for


binding above URL values to two domain objects.

Showperson.jsp file in turn retrieves the binded values from above two objects and
displays it.

To run example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: MainController

52
4. Modal Classes: Increment.java,Decrement.java
5. View File Location: /WEB-IN/jsps/
6. View Resolver Used: InternalResourceViewResolver
7. View File Name: showperson.jsp
8. Web Application Context File Name: viewServlet-servllet.xml
9. DispatcherServlet Name:viewServlet
10. Application Context File Name: web.xml
11. Web Application Context and Application Context File Location: /WEB-INF
12. Type:http://localhost:8080/viewtemplates/test?
id=11&pname=Mukesh&salary=10000

File Upload and Error Handling

File Upload:

 To upload file, you have to add commons-io-2.4.jar and commons-fileupload-


1.3.1.jar in both Java Build Path and Deployment Assembly.
 We need to add following lines of code on our web application context file to run
this example:

 We choose file to be uploaded from our computer and give file name to be stored
on the server. We have following two programs for this:
1. Upload Single File Only:
 Methods responsible for displaying upload screen is retUpload() which is
implemented inside MainController class and method responsible for
uploading file is uploadFileHandler() [which is also implemented inside
MainController ]
 Type: http://localhost:8080/viewtemplates/upload url in the browser.
[ upload.jsp which is located inside /WEB-INF/jsps directory will be
displayed]

2. Upload Multiple Files:


 Methods responsible for displaying upload screen is retMultipleUpload()
which is implemented inside MainController class and method responsible
for uploading file is uploadMultipleFileHandler [which is also implemented
inside MainController ]
 Type: http://localhost:8080/viewtemplates/uploadmultiple url in the
browser. [ uploadMultipe.jsp which is located inside /WEB-INF/jsps
directory will be displayed]
53
Error Handing:

Refer to ExceptionResolver above

Prototype Usage

Refer to page no 28 and 29 of Chapter 1

Jquery and Ajax in Spring Web MVC Project

To use jquery and ajax and css in your applications, first of all you need to create a
folder resources under WebContent Directory and keep all your java script and css and
image files over there.In our case, we have kept test.css,test.js and jquery.js files under
this directory. We have used jQuery and ajax inside hello.jsp file. To run this example:
Type: http://localhost:8080/viewtemplates/hello in your web browser. In this way,
hello.jsp will be displayed and jQuery implementation is verified by displaying " This is
Hello World by JQuery" and ajax call is verified once we click the "Save" button, data and
time information returned from MainController's getTime() method. Method
implemented inside MainController which is responsible for displaying hello.jsp file is
helloWorld(). Do not forget to include following lines of code in your web application
context file:

You have to write following codes to include css and java script codes used by your
page inside hello.jsp page

To run example:

1. Project Name:viewtemplates
2. Java Source code package name: ch2.mvc.viewtemplates
3. Controller Class Name: MainController
4. View File Location: /WEB-IN/jsps/
5. CSS,JS,IMAGE FILE LOCATION: /viewtemplates/WebContent/resources
6. View Resolver Used: InternalResourceViewResolver
7. View File Name: hello.jsp
8. Web Application Context File Name: viewServlet-servllet.xml
9. DispatcherServlet Name:viewServlet
10. Application Context File Name: web.xml
11. Web Application Context and Application Context File Location: /WEB-INF

54
12. Type: http://localhost:8080/viewtemplates/hello to run above example

Integrating Spring and JSF

JSF is a MVC framework. JSF is a component based MVC and Spring MVC is request
based MVC. We cannot mix them. They are indeed competitors. Facelets(XHTML) is
default view technology for JSF. However, we can use JSP as view technology for
spring MVC. We can use Spring MVC with Facelets view technology and many others.

A managed bean is also a regular Java class in JSF and it is configured in faces-
config.xml file and it made available to the Application by the JSF Framework.

Spring uses Spring Beans and JSF uses Managed Beans. The Spring Framework
provides support in such a way that a Spring Bean is made visible to the JSF
Environment. Precisely, the Spring Bean what we have configured in the Xml file can be
directly referred in the faces-config.xml as if it was a JSF managed Bean.

Integrating Spring and JSF means using Spring Bean Object from JSF.

1. Create a Dynamic Web Project named JSFDemo


2. Do not forget to add following jar files into the project [ Java Build Path and
Deployment Assembly]
 Commons-beanutils-1.9.2.jar
 Commons-chain-1.2.jar
 Commons-collection4-4.1.jar
 Commons-digester3-3.2.jar
 Commons-logging-1.2.jar
 Jsf-api-2.2.8-12.jar
 Jsf-impl-2.2.8-12.jar
 Jstl-1.2.jar
 spring-beans-4.2.2.RELEASE.jar
 spring-context-4.2.2.RELEASE.jar
 spring-core-4.2.2.RELEASE.jar
 spring-expressions-4.2.2.RELEASE.jar
 spring-web-4.2.2.RELEASE.jar

3. Assume that we have following Spring Bean class

55
4. Above bean class is registered in applicationContext.xml file which is stored
on /WEB-INF/applicationContext.xml location as shown below:

Above XML context file will initialize "Hello World" value to message property of
SringBean class.
5. applicationContext.xml location is specified in web.xml file as shown below:

6. Moreover, to load applicationContext.xml file during the runtime, we need to


register following listener class inside web.xml file

7. JSF is specified in web.xml file as shown below:

56
8. Assume that we have a JSF bean file named JSFBean as shown below:

9. Above JSFBean class is registered inside faces-config.xml file which is also


stored on /WEB-INF/faces-config.xml location as shown below:

Note that springBean is an id of SpringBean class which was defined in


applicationContext.xml [ Spring application context file]. We are referencing it in
faces-config.xml file which is JSF application context file. It means, spring bean is
being used within JSF application context file. This proves the integration

57
between JSF and Spring. Code written inside <managed-property> tag will fetch
SpringBean object and assign it to sprgbn variable which is declared in JSFBean
class. Usage of springBean[that was defined in applicationContext.xml] in faces-
config.xml is resolved by writing following resolver codes in faces-config.xml file

10. When we type URL http://localhost:8080/JSFTutorial/jsf/HelloWorld.jsp in


browser,following window is displayed:

11. Code to display above window is implemented inside HelloWorld.jsp which is


stored /WEB-INF/HelloWorld.jsp location shown below:

12. When we press "Get Completed Name" button, following window is displayed:

58
Code responsible for displaying above output is HelloWorldResult.jsp

Inside the highlighted rectangle, you can see "Hello World!" message. This is the
proof that Spring and JSF are integrated because this "Hello World !" message
we had earlier set to message property of SpringBean through
applicationContext.xml file. And from faces-config.xml file later we had accessed
same spring bean and assigned it to sprgbn object that is declared in JSFBean
class. Later, in HelloWorld.jsp we call getGreetingMessage method of JSFBean
class through jsfBean which was defined in faces-config.xml file.
getGreetingMessage() method in JSFBean class in turn calls getMessage()
method of SpringBean class, which in turn returns the "Hello World !" value that
was earlier assigned to message property of SpringBean class.
13. Code corresponding to HelloWorldResult.jsp is shown below:

Note: To avoid ViewExpiredException , you can keep following line of code inside
web.xml file

59
Integrating with Tapestry

Tapestry is a framework that was used for web development in earlier days. These days
Tapestry is not commonly used. We can integrate Tapestry to Spring Framework.
Integrating Tapestry to Spring Framework means we can use Spring beans from
Tapestry application.
In earlier days to use Tapestry in your project, you should have to install Spindle in your
eclipse environment. Spindle is not supported on latest version of eclipse. You have to
download eclipse 3.8 for spindle to work. To install Spindle, follow the following steps:

1. Download Eclipse version 3.8 from following URL:


http://archive.eclipse.org/eclipse/downloads/drops/R-3.8.1-201209141540/
download.php?dropFile=eclipse-SDK-3.8.1-win32.zip
2. Download Spindle from Source Forge a.k.a from the following link:
3. http://iweb.dl.sourceforge.net/project/spindle/spindle/Spindle%203.4%20for
%20Eclipse%203.3/spindle.update.site.archive_3.4.0.zip Unzip the downloaded
file inside a folder named spindle
4. Open Eclipse and Go to Help->Install New Software->Click on Add Button->
Click on Archive Button and point to Spindle Directory where previously
downloaded components are unzipped-> Type Spindle in Name Field-> Press
OK Button-> Now Check the Eclipse item and follow the instructions accordingly.

Tapestry application development with older version of eclipse is not recommended.


You can also develop tapestry web application with latest version of eclipse, jdk and
Tomcat. However, you need to install Maven for the development of Tapestry web
application. To install maven, you have to go to Help->Install New Software->Click on
Add Button->Fill Following Information on the dialog box

Follow instructions accordingly-> Wait for a couple of minutes-> Maven will be installed
on your eclipse-> Restart eclipse.

After installing maven on eclipse, to run tapestry web application, you have to create a
maven project. To create a maven project File->new->Other->Maven->Maven Project->
Click Next-> Click Configure Button-> Click Add Remote Catalog Button-> Fill Following
information on the dialog box

60
On the Select an Archetype dialog , select the newly-added Apache Tapestry catalog, then select the
"quickstart" artifact from the list and click Next.Fill following information onto the dialog box:

61
Click Finish
In this way, you created tapestry project successfully.
To execute the project, Right Click on Project Name->Run As->Run on Server->Click
Next->Finish

You will notice following web page typing following URL:

http://localhost:8080/tutorial2/

62
If you closely look at project structure, you can see following project tree structure:

63
Inside Java Resources. Src/man/java folder there are following sub folders:
Com.example.tutorial.pages where tapestry application page class files are placed. And
inside src/main/resources folder all tapestry page template files are placed.

Inside src/main/Webapp/WEB-INF: Web Deployment Descriptor web.xml is stored here.

Simialry, you can see pom.xml inside target folder

Tapestry web application comprises a set of pages. Each tapestry page has a template
and page class. Page Template is XML document that ends with .tml extension and
follows syntax mostly of XHTM and are placed inside resources folder as shown above.
Every Page Template has corresponding Page class[ Name of Page template file and
corresponding page class must be similar] and Page Template accesses values or
Properties from Page class. Page classes are kept inside java directory and has .java
extension.
Now let us create a file named Start.tml and Start.java inside src/main/resources and
src/main/java directory respectively.[ Create these files by Right clicking Java
Resources folder].

64
Content of Start.java is:
package com.example.tutorial.pages;

import java.util.Date;

import javax.inject.Inject;

/**
* Start page of application t5first.
*/
public class Start
{
private int someValue=555;
@Inject
private com.spring.demo.SpringClass springObj;
public int getSomeValue() {
return someValue;
}
public void setSomeValue(int someValue) {
this.someValue = someValue;
}

public String getCurrentTime()


{
Date date = new Date();
String message = ". Tapestry is cool!";
return date + message;
}
public String getEName()
{
return springObj.geteName();
}
public com.spring.demo.SpringClass getSpringObj() {
return springObj;
}
public void setSpringObj(com.spring.demo.SpringClass springObj) {
this.springObj = springObj;
}
public Date getCurrentTime1()
{
return new Date();
}

Content of Start.tml file is:


<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
<head>
<title>t5first Start Page</title>
</head>
<body>
<h1>Tapestry Start Page</h1>
<p> This is the start page for this application, a good place

65
to start your modifications.
Just to prove this is live: </p>
<p> The current date and time is: ${currentTime}. </p>
<p> Value fetched from Stat.tml page is: ${someValue}. </p>
<p> Value fetched from Spring class is: ${springObj.geteName()}. </p>
<p> Value Returned from getCurrentTime1 method in MS is: ${currentTime1.time}.
</p>
<p> HashCode is: ${currentTime1.hashCode()}. </p>
<p> [<t:pagelink t:page="Start">refresh</t:pagelink>] </p>
</body>
</html>
[ Create above file by Right Clicking Pages folder inside src/main/resources]

Content of SpringClass.java file is:


package com.spring.demo;

public class SpringClass {


public String eName;

public String geteName() {


return eName;
}

public void seteName(String eName) {


this.eName = eName;
}

Edit src/main/Webapp/WEB-INF/web.xml and remove following lines of code from it:

Add following lines of code into the web.xml file

66
Create applicationContext.xml file inside src/main/Webapp/WEB-INF/ folder and
following lines of code inside it.

Above code will set eName property of SpringClass[Spring Bean Class] value to
"Mukesh". Now Start.tml tapestry page template file access above eName value as
shown below:

<p> Value fetched from Spring class is: ${springObj.geteName()}. </p>

Start.java is a tapestry page class which contains following code:


@Inject
private com.spring.demo.SpringClass springObj;

Above code access SpringClass object i.e. Tapestry Page class access SpringBean
object.

67
Inside target folder there is a file named pom.xml, add following on it:

<dependency>
<groupId>org.apache.tapestry</groupId>
<artifactId>tapestry-spring</artifactId>
<version>5.4.0</version>
</dependency>

Run your Project, you will get the following:

The output included within the rectangle above verifies that Tapestry and Spring are
integrated successfully [ i.e. Tapestry Page Template accesses Spring Bean class
property value].

D:\tapdemo\tutorial2 covers all above examples

68

You might also like