Spring and struts1 integration solution (2)

Source: Internet
Author: User

The previous section describes how to use struts to implant the system separately, and how webapplicationcontext initializes in servlet containers. Generally, web applications can be easily used.

However, with the wide application of struts, integrating struts and spring is a problem to be faced. Spring also provides related struts classes, mainly using Org. springframework. web. struts. actionsupport, we only need to inherit our action from actionsupport, that is, we can call the getwebapplicationcontext () method in actionsupport to retrieve webapplicationcontext.

In this way, getbean is required in the action, just like in the previous section. The Code does not look concise enough. Therefore, Spring provides another method: Use spring to manage struts actions and use Org. springframework. web. struts. contextloaderplugin plug-in, which is loaded when struts is started, so that our actions can be managed like bean management.

The following shows only the modified Code. For the original code, see spring and hibernate integration spring and struts1 integration solution (1)

Struts-config.xml

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype Struts-config public "-// Apache Software Foundation // DTD struts configuration 1.3 // en" http://struts.apache.org/dtds/struts-config_1_3.dtd "> <Struts-config> <form-beans/> <global- exceptions/> <global-forwards/> <action-mappings> <! -- Use delegatingactionproxy to delegate the strut action to the spring container for management. Delegatingactionproxy is a subclass of action. It transfers the call request to the real action implementation --> <action Path = "/person/List" type = "org. springframework. web. struts. delegatingactionproxy "Validate =" false "parameter =" method "> <! -- JSP is deployed in the WEB-INF to prevent users from directly accessing JSP --> <forward name = "list" Path = "/WEB-INF/person/list. JSP "> </forward> </Action-mappings> <! -- Internationalization --> <message-resources parameter = "struts. applicationresources"/> <! -- Host struts action to spring container management and load actionservlet according to the configuration file of contextconfiglocation --> <plug-in classname = "org. springframework. web. struts. contextloaderplugin "> <set-Property =" contextconfiglocation "value ="/WEB-INF/action-servlet-person.xml "/> </plug-in> </Struts-config>

Action-servlet-person.xml

<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-Lazy-init = "true"> <! -- The class configured here is the path of the real action class and cannot be named by ID. The ID cannot contain special characters --> <bean name = "/person/List" class = "com. ch. action. personaction "> <property name =" personservice "ref =" personservice "/> </bean> </beans>

Personaction

Package COM. ch. action; import Java. util. list; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import Org. apache. struts. action. actionform; import Org. apache. struts. action. actionforward; import Org. apache. struts. action. actionmapping; import Org. apache. struts. actions. dispatchaction; import Org. springframework. orm. hibernate3.support. opensessioninviewfilter; import or G. springframework. web. context. contextloader; import COM. ch. dao. ipersonservice; import COM. ch. entity. person;/*** usually requires the same action in the design to process different requests sent by the client. * The dispatchaction class is used to solve these problems, configure and pass different request methods by Setting Parameter * @ author ch **/public class personaction extends dispatchaction {private ipersonservice personservice; @ overrideprotected actionforward unspecified (actionmapping mapping, actionform form, httpserv Letrequest request, httpservletresponse response) throws exception {// todo auto-generated method stubreturn list (mapping, form, request, response);} @ suppresswarnings ("unchecked ") public actionforward list (actionmapping mapping, actionform form, httpservletrequest request, httpservletresponse response) throws exception {// todo auto-generated method stublist <?> List = (list <person>) personservice. findallpersons (); Request. setattribute ("list", list); Return Mapping. findforward ("list");} public void setpersonservice (ipersonservice personservice) {This. personservice = personservice ;}}

Deployment running result:


Other integration methods:

1. Use org. springframework. Web. Struts. actionsupport (orDispatchactionsupport):

Spring's actionsupport inherits from org. Apache. Struts. action. Action. The subclass of actionsupport can be obtained.
Global variables of the webapplicationcontext type. You can get this variable through getwebapplicationcontext () and then get the bean object.

public class PersonAction extends org.springframework.web.struts.ActionSupport {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {// TODO Auto-generated method stubWebApplicationContext wc = getWebApplicationContext();IPersonService personService = (IPersonService)wc.getBean("personService");List<?> list = (List<Person>)personService.findAllPersons();request.setAttribute("list", list);return mapping.findForward("list");}}

2. Use delegatingrequestprocessor to forward the processing to the bean in the spring container:

Struts-config.xml

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype Struts-config public "-// Apache Software Foundation // DTD struts configuration 1.3 // en" http://struts.apache.org/dtds/struts-config_1_3.dtd "> <Struts-config> <form-beans/> <global- exceptions/> <global-forwards/> <action-mappings> <! -- Use delegatingactionproxy to delegate the strut action to the spring container for management. Delegatingactionproxy is a subclass of action, it transfers the call request to the real action implementation --> <action Path = "/person/List" Validate = "false" parameter = "method"> <! -- JSP is deployed in the WEB-INF to prevent users from directly accessing JSP --> <forward name = "list" Path = "/WEB-INF/person/list. JSP "> </forward> </Action-mappings> <controller processorclass =" org. springframework. web. struts. delegatingrequestprocessor "/> <! -- Internationalization --> <message-resources parameter = "struts. applicationresources"/> <! -- Host struts action to spring container management and load actionservlet according to the configuration file of contextconfiglocation --> <plug-in classname = "org. springframework. web. struts. contextloaderplugin "> <set-Property =" contextconfiglocation "value ="/WEB-INF/action-servlet-person.xml "/> </plug-in> </Struts-config>

After the Controller processorclass is configured as delegatingrequestprocessor (inherited from requestprocessor), Struts is told to use delegatingrequestprocessor to replace the original requestprocessor. Struts forwards the intercepted user requests to the corresponding bean in the spring context, match according to the bean name attribute. The struts action configuration does not need to configure the type attribute (even if the type attribute is configured, it does not work unless the corresponding name attribute bean cannot be found in the spring configuration file ).
3. You can port the configuration beans in the action-servlet-person.xml to applicationcontext. xml and load these beans through contextloaderlistener. In this way, you can remove the following code from the struts configuration file:

<! -- Host struts action to spring container management and load actionservlet according to the configuration file of contextconfiglocation --> <plug-in classname = "org. springframework. web. struts. contextloaderplugin "> <set-Property =" contextconfiglocation "value ="/WEB-INF/action-servlet-person.xml "/> </plug-in>

In fact, the functions of contextloaderlistener and contextloaderplugin overlap. They initialize spring configurations. The difference is that the bean loaded by contextloaderlistener and contextloaderplugin is not in the same webapplicationcontext. Pay attention to this when using the opensessioninview filter mode (the specific content will be introduced next time ).

Summary

  • There are three ways to integrate Struts with spring:Use spring actionsupport,Use spring's delegatingrequestprocessor class,Full authority.
  • The first method is to integrate the action of struts with actionsupport, so that struts and spring are coupled with a large number of codes (getwebapplicationcontext and getbean are required each time). The Code is not concise enough; the second method is similar to the third method. Action creation and object dependency injection are all completed by the IOC container. The second method is that the requestprocessor class has been proxies. If you want to implement your own implementation method (such as encoding processing), it is troublesome. Therefore, the third method is preferred.
  • The last two types of struts and spring integration apply Spring IoC to manage struts actions. As the name suggests, the two are agent objects. Familiar with Struts, you must know requestprocessor and action. Spring will go into the request chain at the page layer (by extending the requestprocessor and action classes in struts ), in order to pass the intercepted requests to the action instance managed by spring, so as to effectively link the page layer to the service layer.

  • 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.