Go to spring MVC

Source: Internet
Author: User
Tags ibm developerworks

Easy Application Development with spring MVC

Document options

<Tr valign = "TOP"> <TD width = "8"> </TD> <TD width = "16"> </ TD> <TD class = "small" width = "122"> <p> <SPAN class = "Ast"> the required JavaScript document options are not displayed </span> </P> </TD> </tr>


Send this page as an email

Discussion

Sample Code


Level: Intermediate

Naveen balani, technical architect, webify Solutions

October 13, 2005

In Part 1 of Naveen balani's Spring Series, learn how to use the Spring framework to develop MVC-based applications.

InSpring SeriesIn section 3rd, I will introduce the spring MVC framework. Just as in my previous article, I used banking examples to show you how to model and build simple applications. The sample application contains some technologies (such as dependency injection) that have been learned, but mainly demonstrates the features of spring MVC.

Before you start, download the source code of this article. For more information, see accessing the Spring framework and tomcat 5.0.

Spring MVC Framework

The Spring framework provides a full-featured MVC module for Building Web applications. Using spring-pluggable MVC Architecture, you can choose whether to use a built-in spring Web framework or a Web framework such as struts. Through the policy interface, the Spring framework is highly configurable and contains multiple view technologies, such as assumerver pages (JSP), velocity, tiles, itext, and poi. The spring MVC Framework does not know the view used, so it does not force you to only use JSP technology. Spring MVC separates the roles of controllers, model objects, schedulers, and processing program objects, making them easier to customize.

Spring web MVC framework is centered aroundDispatcherServletDesigned to distribute requests to the processing program, with configurable handler ing, view resolution, local language, topic resolution, and file upload support. The default handler is very simple.ControllerInterface, only one methodModelAndView handleRequest(request, response). Spring provides a controller hierarchy that can be derived from child classes. If the application needs to process the user input form, it can inheritAbstractFormController. If you need to process multi-page input to a form, you can inheritAbstractWizardFormController.

The sample application helps you learn these features intuitively. The Banking application allows users to retrieve their account information. When building a bank application, you can learn how to configure the spring MVC Framework and the view layer of the implementation framework. The view layer includes the jstl tag (used to display output data) and the assumerver Pages technology.



Back to Top

Configure spring MVC

To start building the sample application, configure the spring MVCDispatcherServlet. Please goWeb. xmlFile. Listing 1 shows how to configuresampleBankingServlet.

Listing 1. configuring spring MVC dispatcherservlet


<servlet>
<servlet-name>sampleBankingServlet</servlet-name>
<servlet-class>
org.springframework.we.servlet.DispatcherServlet
<servlet-class>
<load-on-startup>1<load-on-startup>
<servlet>

DispatcherServletLoad the spring application context from an XML file. The XML file name is added after the servlet name.-Servlet. In this example,DispatcherServletFromSampleBankingServlet-servlet.xmlFile Load application context.

Configure the application URL

The next step is to configuresampleBankingServletThe URL to be processed. SimilarlyWeb. xml.

List 2. Configure the URL to be processed


<servlet-mapping>
<servlet-name> sampleBankingServlet<servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

Load the configuration file

Next, load the configuration file. To achieve this, register for the servlet 2.3 StandardContextLoaderListenerOr register for containers of servlet 2.2 or lower.ContextLoaderServlet. To ensure backward compatibility, useContextLoaderServlet. When starting a web application,ContextLoaderServletLoad the spring configuration file. Listing 3 registeredContextLoaderServlet.

Listing 3. Registering contextloaderservlet


<servlet>
<servlet-name>context>servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

contextConfigLocationThe parameter defines the spring configuration file to be loaded, as shown in the servlet context below.

<context-param>
<param-value>contextConfigLocation</param-value>
<param-value>/WEB-INF/sampleBanking-services.xml</param-value>
</context-param>

SampleBanking-services.xmlThe file represents the configuration of the sample banking Application Service and bean configuration. If you want to mount multiple configuration files, you can<param-value>Use a comma as the Separator in the tag.



Back to Top

Spring MVC example

The example bank application allows you to view account information based on a unique ID and password. Although spring MVC provides other options, I will use JSP technology as the view page. This simple application contains a view page for user input (ID and password), and the other page displays the user's account information.

FromLoginBankControllerIt expands spring MVC'sSimpleFormController.SimpleFormContollerProvidesHTTP GETThe function of the form received by the request, and the process fromHTTP POSTThe function of receiving the same form data.LoginBankControllerUseAuthenticationServiceAndAccountServicesService to verify and execute account activities. Listing 5 in the "Configure view attributes" section describes howAuthenticationServiceAndAccountServicesConnectLoginBankController. Listing 4 showsLoginBankController.

Configure view attributes

Below, I must registerHTTP GETPage displayed during request. Used in spring ConfigurationformViewProperty registration page, as shown in listing 5.sucessViewAttribute indicates that the form data is submitted anddoSubmitAction()Page displayed after the logic in the method is successfully executed.formViewAndsucessViewAll attributes represent the logical names of the defined views. The logical names are mapped to the actual view pages.

Listing 5. Register loginbankcontroller

  
<bean id="loginBankController"
class="springexample.controller.LoginBankController">
<property name="sessionForm"><value>true</value></property>
<property name="commandName"><value>loginCommand</value></property>
<property name="commandClass">
<value>springexample.commands.LoginCommand</value>
</property>
<property name="authenticationService">
<ref bean="authenticationService" />
</property>
<property name="accountServices">
<ref bean="accountServices" />
</property>
<property name="formView">
<value>login</value>
</property>
<property name="successView">
<value>accountdetail</value>
</property>
</bean>

