6) Controller
Controllers are components that are being called by the Dispatcher Servlet for doing any kind of Business Logic. Spring Distribution already comes with a variety of Controller Components each doing a specific purpose. All Controller Components in Spring implement the org.springframework.web.servlet.mvc.Controller interface. This section aimed to provide the commonly used Controllers in the Spring Framework. The following are the Controller Components available in the Spring Distribution.
* SimpleFormController
* AbstractController
* AbstractCommandController
* CancellableFormController
* AbstractCommandController
* MultiActionController
* ParameterizableViewController
* ServletForwardingController
* ServletWrappingController
* UrlFilenameViewController
The following section covers only on AbstractController, AbstractCommandController, SimpleFormController and CancellableFormController in detail.
6.1) Abstract Controller
If one wants to implement Custom Controller Component right from the scratch, then instead of implementing the Controller interface, extending AbstractController can be preferred as it provides the basic support for the GET and the POST methods. It is advised that only for simple purpose, this type of extensions should be used. The purpose may be as simple as returning a resource to the Client upon request without having the need to examine the Request Parameters or other Stuffs. For example, consider the following piece of code,
MySimpleController.java
public class MySimpleController extends AbstractController{
public void handleRequestInternal(HttpServletRequest request,
HttpServletResponse response){
return new ModelAndView("myView");
}
}
Note that the Dispatcher Servlet will call the handleRequest() method by passing the Request and the Response parameters. The implementation just returns a ModelAndView (discussed later) object with myView being the logical view name. There are Components called View Resolvers whose job is to provide a mapping between the Logical View Name and the actual Physical Location of the View Resource. For the time being, assume that somehow, myView is mapped to myView.jsp. So, whenever the Dispatcher Servlet invokes this MySimpleController object, finally myView.jsp will be rendered back to the Client.
6.2) Abstract Command Controller
The concept of Command Controller comes into picture when the Business Logic depends upon the values that are submitted by the User. Instead of depending on the Servlet Api to get the Request Parameter Values and other session Objects, we can depend on this Abstract Command Controller to take those pieces of Information. For example consider the following code snippet which has a simple business logic telling that, depending on the existence of username, display the form success.jsp or failure.jsp
MySimpleController.java
public class MySimpleController extends AbstractCommandController{
public MySimpleController(){
setCommandClass(UserInfo.class);
}
public void handle(HttpServletRequest request, HttpServletResponse response,
Object command){
UserInfo userInfo = (UserInfo)command;
if ( exists(userInfo.getUserName){
return new ModelAndView("success");
}else{
return new ModelAndView("failure");
}
}
private boolean exits(String username){
// Some logic here.
}
}
Note that the Client Parameters (username , in this case) is encapsulated in a simple Class called UserInfo which is given below. The value given by the Client for the username field will be directly mapped to the property called username in the UserInfo. In the Constructor of the MySimpleController class, we have mentioned the name of the Command Class which is going to hold the Client Request Parameters by calling the setCommandClass() method. Also note that in the case of Command Controller, the method that will be called by the Dispatcher Servlet will be handle() which is passed with the Command object apart from the Request and the Response objects.
UserInfo.java
public class UserInfo{
private String username;
// Getters and Setters here.
}
6.3) Simple Form Controller
Asking the User to fill in a Form containing various information and submitting the form normally happens in almost every Web Application. The Simple Form Controller is exactly used for that purpose. Let us give a simple example to illustrate this. Assume that upon Client Request a page called empInfo.jsp is rendered to the client containing empName, empAge and empSalary fields. Upon successful completion a Jsp Page called empSuccess.jsp is displayed back to the Client. Now let us see how we can make use of the Simple Form Controller to achieve this kind functionality.
The very first thing is that, to collect the Client Input Values, a Command object which contains getter and setters must be defined. Following the skeleton of the class called EmpInfo.
EmpInfo.java
public class EmpInfo{
private String empName;
private int empAge;
private double empSalary;
// Getters and setters for the above properties.
}
The next thing is to write a class that extends SimpleFormController. But this time, the doSubmitAction() method should be overridden. This is the method that will be called when the Client submits the form. Following is the definition of the Controller class.
EmpFormController.java
public class EmpFormController extends SimpleFormController{
public EmpFormController(){
setCommandClass(EmpInfo.class);
}
public void doSubmitAction(Object command){
EmpInfo info = (EmpInfo)command;
process(info);
}
private void process(EmpInfo info){
//Do some processing with this object.
}
}
As we mentioned previously, the form that collects information from the Client is empInfo.jsp and upon successful submission the view empSuccess.jsp should be displayed. This information is externalized from the Controller class and it is maintained in the Configuration File like the following,
<bean id = "empForm" class="EmpFormController">
<property name="formView">
<value>empInfo</value>
</property>
<property name="successView">
<value>empSuccess</value>
</property>
</bean>
Note the two property names 'formView' and 'successView' along with the values 'empInfo' and 'empSuccess'. These properties represent the initial View to be displayed and the final view (after successful Form submission) to be rendered to the Client.
6.4) Cancellable FormController
If you carefully notice with the implementation of Simple Form Controller, there are ways to provide the Initial and the Successful View to the Clients. But what happens when the Form is cancelled by the User? Who will process the Cancel operation of the Form?
The above issues can be given immediate solution with the usage of Cancellable FormController. The good thing is that Cancellable FormController extends SimpleForm Controller so that all the functionalities are visible to this Controller also. Suppose say that the User clicks the cancel button, the Framework will check in the Request parameter for a key with name 'cancelParamKey'. If it is so, then it will call the onCancel() method. Consider the following definition,
MyCompleteFormController.java
public class MyCompleteFormController extends CancellableFormController{
public ModelAndView onCancel(){
return new ModelAndView("cancelView");
}
}
7) Model And View
Model and View (represented by the class org.springframework.web.servlet.ModelAndView) is returned by the Controller object back to the Dispatcher Servlet. This class is just a Container class for holding the Model and the View information. The Mode object represents some piece of information that can be used by the View to display the information. Both these Objects are given high degree of abstraction in the Spring Framework.
Any kind of View Technology (org.springframework.web.servlet.View) can be plugged into the Framework with ease. For example, Excel, Jasper Reports, Pdf, Xslt, Free Marker, Html, Tiles, Velocity etc. are the supported Frameworks as of now. The Model object (represented by org.springframework.ui.ModelMap) is internally maintained as a Map for storing the Information.
Following are the ways to Construct the Model and the View object.
View pdfView = �;
Map modelData = new HashMap();
ModelAndView mv1 = new ModelAndView(pdfView, modelData);
The above constructs a ModelAndView object by passing the actual View object along with the Model object. Now consider the following code,
ModelAndView mv1 = new ModelAndView("myView", someData);
Note, in the above example, a string with "myView" is passed for the View. This way of specifying a View is called a Logical View. It means that myView either can point to something called myView.jsp or myView.pdf or myView.xml. The Physical View Location corresponding to the Logical View can be made configurable in the Configuration File.
8) View Resolver
In the previous section, we talked about Logical View and the Physical View Location for the Logical View. The mapping between the Logical name and the Physical View Location is taken care by the View Resolver object. Without any surprise, Spring comes with a set of Built-In Spring Resolvers. It is even possible to write Custom View Resolvers by implementing the org.springframework.web.servlet.ViewResolver interface. Following are the available View Resolvers in the Spring Distribution.
* BeanNameViewResolver
* FreeMarkerViewResolver
* InternalResourceViewResolver
* JasperReportsViewResolver
* ResourceBundleViewResolver
* UrlBasedViewResolver
* VelocityLayoutViewResolver
* VelocityViewResolver
* XmlViewResolver
* XsltViewResolver
The following section concentrates only on Internal Resource View Resolver and Bean Name View Resolver in detail.
8.1) Internal Resource View Resolver
The Internal Resource View Resolver will try to map the Logical name of the Resource as returned by the Controller object in the form of ModelAndView object to the Physical View location. For example, consider the following class definition which returns different ModelAndView objects.
MyController.java
public class MyController {
public void handle(){
if(condition1()){
return new ModelAndView("myView1");
}else if (condition2()){
return new ModelAndView("myView2");
}
return new ModelAndView("myView3");
}
}
Assume that if the Client Request satisfies condition1(), then the view myView.jsp which is present in the /WEB-INF folder should be displayed and for the client Requests satisfying condition2() and the other one, myView2.jsp and myView3.jsp should be displayed.
For this to happen, the following entry must be made in the Configuration File,
<bean id="viewResolver" class="org.springframework.web.servlet.view.
InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
This is how the Internal Resource View Resolver will map the Logical View Name to the physical Location. When the logical View name is myView1, then it will construct a view name which is the summation of the prefix + the logical View Name + the suffix, which is going to be /WEB-INF/myView.jsp. The same is the case for myView2.jsp and myView3.jsp.
8.2) Bean Name View Resolver
One of the dis-advantage of using Internal Resource View Resolver is that the name of the View file (whether it is a Jsp File or the Pdf File) must be present in the Web Application Context. Dynamically generated View files may not be possible. In such a case, we may use the Bean Name View Resolver which will dynamically generate View in Pdf or Excel Formats.
For the example, if the ModelAndView object represents a View by name "pdf" as shown in the following snippet,
return ModelAndView("pdf")
And, if we want to generate the Pdf file, then we should have defined the Configuration information in the file as follows,
<bean id="beanNameResolver"
class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
The above code configures the Framework to use BeanNameViewResolver. Since the logical name 'pdf' must resolve to a Bean Name, we should define a similar entry like the following in the Configuration File. Note that, in the following MyPdfGenerator may be the sub-class of org.springframework.web.servlet.view.document.AbstractPdfView for generating the Pdf File.
<bean id = " pdf " class = "MyPdfGenerator"/>