Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring to better handle Struts actions

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use Spring to better deal with Struts actions, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

George Franciscus, co-author of Struts Recipes, will introduce another major Struts integration trick-this time to import Struts applications into the Spring framework. Follow George, who will show you how to change Struts actions so that managing Struts actions is like managing Spring beans. The result is an enhanced web framework that can easily take advantage of Spring AOP.

You must have heard of the inversion of Control (IOC) design pattern, because information about it has been circulating for a long time. If you have ever used the Spring framework in any function, then you know how it works. In this article, I use this principle to inject a Struts application into the Spring framework, and you will see first-hand the power of the IOC pattern.

Integrating a Struts application into the Spring framework has many advantages. First, Spring is designed to solve real-world problems about JEE, such as complexity, low performance, testability, and so on. Second, the Spring framework includes an AOP implementation that allows you to apply aspect-oriented techniques to object-oriented code. Third, some people might say that the Spring framework can only handle Struts better than Struts can handle itself. But it's a matter of opinion, and after I demonstrate three ways to integrate Struts applications into the Spring framework, it's up to you to decide which one to use.

The methods I demonstrate are relatively simple to implement, but they have significantly different advantages. I have created a separate and available example for each method so that you can fully understand each method. See the download section for the complete example source code. See Resources to download the Struts MVC and Spring frameworks.

Why is Spring so great?

Rod Johnson, the founder of Spring, takes a critical view of Java ™enterprise software development and proposes that many enterprise problems can be solved through the strategic use of the IOC pattern (also known as dependency injection). When Rod and a dedicated team of open source developers put this theory into practice, the result was the Spring framework. In short, Spring is a lightweight container that allows you to easily connect objects together using an external XML configuration file. Each object can receive a reference to the dependent object by displaying a JavaBean property, leaving you with a simple task of concatenating them in a XML configuration file.

Dependency injection is a powerful feature, but the Spring framework provides more. Spring supports pluggable transaction managers to provide a wider range of options for your transaction processing. It integrates a leading persistence framework and provides a consistent exception hierarchy. Spring also provides a simple mechanism for using aspect-oriented code instead of normal object-oriented code.

Spring AOP allows you to use interceptors to intercept application logic at one or more execution points. Strengthening the logging logic of the application in the interceptor results in a more readable and practical code base, so interceptors are widely used in logging. As you'll soon see, Spring AOP has released its own interceptor to address crosscutting concerns, or you can write your own interceptor.

Integrate Struts and Spring

Like Struts, Spring can be implemented as a MVC. Both frameworks have their own advantages and disadvantages, although most people agree that Struts is still the best in terms of MVC. Many development teams have learned to use Struts as a basis for building high-quality software when time is tight. Struts is so driven that the development team would rather integrate the features of the Spring framework than convert it to Spring MVC. No need for conversion is good news for you. The Spring architecture allows you to connect Struts as a Web framework to the Spring-based business and persistence layer. The end result is that everything is now in place.

In the next tips, you will learn about three ways to integrate Struts MVC into the Spring framework. I will reveal the shortcomings of each method and compare their advantages. Once you understand the effects of all three methods, I'll show you an exciting application that uses my favorite of the three.

Three tips

Each of the following integration techniques (or tricks) has its own advantages and characteristics. I prefer one of them, but I know that all three can deepen your understanding of Struts and Spring. This will give you a wide range of options when dealing with a variety of situations. The methods are as follows:

Integrate Structs using Spring's ActionSupport class

Overwrite the RequestProcessor of Struts with Spring's DelegatingRequestProcessor

Delegate Struts Action management to the Spring framework

Load the application environment

No matter which technology you use, you need to use Spring's ContextLoaderPlugin to load the Spring application environment for Struts's ActionServlet. Just like adding any other plug-in, simply add the plug-in to your struts-config.xml file, as follows:

As mentioned earlier, in the download section, you can find the complete source code for these three fully usable examples. Each example provides a different approach to integrating Struts and Spring for a book search application. You can see the main points of the example here, but you can also download the application to see all the details.

