Part 25th _struts2.1 and Spring integration

Source: Internet
Author: User

After dependency injection, the method is called automatically before the object is destroyed:

We can learn about the timing of dependency injection by outputting related statements in the Setxxx () method, similar to the previous code of the spring project, which can be performed automatically after dependency injection is completed.

If we want an instance of a class to automatically execute certain methods after all the properties have been set, there are two ways:

    • Implement the Initializingbean interface, and implement the only method inside the Afterpropertiesset (), this method will be called automatically after all the attributes are injected.
    • Define a method of any name in the class (such as Init ()) and add init-method= "init" to the bean tag of the corresponding class in Applicationcontext.xml. (The init name specified earlier)

Spring official documentation recommends using the latter, so that the custom class does not have a relationship with spring as much as possible (coupling), because spring advocates the principle of minimizing the coupling between interfaces, which spring claims to be non-intrusive, That is, the whole program does not feel the existence of spring, just need to configure the relevant information in the configuration file, spring can be a separate bean to assemble a series of interrelated objects.

There is initialization to destroy, implement the only abstract method in the Disposablebean interface Destroy () or configure the Destroy-method property to be automatically called before the object is destroyed.

For spring's Bean Factory (IoC) This block is temporarily over.

Let's take a look at how the front-end framework struts and the one-stop framework spring (itself provides support for MVC, Spring MVC, the reason why this is not said because it is used in a lot of foreign, but in the domestic use of relatively few) organic integration.

Start by creating a new Web Project named Strutsspring.

1. First complete the struts-related configuration and copy the previous project's struts.xml to the SRC directory.

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public    "-//apache software foundation//dtd struts Configuration 2.0//en"    "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts><package name=" strutsspring "extends=" Struts-default " ></package></struts>

2. Copy struts dependent six jar files plus IO jar Package A total of seven jar files into the Web-inf lib directory.

3. Configure the configuration in Web. XML to support struts (also adds support for spring, as described later).

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">    <filter>  <filter-name>struts2</ filter-name>  <filter-class>  Org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  </filter-class>  </ filter>    <filter-mapping>  <filter-name>struts2</filter-name>  <url-pattern >/*</url-pattern>  </filter-mapping>    <listener>  <listener-class>  Org.springframework.web.context.ContextLoaderListener  </listener-class>  </listener>  </web-app>

4. After completing the above steps, the current project is a typical struts project. Next, configure its contextpath to Tomcat (Server.xml).

<context path= "/strutsspring" docbase= "D:\JavaWeb\strutsspring\WebRoot" reloadable= "true"/>

Start the server, Access localhost:8080/strutsspring, the page pops up this is my JSP page. That's the success.

The following is the introduction of spring support, since it is now a Web project, more than the usual Java application introduced in the package.

Select the project, Myeclipse->add spring capabilities, select Spring version for Spring 2.5,jar package Select Spring 2.5 AOP Libraries, Spring 2.5 Core Li Braries, Spring 2.5 Web Libraries,jar Library Installation Select Copy checked library contents to project folder, click Next, Remove Enabl E AOP builder in front of the tick, then change src to Webroot/web-inf in folder, click Finish.

So far, struts and spring are all included in the project, and the next thing to do is to glue them together in two steps:

    • The spring plug-in for struts is also added to the Web-inf Lib directory. There is a struts2-spring-plugin-2.1.6.jar in the Lib directory under struts2.1.6 downloaded from the official website. This action is created, destroyed, and so on by the spring management, struts will let go of the matter. What is this for? Came to Struts2-core-2.1.6.jar below, there is a org.apache.struts2, under which there is a default.properties: In line 36-39 has been commented out text:
# # If specified, the default object factory can be overridden here### Note:short-hand notation are supported in some case s, such as "Spring" # # #       Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here# Stru Ts.objectfactory = Spring

There is a struts-plugin.xml in Struts-spring-plugin-2.1.6.jar that has a place where spring's object factory is enabled:

<!--make  the Spring object factory the automatic default--and    <constant name= "Struts.objectfactory" Value= "Spring"/>
    • Add a Spring startup class in Web. XML (the previous version is started with a filter, and later versions are started with a listener: The server starts, the Listener class is instantiated)
        <listener>  <listener-class>  Org.springframework.web.context.ContextLoaderListener  < /listener-class>  </listener>

Until now, the pre-deployment of the integration work is counted to end.

Restart the server and you can see a line of information in the output:

Info: Initializing Spring root Webapplicationcontext

Looking at the API documentation for spring, Webapplicationcontext implements the Beanfactory interface.

Now, let's integrate these two frameworks to see how the middle process is done.