commandClassAndcommandNameTag determines the bean to be active in the view page. For example, you can useLogin. jspPage accessloginCommandBean, which is the login page of the application. Once the user submits the login page, the application canLoginBankControllerOfonSubmit()Method.

View parser

Spring MVCView parserResolve each logic name to the actual resource, that is, the JSP file containing account information. I use spring.InternalResourceViewResolver, As shown in Listing 6.

Because I used the jstl tag in the JSP page, the user login name is parsed into a resource/JSP/login. jsp, AndviewClassBecomeJstlView.

Verification and Account Service

As mentioned above,LoginBankControllerInternally connected to springAccountServicesAndAuthenticationService.AuthenticationServiceClass handles the verification of bank applications.AccountServicesClass handles typical banking services, such as searching for transactions and wire transfers. Listing 7 shows the authentication of the banking application and the configuration of the Account Service.

Listing 7. Configuration verification and Account Service


<beans>
<bean id="accountServices"
class="springexample.services.AccountServices">
</bean>
<bean id="authenticationService"
class="springexample.services.AuthenticationService">
</bean>
</beans>

The above services are available inSampleBanking-services.xmlAnd then loadWeb. xmlFile, as discussed earlier. After the controller and service are configured, this simple application is complete. Now let's take a look at what will happen when deploying and testing it!



Back to Top

Deploy applications

I deploy the sample application in the Tomcat servlet container. Tomcat is the servlet container used in implementation for official reference of Java Servlet and Java serverpagest technology. If you haven't done this before, download the jakarta-tomcat-5.0.28.exe and run it to install Tomcat anywhere you like, suchc:/tomcat5.0.

Next, download the sample code and release it to the drive (for exampleC :/. After creating the spring project folder, open it andSpring-BankingCopy subfoldersC:/tomvat5.0/webapps. The spring-banking folder is a Web file containing the spring MVC sample application. The LIB folder contains the Spring framework required by the application, spring-related MVC libraries, jstl tag libraries, and jar files.

To start the Tomcat server, run the following command:

cd bin C:/Tomcat 5.0/bin> catalina.bat start

Tomcat should start and deploy the spring MVC sample application.



Back to Top

Test the application

To test the application, Open a Web browser and point to http: // localhost:Tomcatport/Springbanking and replace it with the actual running port of the Tomcat serverTomcatport. The logon screen shown in Figure 1 is displayed. Enter the user ID "admin" and password "password", and press the logon button. Other user IDs or passwords may cause errors from the authentication service.

Figure 1. Spring MVC sample logon screen

After successful logon, the account details page shown in Figure 2 is displayed.

Figure 2. Spring MVC sample account details page



Back to Top

Conclusion

InSpring SeriesIn the third article, I introduced the features of spring MVC framework. I demonstrated how to configure and Develop Spring MVC applications, how to configure spring MVC controllers and insert dependencies into them, and how to develop application views using the assumerver Pages technology, and how to integrate your page with the view layer of spring MVC. To sum up this article, I demonstrated how to deploy an application in a Tomcat servlet container and how to test it in a browser.

Continue to followSpring Series. In the next article, I will introduce how to integrate JMS-based applications with the Spring framework. For more information about Spring framework and spring MVC, see references.



Back to Top

Download

Description Name Size Download Method
Example source code, spring files, Jar files Wa-spring3-SpringProjectPart3.zip 1966 KB HTTP
Information about the Download Method

References

Learning

  • For more information, see the original article on the developerworks global site.

  • "Spring Series, Part 1: Spring framework Introduction" (developerworks, 1st) and "Spring Series, Part 2: When hibernate encounters Spring" (developerworks, 2nd ): this article introduces how to use spring technology to build lightweight and robust J2EE applications and how to integrate hibernate transactions with spring's Aspect-oriented programming (AOP) to form a reliable persistent framework.
  • "AOP @ work: Comparison of AOP tools, Part 1" (Mik Kersten, developerworks, 1st): Compares Spring AOP and AOP frameworks.
  • "The secret to success in lightweight Development, Part 1: Spring exposure" (Bruce Tate, developerworks, 3rd): demonstrates the significance of spring as a lightweight container.
  • "Ruby on Rails and J2EE: Can they coexist ?" (Aaron rustad, developerworks, September July 2005): Compare the less-known J2EE framework alternatives, such as EJB and spring.
  • Java Technology Zone: there are hundreds of articles covering Java Web-based solutions.

Obtain products and technologies

  • Spring homepage: Download the Spring framework.

  • Ant homepage: Download Apache ant.

Discussion

  • Participate in Forum discussions.

  • Developerworks blogs: Join the developerworks community.

About the author

 

Naveen balani spent most of his time designing and developing J2EE-based frameworks and products. He has written various articles for IBM developerworks, topics covered include ESB, SOA, JMS, Web Service Architecture, CICs, axis, DB2, XML extender, WebSphere Studio, MQSeries, Java wireless devices, DB2 everyplace for Palm, j2s, MIDP, Java-Nokia, Visual Studio.. NET and wireless data synchronization. You can send an email to him. His address is naveenbalani@rediffmail.com.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.