Tip 1. ActionSupport using Spring

Manually creating a Spring environment is the most intuitive way to integrate Struts and Spring. To make it easier, Spring provides some help. For easy access to the Spring environment, the org.springframework.web.struts.ActionSupport class provides a getWebApplicationContext () method. All you do is extend your action from Spring's ActionSupport instead of the Struts Action class, as shown in listing 1:

Listing 1. Integrate Struts with ActionSupport

Package ca.nexcel.books.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 ca.nexcel.books.beans.Book

Import ca.nexcel.books.business.BookService

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 ("isbn")

/ / the old fashion way

/ / BookService bookService = new BookServiceImpl ()

ApplicationContext ctx =

GetWebApplicationContext (); | (2)

BookService bookService =

(BookService) ctx.getBean ("bookService"); | (3)

Book book = bookService.read (isbn.trim ())

If (null = = book) {

ActionErrors errors = new ActionErrors ()

Errors.add (ActionErrors.GLOBAL_ERROR,new ActionError

("message.notfound"))

SaveErrors (request, errors)

Return mapping.findForward ("failure")

}

Request.setAttribute ("book", book)

Return mapping.findForward ("success")

}

}

Let's think quickly about what's going on here. At (1), I created a new Action by extending from Spring's ActionSupport class instead of Struts's Action class. At (2), I use the getWebApplicationContext () method to get an ApplicationContext. To get business services, I use the environment I got at (2) to find a Spring bean at (3).

This technique is simple and easy to understand. Unfortunately, it couples Struts actions with the Spring framework. If you want to replace Spring, you must rewrite the code. And, because the Struts action is not under the control of Spring, it cannot gain the advantage of Spring AOP. This technique may be useful when using multiple independent Spring environments, but in most cases it is not as appropriate as the other two.

Tip 2. Override RequestProcessor

Separating Spring from Struts actions is a more ingenious design choice. One way to separate is to use the org.springframework.web.struts.DelegatingRequestProcessor class to override Struts's RequestProcessor handler, as shown in listing 2:

Listing 2. Integration through Spring's DelegatingRequestProcessor

Type= "ca.nexcel.books.actions.SearchSubmit"

Input= "/ searchEntry.do"

Validate= "true"

Name= "searchForm" >

| (1)

I used tags to override the default Struts RequestProcessor with DelegatingRequestProcessor. The next step is to register the action in my Spring configuration file, as shown in listing 3:

Listing 3. Register an action in the Spring configuration file

| (1)

Note: at (1), I registered a bean with the name attribute to match the struts-config action mapping name. The SearchSubmit action reveals a JavaBean attribute that allows Spring to populate the property at run time, as shown in listing 4:

Listing 4. Struts action with JavaBean attribute

Package ca.nexcel.books.actions

Import java.io.IOException

Import javax.servlet.ServletException

Import javax.servlet.http.HttpServletRequest

Import javax.servlet.http.HttpServletResponse

Import org.apache.struts.action.Action

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 ca.nexcel.books.beans.Book

Import ca.nexcel.books.business.BookService

Public class SearchSubmit extends Action {

Private BookService bookService

Public BookService getBookService () {

Return bookService

}

Public void setBookService (BookService bookService) {| (1)

This.bookService = bookService

}

Public ActionForward execute (

ActionMapping mapping

ActionForm form

HttpServletRequest request

HttpServletResponse response)

Throws IOException, ServletException {

DynaActionForm searchForm = (DynaActionForm) form

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

Book book = getBookService () .read (isbn.trim ()) | (2)

If (null = = book) {

ActionErrors errors = new ActionErrors ()

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

SaveErrors (request, errors)

Return mapping.findForward ("failure")

}

Request.setAttribute ("book", book)

Return mapping.findForward ("success")

}

}

In listing 4, you can see how to create a Struts action. At (1), I created a JavaBean attribute. DelegatingRequestProcessor automatically configures this property. This design makes the Struts action unaware that it is being managed by Spring and enables you to take advantage of all the advantages of Sping's action management framework. Because your Struts actions don't notice the existence of Spring, you don't need to rewrite your Struts code to replace Spring with other control reversal containers.

It is true that the DelegatingRequestProcessor method is better than the first, but there are still some problems. If you use a different RequestProcessor, you need to manually integrate Spring's DelegatingRequestProcessor. The added code can cause maintenance problems and reduce the flexibility of your application in the future. In addition, there have been rumors of using a series of commands instead of Struts RequestProcessor. This change will have a negative impact on the life of this solution.

Tip 3. Delegate action management to Spring

A better solution is to delegate Strut action management to Spring. You can do this by registering an agent in the struts-config action map. The agent is responsible for finding Struts actions in the Spring environment. Because the action is under the control of Spring, it can populate the JavaBean property of the action and make it possible to apply features such as Spring's AOP interceptor.

The Action class in listing 5 is the same as in listing 4. But struts-config has some differences:

Listing 5. Delegate method for Spring integration

Type= "org.springframework.web.struts.DelegatingActionProxy" | (1)

Input= "/ searchEntry.do"

Validate= "true"

Name= "searchForm" >

Listing 5 is a typical struts-config.xml file with one small difference. It registers the name of the Spring proxy class instead of the class name that declares the action, as shown in (1). The DelegatingActionProxy class uses the action map name to find actions in the Spring environment. This is the environment in which we use ContextLoaderPlugIn declarations.

Registering a Struts action as a Spring bean is straightforward, as shown in listing 6. I simply created a bean using the action mapping using the tag's name attribute (in this case, "/ searchSubmit"). The JavaBean attribute of this action is populated like any Spring bean:

Listing 6. Register a Struts action in the Spring environment

The advantages of action delegation

Action delegation solution is the best of the three methods. The Struts action does not understand Spring and can be used in non-Spring applications without making any changes to the code. Changes to RequestProcessor will not affect it, and it can take advantage of Spring AOP features.

The advantages of action delegation are more than that. Once you let Spring control your Struts actions, you can use Spring to add more energy to your actions. For example, without Spring, all Struts actions must be thread-safe. If you set the singleton property of the tag to "false", your application will have a newly generated action object on each request, regardless of the method. You may not need this feature, but it's also good to have it in your toolbox. You can also take advantage of Spring's lifecycle approach. For example, when a Struts action is instantiated, the init-method attribute of the tag is used to run a method. Similarly, the destroy-method property executes a method before removing the bean from the container. These methods are good ways to manage expensive objects, which are managed in the same way as the Servlet lifecycle.

Intercept Struts

As mentioned earlier, one of the main advantages of integrating Struts and Spring by delegating Struts actions to the Spring framework is that you can apply Spring's AOP interceptor to your Struts actions. By applying the Spring interceptor to the Struts action, you can handle crosscutting concerns with minimal cost.

Although Spring provides many built-in interceptors, I'll show you how to create your own interceptor and apply it to a Struts action. In order to use the interceptor, you need to do three things:

Create an interceptor.

Register the interceptor.

Declare where to intercept the code.

These seemingly simple words are very powerful. For example, in listing 7, I created a logging interceptor for the Struts action. This interceptor prints a sentence before each method call:

Listing 7. A simple logging interceptor

Package ca.nexcel.books.interceptors

Import org.springframework.aop.MethodBeforeAdvice

Import java.lang.reflect.Method

Public class LoggingInterceptor implements MethodBeforeAdvice {

Public void before (Method method, Object [] objects, Object o) throws Throwable {

System.out.println ("logging before!")

}

}

This interceptor is very simple. The before () method runs before each method in the intercept point. In this case, it prints out a sentence that can actually do whatever you want. The next step is to register the interceptor in the Spring configuration file, as shown in listing 8:

Listing 8. Register interceptors in the Spring configuration file

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report