New login.jsp (introduced Struts tag library <%@ taglib uri= "/struts-tags" prefix= "S"%>):

<body>  action= "Login" >  <s:textfield name= "username" size= "<s:form" label= "username" > </s:textfield>  <s:textfield name= "password" size= "label=" ></s:textfield>    <s:submit value= "Submit" ></s:submit>  </s:form>  </body>

Then create a new package com.test.action, under which the new class Loginaction (the service Interface is added):

Package Com.test.action;import Com.opensymphony.xwork2.actionsupport;import Com.test.service.loginservice;import Com.test.service.impl.loginserviceimpl;public class Loginaction extends actionsupport{private String username; Private String password;private loginservice loginservice;public loginservice getloginservice () {return loginservice;} public void Setloginservice (Loginservice loginservice) {this.loginservice = Loginservice;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} @Overridepublic String Execute () throws exception{//Note: The business logic should never be written in action, and in action it should only be done with some upfront processing such as data validation and type conversion. The business logic layer of the backend is entered only after the legal data has been processed in the prophase. If there is no spring can consider this write (disadvantage: interface and implementation coupling in a piece)://Loginservice = new Loginserviceimpl ();//Loginservice.islogin (username, password); if (Loginservice.islogin (username, password)) {return SUCCESS;} else {return ERROR;}}}

Business logic Processing-New package Com.test.service, new interface Loginservice below:

Package Com.test.service;public Interface Loginservice{public Boolean IsLogin (string username, string password);}

Create a new Com.test.service.impl package, write the implementation class for the Service interface Loginserviceimpl (complete the real business process):

Package Com.test.service.impl;import com.test.service.loginservice;/** * This class completes real business processing * @author ASUS * */public class Logi Nserviceimpl Implements Loginservice{public Boolean IsLogin (string username, string password) {if ("Hello". Equals ( username) && "World". Equals (password)) {return true;} Else{return false;}}}

The implementation class is defined, and eventually it must be called by the action, how do we let the action know that it's what spring did for us?

    • Declare what service interface it needs in loginaction.
    • Then configure in Struts.xml (note that the class attribute in action is no longer com.test.action.LoginAction):
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public    "-//apache software foundation//dtd struts Configuration 2.0//en"    "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts><package name=" strutsspring "extends=" Struts-default " ><!--Loginaction is a name declared in the Bean's ID in spring applicationcontext.xml--><action name= "Login" class= " Loginaction "> <result name=" Success ">/success.jsp</result><result name=" error ">/error.jsp </result></action></package></struts>

Configure in Applicationcontext.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><beansxmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd "><bean id=" Loginservice "class=" Com.test.service.impl.LoginServiceImpl "></bean ><bean id= "loginaction" class= "com.test.action.LoginAction" ><property name= "Loginservice" ref= " Loginservice "></property></bean></beans>

The Execute method in Loginaction:

@Overridepublic String Execute () throws exception{//Note: The business logic should never be written in action, and in action it should only be done with some upfront processing such as data validation and type conversion. The business logic layer of the backend is entered only after the legal data has been processed in the prophase. If there is no spring can consider this write (disadvantage: interface and implementation coupling in a piece)://Loginservice = new Loginserviceimpl ();//Loginservice.islogin (username, password); if (Loginservice.islogin (username, password)) {return SUCCESS;} else {return ERROR;}}

Supplemental success.jsp (Introduction tag library) and error.jsp:

  <body>    username:<s:property value= "username"/><br/>    password:<s:property value= " Password "/>  </body>

ERROR.JSP:

  <body>    Login Error!!!  </body>

Restart the service, test input Hello World Display success.jsp page corresponding information, otherwise output error message login error!!!

Additional notes:

Since Loginserviceimpl is a stateless class, there are no attributes, only methods, and new how many times have not changed, Therefore, you need to add a scope attribute to the Applicationcontext.xml bean (note: For action, be sure to configure it as prototype or request):

<bean id= "Loginservice" class= "Com.test.service.impl.LoginServiceImpl" scope= "Singleton" ></bean>< Bean id= "loginaction" class= "Com.test.action.LoginAction" scope= "prototype" >

In addition, if scope is not configured, its default value is singleton, so configuring scope affects the correctness of the program in addition to its efficiency.

For the bean element of spring's configuration file, its Scope property has the following values:

    1. Singleton, single case.
    2. Prototype, which indicates that a new instance is generated each time the bean is removed from the container. Equivalent to a new object.
    3. Request, the property is Web-based, indicating that a new instance is generated each time a request is accepted. In this case, the request is the same as prototype.
    4. Session, which indicates that there is only one object in each session.
    5. Globalsession.

Part 25th _struts2.1 and Spring integration

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.