- 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.
struts.objectFactory = spring
struts.devMode = true
struts.enable.DynamicMethodInvocation = falsesrc/struts.properties - The Action class: Here is the code for the action class
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;
}
}SearchAction.java - 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.
- The struts Configuration:
<!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>src/struts.xml - The action's class attribute has to map the id attribute of the bean defined in the spring bean factory definition.
- The Spring bean factory definition
<?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>WEB-INF/applicationContext.xml - 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.
- The web deployment descriptor
<?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>web.xml The only significant addition here is that of the RequestContextListener. This listener allows Spring framework, access to the HTTP session information. - 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.
<%@ 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>search.jsp - 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
Labels
.NET Job Questions
About Java
Absract class
Abstract class
Abstract Class and Interface
Aggregation
ajax
aop
apache ofbiz
Apache ofbiz tutrial
Association
authentication
autocad
basics
batch
Binary Tree
bootstrap loader in java
build
Builder design pattern
C++ Job Questions
caching
CallableStatement in java
certifications
Chain of responsibility Design pattern
charts
check parentheses in a string
Classes
classloader in java
classloading concept
code quality
collage level java program
Composition
concurrency
Concurrency Tutorial
Converting InputStream to String
Core Java
core java concept
core java interview questions
Core Java Interview Questions
Core Java Questions
core java tutorial
CyclicBarrier in Java
data structures
database
Database Job Questions
datetime in c#
DB
Db2 SQL Replication
deserialization in java
Design Patterns
designpatterns
Downloads
dtd
Eclipse
ejb
example/sample code
exception handling in core java
file handling injava
File I/O vs Memory-Mapped
Filter
first program in spring
flex
Garbage Collection
Generics concept in java
grails
groovy and grails
Guice
Heap
hibernate
Hibernate Interview Questions
how-to
IBM DB2
IBM DB2 Tutorial
ide
immutable
Interceptor
Interface
interview
Interview Questions for Advanced JAVA
investment bank
j2ee
java
JAVA Code Examples
Java 7
java changes
java class loading
JAVA Classes and Objects
Java Classloader concept
Java classloading concept
java cloning concept
java collection
Java collection interview questions
Java Collections
java concurrency
Java CountDownLatch
java definiton
Java design pattern
Java EE 5
Java EE 6
Java Exceptions
Java file
Java Garbage Collection
Java generics
Java Glossary
java hot concept
java immutable concept
Java Interface
Java interview Question
java interview question 2012
java interview question answer
Java Interview Questions
Java Interview Questions and Answers
java interview topic
java investment bank
Java Job Questions
java multithreading
java multithreading concept
java new features
Java Packages
java proxy object
java questions
Java Serialization
Java serialization concept
java serialization interview question
java session concept
java string
Java Swings Questions
java synchronization
java threading
Java Threads Questions
java tutorial
java util; java collections; java questions
java volatile
java volatile interview question
Java Wrapper Classes
java.java1.5
java.lang.ClassCastException
JavaNotes
javascript
JAX-WS
jdbc
JDBC
JDBC Database connection
jdk 1.5 features
JDK 1.5 new features Concurrent HashMap
JMS interview question
JMS tutorial
job
JSESSIONID concept
JSESSIONID interview Question
JSF
jsp
JSP Interview Question
JSP taglib
JSTL with JSP
Junit
Junit Concept
Junit interview question.Best Practices to write JUnit test cases in Java
JVM
Linux - Unix tutorial
Marker Interfaces
MD5 encryption and decryption
messaging
MNC software java interview question
musix
NCR java interview question
Networking Job Questions
news
Object Serialization
Objects
ojdbc14.jar
OOP
Oracle
Oracle SQL Query for two timestamp difference
orm
own JavaScript function call in Apache ofbiz
Packages
Palm Apps
patterns
pdf
persistence
Portal
Portlet Spring Integration
Prime number test in java
programs
Rails
Reboot remote computers
REST
Ruby
Sample application
schema
SCJP
security
Senior java developer interviews
servlet3
servlets
session tracking
singleton design pattern
Spring
Spring 2.5 Framework
spring ebook
Spring framework concept
spring MVC
spring pdf
Spring Security
Spring Security interview questions
SQL
SQL performance
SQL Query to create xml file
Sql Query tuning
ssis and ssrs
StAX and XML
string concept
string immutable
string in java
strings
struts
Struts2
Struts2 integration
synchronization works in java
Technical Interview
testing
tips
Tomcat
top
Tutorial
Volatile in deep
Volatile working concept
web
Web Developer Job Questions
web services
weblogic
Weblogic Application Server
websphere
what is JSESSIONID
xml
XML parsing in java
XML with Java
xslt
|
Monday, 29 July 2013
Integrating Struts 2.0 with Spring
In the past, I posted an example on how to use Displaytag with Struts and Spring, using Spring JDBC for data access(1, 2). 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.
Labels:
example/sample code,
persistence,
Spring,
struts
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment