`
coreoak
  • 浏览: 65127 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring MVC3

阅读更多
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"/>
分享到:
评论

相关推荐

    spring mvc 3_demo

    在这个"Spring MVC 3_demo"中,我们重点探讨的是使用注解来实现Spring MVC 3的应用。注解在Spring MVC中扮演着重要角色,它们简化了配置,提高了代码的可读性和可维护性。 1. **注解驱动的控制器**: 在Spring MVC...

    Mastering Spring MVC 3中文版

    《Mastering Spring MVC 3中文版》是一本深入解析Spring MVC框架的专业书籍,它涵盖了Spring MVC的核心概念、设计原理以及实际应用。Spring MVC是Spring框架的一部分,主要用于构建Web应用程序的模型-视图-控制器...

    spring mvc3 学习资料

    根据提供的文件信息,这是一份关于Spring MVC3的学习资料,涵盖了Spring MVC3的基础知识、高级特性和使用技巧。接下来,我将详细地说明文档中所提到的知识点。 1. WebMVC简介 - WebMVC指的是Model-View-Controller...

    spring MVC3 mybatis3 spring3整合实例

    Spring MVC、MyBatis 和 Spring 是Java开发领域中三大核心框架,它们的整合使用能够...这个教程中的"spring MVC3 mybatis3 spring3整合实例"应该会详细讲解这些内容,帮助开发者更好地理解和掌握这三大框架的整合使用。

    spring MVC3 + mybatis 3 - demo工程

    **Spring MVC3与MyBatis 3整合的Demo工程** Spring MVC和MyBatis是Java Web开发中的两个重要框架,Spring MVC负责控制层,而MyBatis则专注于数据访问层。这个Demo工程提供了如何将两者结合使用的实例,适用于Oracle...

    Spring MVC3和Hibernate3整合的源码

    Spring MVC 3与Hibernate 3是两个非常重要的Java Web开发框架,它们的整合使得开发者能够构建高效、可维护的Web应用程序。Spring MVC提供了强大的模型-视图-控制器(MVC)架构,而Hibernate则是一个优秀的对象关系...

    Spring3、 Hibernate4、 Spring mvc3 通用后台管理系统

    Spring3、Hibernate4 和 Spring MVC3 的集成是现代Java企业应用的常见架构模式。Spring作为整体框架,负责管理和协调各个组件;Hibernate作为ORM工具,处理数据库交互;Spring MVC则处理Web请求,将控制权流转到业务...

    spring mvc3 showcase(Spring MVC3 Demo)

    这是老外开发的一个Spring MVC3的例子,Spring版本为:3.2.0.RELEASE。 这个例子展示了Spring MVC的很多特性,其中使用到了Json数据格式和jQuery及jQuery UI技术,很好的一个Demo,值得学习、效仿! 工程使用Maven...

    java web开发spring mvc3框架包含jar包,适于学习

    在描述中提到的"java web开发spring mvc3框架包含jar包",这意味着这个压缩包包含了运行Spring MVC 3项目所需的所有依赖库。Spring MVC 3是该框架的一个旧版本,但仍然被许多初学者和开发者用于学习和理解其基本概念...

    Spring3,Hibernate4,Spring mvc3 通用后台管理系统

    《Spring3,Hibernate4,Spring MVC3:构建通用后台管理系统的深度解析》 在现代企业级应用开发中,Spring、Hibernate 和 Spring MVC 是三个至关重要的技术框架,它们各自扮演着核心角色,共同构建出高效、稳定的...

    精通Spring MVC 4

    Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。Spring MVC4是当前zuixin的版本,在众多特性上有了进一步的提升。, 在精通Spring...

    Spring MVC3入门之1 Hello World(XML based)

    **Spring MVC3 入门教程** 在本文中,我们将探讨如何使用Spring MVC 3框架创建一个简单的"Hello World"应用程序。Spring MVC是Spring框架的一部分,它提供了一个模型-视图-控制器(MVC)架构来构建Web应用程序。...

    Spring MVC 3 实例

    Spring MVC 3实例,包含上传下载,还有Spring mvc jsr303表单验证技术,还有一个spring mvc ajax json等 欢迎下载 自己研究,简单易懂 如果有注解不懂,可以看看...

    Spring MVC jar包

    3. **整合Spring MVC和Hibernate**: - **依赖注入**:Spring可以通过DI(Dependency Injection)管理Hibernate的SessionFactory,使得配置更灵活。 - **事务管理**:Spring提供声明式事务管理,可以控制Hibernate...

    Spring MVC3。 最近研究

    7. **使用Maven在Eclipse中创建Spring 3 MVC与Hibernate 3的例子**:Spring MVC可以很好地与ORM框架如Hibernate集成。这部分将带你通过一个实战示例,学习如何在Spring MVC中配置和使用Hibernate进行数据持久化。 ...

    Spring 3.x+Spring MVC 3.x+MyBatis 3.x 整合(五)代码

    Spring 3.x+Spring MVC 3.x+MyBatis 3.x 整合代码 该代码仅截止到《Spring 3.x+Spring MVC 3.x+MyBatis 3.x 整合(五)MyBatis 3.2.5 整合》,原文件地址:http://blog.csdn.net/xz2001/article/details/44346355

    spring mvc3 教程

    spring mvc3 教程,看过就会,最佳实践

    spring mvc3 mybatis3 extjs 3.4权限管理系统

    本人初步采用spring mvc3 mybatis3 extjs 3.4开发进销存软件,有很好的参考价值,其中数据库采用oracle,分页采用调用oracle的存储过程,有很好的学习价值,若是想开发简单的CRM和进销存系统是极品参考的系统。...

    spring3MVC 框架demo

    Spring3MVC是Spring框架的一个重要模块,专为构建Web应用程序提供模型-视图-控制器(MVC)架构支持。这个框架使得开发者可以更轻松地处理HTTP请求、数据绑定、验证以及视图渲染等任务。在"spring3MVC框架demo"中,...

Global site tag (gtag.js) - Google Analytics