JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Struts Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

Struts Interview Questions and FAQs – 1

Q:What is Struts?

A:The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.

Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as
most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.

Q:What is Jakarta Struts Framework?

A:Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

Q:What is ActionServlet?

A:The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

Q:How you will make available any Message Resources Definitions file to the Struts Framework Environment?

A:T Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.

Example:

[code lang=”html”]<message-resources parameter=\"MessageResources\" />[/code]

Q:What is Action Class?

A:The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Q:What is ActionForm?

A:An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

Q:What is Struts Validator Framework?

A:Struts Framework provides the functionality to validate
the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

Q:Give the Details of XML files used in Validator Framework?

A:The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Q:How you will display validation fail errors on jsp page?

A:Following tag displays all the errors:

[code lang=”html”]<html:errors/>[/code]

Q:How you will enable front-end validation based on the xml in validation.xml?

A:The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code:

[code lang=”html”]<html:javascript formName=\"logonForm\" dynamicJavascript=\"true\" staticJavascript=\"true\" />[/code]

generates the client side java script for the form \”logonForm\” as defined in the validation.xml file. The
<html:javascript> when added in the jsp file generates the client site validation script.

Q:How to get data from the velocity page in a action class?

A:We can get the values in the action classes by using data.getParameter(\”variable name defined in the velocity page\”);

Filed Under: Interview Questions Tagged With: Struts

Struts 2.0 and Spring

October 2, 2008 by Krishna Srinivasan Leave a Comment

In this post, I will describe how to do the same using Struts 2.0. The only major step that needs to be done here is to override the default Struts 2.0 OjbectFactory. Changing the ObjectFactory to Spring give control to Spring framework to instantiate action instances etc. Most of the code is from the previous post, but I will list only the additional changes here.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

1)Changing the default Object factory: In order to change the Ojbect factory to Spring, you have to add a declaration in the struts.properties file.

[code lang=”java”]
struts.objectFactory = spring
struts.devMode = true
[/code]

2)The Action class: Here is the code for the action class

[code lang=”java”]
package actions;

import java.util.List;

import business.BusinessInterface;

import com.opensymphony.xwork2.ActionSupport;

public class SearchAction extends ActionSupport {
private BusinessInterface businessInterface;

private String minSalary;

private String submit;

private List data;

public String getSubmit() {
return submit;
}

public void setSubmit(String submit) {
this.submit = submit;
}

public BusinessInterface getBusinessInterface() {
return businessInterface;
}

public String execute() throws Exception {
try {
long minSal = Long.parseLong(getMinSalary());
System.out.println("Business Interface: " + businessInterface + "Minimum salary : " + minSal);
data = businessInterface.getData(minSal);
System.out.println("Data : " + data);

} catch (Exception e) {
e.printStackTrace();
}

return SUCCESS;
}

public void setBusinessInterface(BusinessInterface bi) {
businessInterface = bi;
}

public String getMinSalary() {
return minSalary;
}

public void setMinSalary(String minSalary) {
this.minSalary = minSalary;
}

public List getData() {
return data;
}

public void setData(List data) {
this.data = data;
}
}
[/code]

  • The Action class here does not have access to the HttpServetRequest and HttpServletResponse. Hence the action class itself was changed to the session scope for this example (see below)
  • In order for the action class to be aware of the Http Session, the action class has to implement the ServletRequestAware interface, and define a setServletRequest method, which will be used to inject the ServletRequest into the action class.
  • The BusinessInterface property is injected by Spring framework.

3)The struts Configuration:

[code lang=”html”]
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="Struts2Spring" namespace="/actions" extends="struts-default">
<action name="search" class="actions.SearchAction">
<result>/search.jsp</result>
</action>
</package>
</struts>
[/code]
The action’s class attribute has to map the id attribute of the bean defined in the spring bean factory definition.

4)The Spring bean factory definition:

[code lang=”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-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
default-autowire="autodetect">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:orcl</value>
</property>
<property name="username">
<value>scott</value>
</property>
<property name="password">
<value>tiger</value>
</property>
</bean>

<!– Configure DAO –>
<bean id="empDao" class="data.DAO">
<property name="dataSource">
<ref bean="dataSource"></ref>
</property>
</bean>
<!– Configure Business Service –>
<bean id="businessInterface" class="business.BusinessInterface">
<property name="dao">
<ref bean="empDao"></ref>
</property>
</bean>
<bean id="actions.SearchAction" name="search" class="actions.SearchAction" scope="session">
<property name="businessInterface" ref="businessInterface" />
</bean>
</beans>
[/code]

  • The bean definition for the action class contains the id attribute which matches the class attribute of the action in struts.xml
  • Spring 2’s bean scope feature can be used to scope an Action instance to the session, application, or a custom scope, providing advanced customization above the default per-request scoping.

5)The web deployment descriptor:

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Struts2Spring</display-name>

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</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>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
[/code]
The only significant addition here is that of the RequestContextListener. This listener allows Spring framework, access to the HTTP session information.

6)The JSP file: The JSP file is shown below. The only change here is that the action class, instead of the Data list is accessed from the session.
[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://displaytag.sf.net" prefix="display"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page import="actions.SearchAction,beans.Employee,business.Sorter,java.util.List,org.displaytag.tags.TableTagParameters,org.displaytag.util.ParamEncoder"%>
<html>
<head>
<title>Search page</title>
<link rel="stylesheet" type="text/css" href="/StrutsPaging/css/screen.css" />
</head>
<body bgcolor="white">
<s:form action="/actions/search.action">
<table>
<tr>
<td>Minimum Salary:</td>
<td><s:textfield label="minSalary" name="minSalary" /></td>
</tr>
<tr>
<td colspan="2"><s:submit name="submit" /></td>
</tr>
</table>
</s:form>
<jsp:scriptlet>

SearchAction action = (SearchAction)session.getAttribute("actions.SearchAction");
session.setAttribute("empList", action.getData());
if (session.getAttribute("empList") != null) {
String sortBy = request.getParameter((new ParamEncoder("empTable")).encodeParameterName(TableTagParameters.PARAMETER_SORT));
Sorter.sort((List) session.getAttribute("empList"), sortBy);

</jsp:scriptlet>

<display:table name="sessionScope.empList" pagesize="4" id="empTable" sort="external" defaultsort="1" defaultorder="ascending" requestURI="">
<display:column property="empId" title="ID" sortable="true" sortName="empId" headerClass="sortable" />
<display:column property="empName" title="Name" sortName="empName" sortable="true" headerClass="sortable" />
<display:column property="empJob" title="Job" sortable="true" sortName="empJob" headerClass="sortable" />
<display:column property="empSal" title="Salary" sortable="true" headerClass="sortable" sortName="empSal" />
</display:table>
<jsp:scriptlet>
}
</jsp:scriptlet>

</body>
</html:html>
[/code]

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

7)The Other required classes: The following other classes have been used for the example, and they can be obtained from the previous posts (1, 2).

  • Employee.java
  • BusinessInterface.java
  • Sorter.java
  • DAO.java
  • EmpMapper.java

Filed Under: Spring Framework Tagged With: Spring Integration, Struts, Struts Integration

Integrating Struts With Spring

May 15, 2007 by Krishna Srinivasan Leave a Comment

This article explains how to integrating struts with spring. Struts is more established and more stable MVC2 framework at this time so if your application is based on Struts framework you may forget about thinking to move to some other framework. But at the same time you must have heard about the buzz created by Inversion of Control (IOC) design pattern. This design pattern is implemented by Spring framework. Besides there are some more amazing features of Spring like AOP. So if you like to take advantage of these features of Spring you do not have to rebuild the application, but you can integrate your existing Struts application with Spring without much hassle. More about that latter but first we would like to have a look at new features of Spring and how they work.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

If you are beginner for spring framework, please read our article on introduction to spring framework, spring aop, spring mvc. Javabeat covers extensive articles on the spring framework. If you are interested in receiving the updates, please subscribe here.

What’s new in Spring?

Spring implements the IOC design pattern. It is a lightweight container and the objects are managed using an external XMl configuration file. Reference to a dependent object is obtained by exposing a JavaBean property. You just have to enter the properties in the external XML file.

Spring and IOC

IOC is a design pattern that externalizes application logic so that it can be injected into client code rather than written into it. Use of IOC in Spring framework separates the implementation logic from the client.

