Example Description: how to integrate Spring and Struts

Source: Internet
Author: User

This article describes how to integrate Spring and Struts with a simple example.

1. Struts and Spring

Struts represents the implementation of the second MVC Architecture. The most important component in Struts is ActionServlet, a subclass of Action and ActionForm. ActionServlet represents controller, it accepts requests based on the configuration file and forwards these requests to the corresponding ActionForm and Action subclass. ActionForm transfers user input data to Action. Action calls the business layer component to complete necessary operations and finally submits the data to view. ActionServlet uses a configuration file (struts-config.xml) to load the definition of the Action subclass to accept user requests, based on the request URL, the controller finds an action definition to accept this request, Struts component to process user requests, check the configuration file to complete the action.

Spring is a lightweight container that makes it easy to bind objects using an external XML configuration file. Each object can get a pointer to a dependent object by listing the JavaBean attribute, bind an XML configuration file to make the rest of the work easier. Dependency injection (DI) is a very powerful function. Spring supports pluggable transaction managers and provides more options for transaction management. it integrates the persistence architecture and provides a unified exception classification. Spring also provides a simple mechanism for aspect-oriented (AOP) programming.

2. Struts and Spring Integration

Integrating Struts applications into the Spring framework can adopt multiple methods. First, Spring is designed to solve actual JEE problems, such as complexity, low performance, testability, and others. Second, the Spring framework includes an AOP implementation that allows you to use the Aspect-Oriented Programming Technology. Third, the Spring framework can easily manage and coordinate Struts. Similar to Struts, spring also includes MVC implementation. Both architectures have advantages and disadvantages. Struts is the most important architecture of MVC. Many development teams have learned to develop high-quality software within the prescribed time limit by Struts, therefore, the development team would rather integrate Spring functions than switch to Spring MVC. The good news is that the Spring structure allows you to integrate the Struts Web framework, Spring-based business layer, and persistence layer, our method is to apply the ActionSupport class in Spring to integrate Struts.

3. Load the context of the application

First we need to use ContextLoaderPlugin Spring to load the context of the Spring application for Struts ActionServlet, simply add plug-in the struts-config.xml file, as shown in (1:

<? Xml version = "1.0" encoding = "ISO-8859-1 "? >
<! DOCTYPE struts-config PUBLIC

"-// Apache Software Foundation // DTD Struts Configuration 1.1 // EN"

Http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd>

<Struts-config>

<Form-beans>

<Form-bean name = "searchForm"

Type = "org. apache. struts. validator. DynaValidatorForm">

<Form-property name = "cardno" type = "java. lang. String"/>

</Form-bean>

</Form-beans>

<Global-forwards type = "org. apache. struts. action. ActionForward">

<Forward name = "welcome" path = "/welcome. do"/>

<Forward name = "searchEntry" path = "/searchEntry. do"/>

<Forward name = "searchSubmit" path = "/searchSubmit. do"/>

</Global-forwards>

<Action-mappings>

<Action path = "/welcome" forward = "/WEB-INF/pages/welcome.htm"/>

<Action path = "/searchEntry" forward = "/WEB-INF/pages/search. jsp"/>

<Action path = "/searchSubmit"

Type = "com. infotek. Creditcard. actions. SearchSubmit"

Input = "/searchEntry. do"

Validate = "true"

Name = "searchForm">

<Forward name = "success" path = "/WEB-INF/pages/detail. jsp"/>

<Forward name = "failure" path = "/WEB-INF/pages/search. jsp"/>

</Action>

</Action-mappings>

<Message-resources parameter = "ApplicationResources"/>

<Plug-in className = "org. apache. struts. validator. ValidatorPlugIn">

<Set-property = "pathnames" value = "/WEB-INF/validator-rules.xml,/WEB-INF/validation. xml"/>

</Plug-in>

<Plug-in className = "org. springframework. web. struts. ContextLoaderPlugIn"> (1)

<Set-property = "contextConfigLocation" value = "/WEB-INF/beans. xml"/>

</Plug-in>

</Struts-config>


4. Use the Spring ActionSupport class

To integrate Struts with Spring, you must create a Spring context. Org. springframework. web. struts. the ActionSupport class provides a getWebApplicationContext () method to easily obtain the Spring context. All you need to do is to extend your Action from the Spring ActionSupport instead of the action class in Struts, as shown below:

Package com. infotek. Creditcard. actions;
Import java. io. IOException;

Import javax. servlet. ServletException;

Import javax. servlet. http. HttpServletRequest;

Import javax. servlet. http. HttpServletResponse;

Import org. apache. struts. action. ActionError;

Import org. apache. struts. action. ActionErrors;

Import org. apache. struts. action. ActionForm;

Import org. apache. struts. action. ActionForward;

Import org. apache. struts. action. ActionMapping;

Import org. apache. struts. action. DynaActionForm;

Import org. springframework. context. ApplicationContext;

Import org. springframework. web. struts. ActionSupport;

Import com. infotek. Creditcard. beans. Creditcard;

Import com. infotek. Creditcard. business. CreditcardService;

Public class SearchSubmit extends ActionSupport {| (1)

Public ActionForward execute (ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

Throws IOException, ServletException {

DynaActionForm searchForm = (DynaActionForm) form;

String isbn = (String) searchForm. get ("cardno ");

// The old fashion way

// CreditcardService creditcardService = new CreditcardServiceImpl ();

ApplicationContext ctx = getWebApplicationContext (); | (2)

CreditcardService creditcardService =

(CreditcardService) ctx. getBean ("creditcardService"); | (3)

CreditCard creditard = CreditCardService. read (cardno. trim ());

If (null = creditard ){

ActionErrors errors = new ActionErrors ();

Errors. add (ActionErrors. GLOBAL_ERROR, new ActionError ("message. notfound "));

SaveErrors (request, errors );

Return mapping. findForward ("failure ");

}

Request. setAttribute ("creditcard", creditcard );

Return mapping. findForward ("success ");

}

}


In (1), we create an Action by extending the Spring ActionSupport class instead of the Struts action class; in (2), we use the getWebApplicationContext () method to obtain an ApplicationContext; in (3), we use ApplicationContext to search for Spring bean. This technology is easy to understand. Unfortunately, it binds Struts action to Spring framework, if you want to replace Spring, you have to rewrite the code, and the Struts action is not under the control of Spring. Unfortunately, this method cannot benefit from Spring AOP.

5. Conclusion

In this article, we try to use Spring ActionSupport and ContextLoaderPlugIn to integrate Struts, which is the most efficient and simple way, in addition, you can use the proxy subclass in Spring to proxy RequestProcessor in Struts and actions of Struts.

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.