Spring framework offers more than this. The transaction handling is done beautifully in Spring. It can integrate major persistence frameworks and offer a consistent exception hierarchy. The best part of Spring is the mechanism of aspect-oriented code instead of the usual object-oriented code.

Spring AOP provides us with interceptors which are used to intercept the application logic at any execution point and then apply some methods at the interceptors. They are widely used for logging resulting in a more readable and functional code.

Advantages of integrating Struts with Spring:

The advantages of integrating a Struts application into the Spring framework are:

  1. Spring framework is based on new design approach and was designed to resolve the existing problems of existing Java applications such as performance.
  2. Spring framework lets you apply AOP (aspect-oriented programming technique) rather than object-oriented code.
  3. Spring provides more control on struts actions. That may depend on the method of integration you choose.

If you have decided to integrate your Struts application into Spring, we are ready to begin.
There are three ways of doing this and based on the scenarios in your application you can select the way you want to do it.

  1. Using Spring’s ActionSupport class to integrate Struts.
  2. Using ContextLoaderPlugin.

1) Using Spring’s ActionSupport class to integrate Struts.

Integrating Struts with Spring doesn’t sound to be easy but if you follow this method you will find it quite simple and to add to this Spring provides you with org.springframework.web.struts.ActionSupport class. This class provides a method getWebApplicationContext() which you can use to obtain the Spring context. So you just have to extend Spring’s ActionSupport from your strut’s actions.

Using ActionSupport to integrate Struts

[code lang=”java”]
package net.javabeat.example1.actions;

import java.io.IOException;
import javax.servlet.*;
import org.apache.struts.action.*;
import org.springframework.context.ApplicationContext;
import org.springframework.web.struts.ActionSupport;

import net.javabeat.example1.beans.Employee;
import net.javabeat.example1.business.EmpSearchService;

public class SubmitSearch extends ActionSupport {

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

DynaActionForm searchEmpForm = (DynaActionForm) form;
String empId = (String) searchEmpForm.get("empId");

ApplicationContext ctx = getWebApplicationContext();
EmpSearchService empSearchService = EmpSearchService) ctx.getBean("EmpSearchSercvice");
Employee employee = empSearchService.find(empId.trim());

if (null == employee) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("message.empnotfound"));
saveErrors(request, errors);
return mapping.findForward("failure") ;
}
request.setAttribute("employee", employee);
return mapping.findForward("success");
}
}
[/code]

Explanation:

The trick here is to extend your Action from the Spring ActionSupport and not from the Struts Action class. The Spring ActionSupport provides you with the method getWebApplicationContext() to obtain an ApplicationContext and from the ApplicationContext you can access the business service layer.

[code lang=”java”]
ApplicationContext ctx = getWebApplicationContext();
//getWebApplicationContext provided by the Spring ActionSupport class
EmpSearchService empSearchService = (EmpSearchService) ctx.getBean("EmpSearchSercvice");
// From the ApplicationContext get the business service bean
[/code]

Disadvantages:

This method involves changes in the java files of your application, which is not desirable because if you want to move your application back to Struts framework you will have to redo the changes in the java files. And in this method the Struts actions are not in complete control of Spring.

2) Using ContextLoaderPlugin provided with Spring.

ContextLoaderPlugin is provided with Spring’s 1.0.1 release. This plug-in loads the Spring application context for Strut’s applications ActionServlet.There are two methods of integrating Struts with Spring using this plug-in and these two methods are:

  • A) Overriding the Struts RequestProcessor with Spring’s DelegatingRequestProcessor.
  • B) Delegate Struts Action management to the Spring framework.

To use the ContextLoaderPlugin loads the Spring context file for the Struts ActionServlet. To use this plug-in you have to add following to your struts config file:

[code lang=”xml”]
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"/>
[/code]

The location of the context config file can be set through contextConfigLocation property.

[code lang=”xml”]
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/actionname-servlet.xml” />
</plug-in>
[/code]

The default location for the Context config file is /WEB-INF/actionname-servlet.xml.

A)Overriding the Struts RequestProcessor with Spring’s DelegatingRequestProcessor.

One way of using ContextLoaderPlugIn is to override the Struts RequestProcessor with Spring’s DelegatingRequestProcessor class. The Spring’s DelegatingRequestProcessor will lookup the Struts Actions defined in
ContextLoaderPlugIn’s WebApplicationContext. You can either use a single ContexLoaderPlugIn for all your Struts modules and then load the context in all your Struts modules or you can also define seperate ContextLoaderPlugIn
for each of your Struts modules and then use the contextConfigLocation parameter to load the appropriate XML file.
Let us have a look at it.

Integration via Spring’s DelegatingRequestProcessor

[code lang=”xml”]
<?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="searchEmpForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="empId" type="java.lang.String"/>
</form-bean>
</form-beans>
<global-forwards type="org.apache.struts.action.ActionForward">
<forward name="welcome” path="/index.do"/>
<forward name="searchEmployee" path="/searchEmp.do"/>
<forward name="submitSearch" path="/submitSearch.do"/>
</global-forwards>
<action-mappings>
<action path="/welcome" forward="/WEB-INF/views/welcome.htm"/>
<action path="/searchEmployee" forward="/WEB-INF/views/search.jsp"/>
<action path="/submitSearch"
type="net.javabeat.example1.books.actions.SubmitSearch"
input="/searchEmployee.do"
validate="true"
name="searchEmpForm">
<forward name="success" path="/WEB-INF/views/empDetail.jsp"/>
<forward name="failure" path="/WEB-INF/views/search.jsp"/>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources"/>
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="csntextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>
</struts-config>
[/code]

Explanation:

Here we have overridden the Struts RequestProcessor with Spring’s DelegatingRequestProcessor using the controller tag. Now our Spring’s DelegatingRequestProcessor will lookup the Struts Actions
so we need to register the action in our Spring config file as shown below:

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="empSearchService" class="net.javabeat.example1.employee.business.EmpSearchImpl"/>
<bean name="/submitSearch"
class="net.javabeat.example1.employee.actions.SubmitSearch">
<property name="empSearchService">
<ref bean="empSearchService"/>
</property>
</bean>
</beans>
[/code]

Explanation:

This part is same as registering the Spring beans but here we register Struts actions as Spring’s beans, the names of the beans must be same as in struts config file. This will allow Spring to populate our beans at the run time.

[code lang=”java”]
Package net.javabeat.example1.employee.actions;

import java.io.IOException;
import javax.servlet.*;
import org.apache.struts.action.*;

import net.javabeat.example1.employee.beans.Employee;
import net.javabeat.example1.employee.business.EmpSearchService;

public class SubmitSearch extends Action {

private EmpSearchService empSearchService;
public EmpSearchService getEmpSearchService () {
return empSearchService;
}
public void setEmpSearchService(EmpSearchService empSearchService) {
this.empSearchService = empSearchService;
}
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

DynaActionForm searchEmpForm = (DynaActionForm) form;
String empId = (String) searchEmpForm.get("empId");
Employee employee = getEmpSearchService().find(empId.trim());

if (null == employee) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("message.notfound"));
saveErrors(request, errors);
return mapping.findForward("failure") ;
}
request.setAttribute("employee", employee);
return mapping.findForward("success");
}
}
[/code]

Explanation:

Now here we are using Struts action but the beans are managed by Spring. In the above code we create a javaBean which is populated by Spring and then use it to run our business logic.

Disadvantages:

This method is definitely better then the previous one but still here the Spring beans are dependent on the RequestProcessor, this reduces the flexibility of the application.

B) Delegate Struts Action management to the Spring framework.

A much better solution is to delegate Struts action management to the Spring framework. You can do this by registering a proxy in the struts-config action mapping. The proxy is responsible for looking up the Struts action in the Spring context. Because the action is under Spring’s control, it populates the action’s JavaBean properties and leaves the door open to applying features such as Spring’s AOP interceptors.

The delegation method of Spring integration

[code lang=”xml”]
<?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="searchEmpForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="empId" type="java.lang.String"/>
</form-bean>
</form-beans>
<global-forwards type="org.apache.struts.action.ActionForward">
<forward name="welcome” path="/index.do"/>
<forward name="searchEmployee" path="/searchEmp.do"/>
<forward name="submitSearch" path="/submitSearch.do"/>
</global-forwards>
<action-mappings>
<action path="/welcome" forward="/WEB-INF/views/welcome.htm"/>
<action path="/searchEmployee" forward="/WEB-INF/views/search.jsp"/>
<action path="/submitSearch"
type="org.springframework.web.struts.DelegatingActionProxy" (1)
input="/searchEmployee.do"
validate="true"
name="searchEmpForm">
<forward name="success" path="/WEB-INF/views/empDetail.jsp"/>
<forward name="failure" path="/WEB-INF/views/search.jsp"/>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>
</struts-config>
[/code]

Explaination:

This is simply a struts config file, but here we do not declare the action’s class name but we set the Spring’s DelegatingActionProxy. The DelegatingActionProxy will lookup context for the action name in the spring’s config and map it to its class. The context is declared in the ContextLoaderPlugIn.

Now just register the Struts action as a bean in the Spring config file. The properties for this action’s bean will be automatically populated just like any other Spring bean.

Register a Struts action in the Spring context

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="empSearchService" class="net.javabeat.example1.employee.business.EmpServiceImpl"/>
<bean name="/submitSearch"
class="net.javabeat.example1.employee.actions.SubmitSearch">
<property name="empSearchService">
<ref bean="empSearchService"/>
</property>
</bean>
</beans>
[/code]

Disadvantages:

If you have the option to choose a method then this is the best method the only disadvantage here is this method leaves your code less readable because the dependencies are not clear.

Using Spring’s AOP with your Struts Application:

To tackle cross-cutting you can use Spring interceptors

To use Spring’s AOP in your Struts Applications you need to :

  1. Create the interceptor.
  2. Registor the interceptor.
  3. Delclare interceptors.

For example

A sample logging interceptor

[code lang=”java”]
package net.javabeat.example1.employee.interceptors;

import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class LoggingInterceptor implements MethodBeforeAdvice {

public void beforeMethod(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("logging before intersection");
}
}
[/code]

This interceptor will execute the beforeMethod() before every intersection (We are using MethodBeforeAdvice). Here we are just printing a line but we can use it for anything we like. Next let us register the interceptor.

Registering the interceptor in the Spring config file

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="empSearchService" class="net.javabeat.example1.employee.business.EmpSearchServiceImpl"/>
<bean name="/submitSearch"
class="net.javabeat.example1.employee.actions.SubmitSearch">
<property name="empSearchService">
<ref bean="empSearchService"/>
</property>
</bean>
<!– Interceptors –>
<bean name="logger"
class="net.javabeat.example1.employee.interceptors.LoggingInterceptor"/>
<!– AutoProxies –>
<bean name="loggingAutoProxy"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<value>/submitSearch>/values>
</property>
<property name="interceptorNames">
<list>
<value>logger>/value>
</list>
</property>
</bean>
</beans>
[/code]

Explanation:

First we have to register the interceptor:

[code lang=”xml”]
<bean name="logger"
class="net.javabeat.example1.employee.interceptors.LoggingInterceptor"/>
[/code]

Now we need to define the intersections, we will use autoproxy:

[code lang=”xml”]
<bean name="loggingAutoProxy"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
[/code]

Now we have to register the Struts action’s that will be intercepted.

[code lang=”xml”]
<property name="beanNames">
<value>/submitSearch>/values>
// <value>/otherBeans>/values>
</property>
Apply interceptors to the beanNames:
<property name="interceptorNames">
<list>
<value>logger>/value>
</list>
</property>
[/code]

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

Conclusion

All the three methods provide good integrating of Struts with Spring and you can select any method that suits your project. The Action-delegation method seems to be better of the three because you have to make fewer changes in the code and you can take advantages of other features of Spring like AOP (discussed latter). This method gives Spring more control over Struts action. You can make the strut’s actions (or beans in Spring) threadsafe through Spring. You can also use Spring’s life cycle methods.

If you have any questions on the spring framework integration with struts, please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about spring framework, interview questions, spring and hibernate integration,etc.
If you would like to receive the future java articles from our website, please subscribe here.

Filed Under: Spring Framework Tagged With: Struts

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved