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

Struts 2 Tutorials

December 21, 2013 by Krishna Srinivasan Leave a Comment

Apache Struts 2 is another popular Model – View – Controller (MVC) framework from the Apache foundation. Since the inception of Struts 1, it is one of the most popular framework used by the Java developers. Struts 2 enhances the functionality to latest trend in the web applications development like AJAX, Annotations, etc. with simplified implementation approach. This tutorial lists down all the articles and tutorials related to Struts 2 topic from Javabeat.

Struts 2 Tutorials

Struts 2 Architecture

Struts 2 Architecture Diagram

( Image Source )

Struts 2 Getting Started

  • String 2.0 Introduction and Validations : This article provides an introduction to Struts 2.0 and its new Validation Features. Since Struts 2.0 is new, the first few sections of the article discusses in brief about the basics of Struts 2.0, its architecture and its various New Features.
  • Struts 2 Features : List of new features introduced with the release
  • Hello World Example : Getting started hello world example program to start writing your first struts 2 application.  This example provides the complete source code with XML configuration files.
  • HttpServletRequest in Struts 2 Action Class : This explains how to get the HttpServletRequest object inside your action class. It is necessary for some specific scenarios where you have to set values to the request object. It is a simple demonstration to get the object.
  • HttpServletResponse in Struts 2 Action Class : This explains how to get the HttpServletResponse object inside your action class. It is necessary for some specific scenarios where you have to set values to the response object. It is a simple demonstration to get the object.
  • HttpServletContext in Struts 2 Action Class : This explains how to get the HttpServletContext object inside your action class. It is necessary for some specific scenarios where you have to set values to the context object. It is a simple demonstration to get the object.
  • Difference Between FilterDispatcher and StrutsPrepareAndExecuteFilter in Struts 2 : What is the main difference between these two filters used for the struts configuration. These classes are added to the web.xml deployment descriptor for loading struts configuration files.
  • Migrating Struts 1 Applications to Struts 2 : the latest release of struts was in the market and there is a demanding need to migrate the old applications developed with struts to new struts release in order to make use of the powerful features offered by new release.

Struts 2 Configurations

  • Configuration Files Path : The location and path for the different configuration fles used in the struts 2 applications. Also shows the sample folder structure for a simple application.
  • Exception Configuration : Shows how to configure exceptions thrown in your action class in the configuration file. It can be configured per action maping level. It is new addtion to the struts 2 release.
  • Interceptors Example : List of default interceptors in the struts 2 framework and how one can configure the custom interceptors to their application. Interceptors are invoked as the call back methods before and after the action class.
  • Resource Bundle Example : This post demonstrates how to create properties files for stroing the labels for the components used in the web page and how to load them in your application.
  • Custom Interceptor : n this application, we have created a custom interceptor “MyCustomInterceptor” which keeps track of the time spent in the action class. The interceptor is created in the interceptors package inside Source Packages sub directory.

Struts 2 Integration with Other Frameworks

  • Log4j Integration : How to integrate log4j to your application and print the log messages.
  • Spring Integration Example : Spring framework enables the Inversion of Control (IOC) container to manage the struts components (action class, beans) as the spring managed beans.
  • Annotation Example : How to write simple struts 2 application using the annotations. It is a getting started gude for using the annotation with your struts application.
  • JSON Integration : This post shows how your struts application can return JSON result from the server.
  • Struts 2 and JPA Integration : Struts can be used to build the user interface tier of the enterprise application. Whereas, any of the popular ORMs like Hibernate, JPA, iBatis can be used for the persistence tier of the application. Struts2 provides easy integration with these persistence tier frameworks.
  • Struts 2 and Hibernate Integration : This article demonstrates the integration of Struts 2.0 applications with the Hibernate. The concept is explained with the help of a sample application.

Struts 2 UI Tags

  • TextArea Tag Example : Create TextArea component in your JSP file and submit the values to the server.
  • Hidden Tag Example  : Create Hidden component in your JSP file and submit the values to the server. It is not popularly used in the recent days.
  • Select Tag Example : Create Select component in your JSP file and submit the values to the server.
  • Radio Tag Example : Create Radio component in your JSP file and submit the values to the server.
  • CheckBox Tag Example : Create CheckBox component in your JSP file and submit the values to the server.
  • Password Tag Example : Create Passoword component in your JSP file and submit the values to the server.
  • TextField Tag Example : Create TextField component in your JSP file and submit the values to the server.

Struts 2 Control Tags

  • Control Tags : List of control tags usied in the struts 2 applications.
  • If, Else Tag Example : A bsic example for using the if and else construct in your struts application.
  • Generator Tag Example : Example for struts generator tag in JSP file.
  • Merge Tag Example : How to use merge tag for merging the two lists supplied from the server.
  • Iterator Tag Example : How to use the iterator tag for looping the elements in a list.

Struts 2 Data Tags

  • Include Tag Example : Include another source in the current page using the include tag.
  • Push Tag Example : How to push the values to the top of the stack storage in the struts application context.
  • Property Tag Example : It is common tag used with all other tags to print the bean or property values.
  • Date Tag Example : How to use data tag.
  • Bean Tag Example : It is similar to the useBean tag in JSP. It create bean instance in your current page.
  • Action Tag Example : Send action execution to server and retrieves the result.

Filed Under: Tutorials Tagged With: Struts 2 Tutorials

Struts 2 + Log4j Integration

December 16, 2013 by Krishna Srinivasan Leave a Comment

This example demonstrates how to integrate log4j to your struts 2 project.

  • Add log4j.jar file in your project lib folder
  • Create log4j.xml file with loggers and appenders. Here I have added file and console appenders. Each log message will be printed in console and a file. Make sure that log4j.xml file is in the classpath.
  • Import org.apache.log4j.Logger in your action class and start using the logger methods. In this example I have used logger.info method.

Log4j in Struts 2 Location

Lets look at the example code.

1. Action Class

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

import org.apache.log4j.Logger;

public class Struts2HelloWorldAction {
private static final Logger logger = Logger.getLogger(Struts2HelloWorldAction.class);

public String execute(){
logger.info("Executing method");
return "success";
}
}
[/code]

2. Log4j XML Configuration Example – log4j.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="fileAppenderInfo" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="D:/info.log" />
<param name="MaxBackupIndex" value="10"/>
<param name="MaxFileSize" value="5120KB"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d
%-5p [%c{1}][%x] %m %n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender>
<appender name="consoleAppenderInfo" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d
%-5p [%c{1}][%x] %m %n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender>
<logger name="javabeat.net.struts2">
<level value="INFO" />
<appender-ref ref="fileAppenderInfo" />
<appender-ref ref="consoleAppenderInfo" />
</logger>
<logger name="com.opensymphony.xwork2">
<level value="INFO" />
<appender-ref ref="fileAppenderInfo" />
<appender-ref ref="consoleAppenderInfo" />
</logger>
<logger name="org.apache.struts2">
<level value="INFO" />
<appender-ref ref="fileAppenderInfo" />
<appender-ref ref="consoleAppenderInfo" />
</logger>

</log4j:configuration>
[/code]

3. Struts.xml

[code lang=”xml”]
<?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>
<constant name="struts.devMode" value="true" />
<package name="struts2demo" extends="struts-default">
<action name="log4jdemo" class="javabeat.net.struts2.Struts2HelloWorldAction"
method="execute">
<result name="success">/</result>
</action>
</package>
</struts>
[/code]

4. Log Messages

[code]
2013-12-16 15:11:59,266 INFO [XmlConfigurationProvider][] Parsing configuration file [struts-default.xml]
2013-12-16 15:11:59,341 INFO [XmlConfigurationProvider][] Unable to locate configuration files of the name struts-plugin.xml, skipping
2013-12-16 15:11:59,342 INFO [XmlConfigurationProvider][] Parsing configuration file [struts-plugin.xml]
2013-12-16 15:11:59,346 INFO [XmlConfigurationProvider][] Parsing configuration file [struts.xml]
2013-12-16 15:11:59,348 INFO [DefaultConfiguration][] Overriding property struts.i18n.reload – old value: false new value: true
2013-12-16 15:11:59,349 INFO [DefaultConfiguration][] Overriding property struts.configuration.xml.reload – old value: false new value: true
2013-12-16 15:09:52,345 INFO [Struts2HelloWorldAction][] Executing method
[/code]

Filed Under: Struts Tagged With: Struts 2 Tutorials

HttpServletContext in Struts 2 Action Class

December 16, 2013 by Krishna Srinivasan Leave a Comment

There are two ways to get the servlet context object inside struts 2 action class’s execute method.

  • ServletActionContext : Directly accessing the getContext method from the ServletActionContext class will return the context object.
  • ServletContextAware : If you implement the action class with ServletContextAware interface, then struts controller will send the context object through setServletContext method. You are requested to declare a variable for context object and write getter and setter methods.

1. ServletActionContext

[code lang=”java”]import javax.servlet.http.HttpServletContext;
import org.apache.struts2.ServletActionContext;

public class Struts2HelloWorldAction{
public String execute() {
HttpServletContext context = ServletActionContext.getContext();
return "SUCCESS";
}
}[/code]

2. ServletContextAware

[code lang=”java”]import javax.servlet.http.HttpServletContext;
import org.apache.struts2.interceptor.ServletContextAware;

public class Struts2HelloWorldAction implements ServletContextAware{

HttpServletContext context;

public String execute() {
return "SUCCESS";

}

public void setServletContext(HttpServletContext context) {
this.context = context;
}

}[/code]

However, it is recommended to use ServletContextAware instead of ServletActionContext method.

Filed Under: Java Tagged With: Struts 2 Tutorials

HttpServletResponse in Struts 2 Action Class

December 16, 2013 by Krishna Srinivasan Leave a Comment

There are two ways to get the servlet response object inside struts 2 action class’s execute method.

  • ServletActionContext : Directly accessing the getresponse method from the ServletActionContext class will return the response object.
  • ServletResponseAware : If you implement the action class with ServletResponseAware interface, then struts controller will send the response object through setServletResponse method. You are requested to declare a variable for response object and write getter and setter methods.

1. ServletActionContext

[code lang=”java”]
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;

public class Struts2HelloWorldAction{
public String execute() {
HttpServletResponse response = ServletActionContext.getResponse();
return "SUCCESS";
}
}
[/code]

2. ServletResponseAware

[code lang=”java”]
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;

public class Struts2HelloWorldAction implements ServletResponseAware{

HttpServletResponse response;

public String execute() {
Locale locale = getServletResponse().getLocale();
return "SUCCESS";

}

public void setServletResponse(HttpServletResponse response) {
this.response = response;
}

public HttpServletresponse getServletResponse() {
return this.response;
}
}
[/code]

However, it is recommended to use ServletResponseAware instead of ServletActionContext method.

Filed Under: Struts Tagged With: Struts 2 Tutorials

HttpServletRequest in Struts 2 Action Class

December 16, 2013 by Krishna Srinivasan Leave a Comment

There are two ways to get the servlet request object inside struts 2 action class’s execute method.

  • ServletActionContext : Directly accessing the getRequest method from the ServletActionContext class will return the request object.
  • ServletRequestAware : If you implement the action class with ServletRequestAware interface, then struts controller will send the request object through setServletRequest method. You are requested to declare a variable for request object and write getter and setter methods.

1. ServletActionContext

[code lang=”java”]
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

public class Struts2HelloWorldAction{
public String execute() {
HttpServletRequest request = ServletActionContext.getRequest();
return "SUCCESS";
}
}
[/code]

2. ServletRequestAware

[code lang=”java”]
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;

public class Struts2HelloWorldAction implements ServletRequestAware{

HttpServletRequest request;

public String execute() {
String paramValue = getServletRequest().getParameter("param");
return "SUCCESS";

}

public void setServletRequest(HttpServletRequest request) {
this.request = request;
}

public HttpServletRequest getServletRequest() {
return this.request;
}
}
[/code]

However, it is recommended to use ServletRequestAware instead of ServletActionContext method.

Filed Under: Struts Tagged With: Struts 2 Tutorials

Struts 2 Interceptors Example

December 15, 2013 by Krishna Srinivasan Leave a Comment

Interceptors are powerful mechanism to control the flow of each request. These are custom and default implementations which can be enforced to work as the callback methods at certain point of time. Struts 2 provides handful of default interceptors behind the scenes. One example is the exception handling at action level. Also we can write our own interceptors and add our own business logic inside the custom interceptors.

1. Action Class

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

public class Struts2HelloWorldAction{
public String execute(){
return "success";
}
}

[/code]

2. Custom Interceptor

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

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoggingInterceptor implements Interceptor{

@Override
public void destroy() {
System.out.println("Destroying logging interceptor…");

}
@Override
public void init() {
System.out.println("Initializing logging interceptor…");

}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String className = invocation.getAction().getClass().getName();
long startTime = System.currentTimeMillis();
System.out.println("Before calling action class: " + className);
String result = invocation.invoke();
long endTime = System.currentTimeMillis();
System.out.println("After calling action class: " + className
+ " Time taken: " + (endTime – startTime) + " ms");
return result;
}

}

[/code]

3. Struts.xml

If you look at the interceptor definition, we have used interceptor-stack. It is the collection of interceptors defined in one block. The reason why we are doing is to add the default interceptors to the list, otherwise struts 2 will not invoke the default interceptors. 

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="struts2demo" extends="struts-default">
<interceptors>
<interceptor name="logginginterceptor"
class="javabeat.net.struts2.LoggingInterceptor">
</interceptor>
<interceptor-stack name="loggingStack">
<interceptor-ref name="logginginterceptor" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<action name="InterceptorDemo" class="javabeat.net.struts2.Struts2HelloWorldAction">
<interceptor-ref name="loggingStack" />
<result name="success">Result.jsp</result>
</action>
</package>
</struts>
[/code]

4. Result

If you access the application using URL http://localhost:8080/Struts2App/InterceptorDemo, you would see the following output in the console.

[code]
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.util.TextParser)
Initializing logging interceptor…
15 Dec, 2013 5:52:02 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
15 Dec, 2013 5:52:02 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
15 Dec, 2013 5:52:02 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/56 config=null
15 Dec, 2013 5:52:02 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1385 ms
Before calling action class: javabeat.net.struts2.Struts2HelloWorldAction
After calling action class: javabeat.net.struts2.Struts2HelloWorldAction Time taken: 64 ms
[/code]

Filed Under: Struts Tagged With: Struts 2 Tutorials

Struts 2 + JSON Integration

December 15, 2013 by Krishna Srinivasan Leave a Comment

Struts 2 provides struts2-json-plugin.jar for supporting the conversion of result type to JSON strings. Nowadays every framework supports the JSON formats because it is the most preferred format for the REST web services. This example shows how you can integrate Struts 2 and JSON.

  1. Get the struts2-json-plugin.jar and add to the lib folder
  2. In the struts.xml configuration file, extend the package by json-default
  3. Make the result type for action mapping to be json

Lets look at the example code.

1. Action Class

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

import java.util.ArrayList;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;

public class HelloJSONAction{
private ArrayList<String> list;
public ArrayList<String> getList() {
return list;
}
public void setList(ArrayList<String> list) {
this.list = list;
}
public String execute(){
list = new ArrayList<String>();
list.add("Java");
list.add("C++");
list.add("Groovy");
return "success";
}
}

[/code]

2. Struts.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="struts2demo" extends="json-default">
<action name="HelloJSONDemo" class="javabeat.net.struts2.HelloJSONAction" >
<result type="json"/>
</action>
</package>
</struts>
[/code]

3. Struts 2 JSON Integration Demo

If you access the application using URL http://localhost:8080/Struts2App/HelloJSONDemo, you would see the following output.

Struts 2 JSON Example

Filed Under: Struts Tagged With: Struts 2 Tutorials

Struts 2 Annotation Example

December 15, 2013 by Krishna Srinivasan Leave a Comment

Struts 2 supports annotations out of the box in its latest release without even a single line of configuration changes. You are not needed to create struts.xml file and there is no need to mention the scanning path anywhere like we mention in the spring framework. You have to add one extra JAR file struts2-convention-plugin.jar which has the API to scan the classes and find the annotations.

  1. Struts 2 by default scan the action classes and convert the action class name to action mapping. For example if your action class name is “HelloAction”, the default action mapping would be “hello”. The first letter of the first word will be small.
  2. If you add @Action annotation before the execute method, the action mapping will be override the default name.

Lets look at the example code.

1. Action Class

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

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;

@Namespace("/")
@ResultPath(value="/")
@Result(name="success",location="Annotation.jsp")
public class HelloAction{
private String msg = "JavaBeat – Struts 2 Annotation Hello World!!";

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

@Action(value="/helloannotation")
public String execute(){
return "success";
}
}

[/code]

2. JSP File

Annotation.jsp

[code lang=”xml”]
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<h4>
<s:property value="msg" /><br>
</h4>
</body>
</html>
[/code]

3. Struts 2 Annotation Demo

If you access the application using URL http://localhost:8080/Struts2App/helloannotation, you would see the following output.

Struts 2 Annotation Example

Filed Under: Struts Tagged With: Struts 2 Tutorials

Struts 2 Resource Bundle Example

December 15, 2013 by Krishna Srinivasan Leave a Comment

It is best practice to have all the labels used in your application in the centralized location. Tradionally these message resources are stored in the property files using the key=value pairs and loaded on demand by the forms. Every framework supports this basic feature to configure the message resources. This example shows how to load property files in your Struts 2 Application and display it in the screen. Lets look at the code.

1. Action Class

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

public class Struts2HelloWorldAction{
private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String execute(){
return "success";
}
}[/code]

2. Property File

Create a property file in the class path.

form_labels.properties

[code]firstName=First Name
lastName=Last Name
[/code]

3. Struts 2 Configuration File

Add the entry for loading the property files from the class path.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="form_labels" />
<constant name="struts.devMode" value="true" />
<package name="uitagsdemo" extends="struts-default">
<action name="PropertyDemo" class="javabeat.net.struts2.Struts2HelloWorldAction" >
<result name="success">Input.jsp</result>
</action>
</package>
</struts>
[/code]

4. JSP File

Input.jsp

[code lang=”xml”]<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
</head>
<body>
<h2>JavaBeat – Struts 2 Property Labels Demo</h2>
<s:form action="PropertyDemo">
<s:textfield name="firstName" key="firstName" />
<s:textfield name="lastName" key="lastName" />
<s:submit label="Submit" />
</s:form>

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

5. Resource Bundle Demo

If you access the application using URL http://localhost:8080/Struts2App/PropertyDemo, you would see the following output.

Struts 2 Resource Bundle Example

Filed Under: Struts Tagged With: Struts 2 Tutorials

Struts 2 + Spring Integration Example

December 15, 2013 by Krishna Srinivasan Leave a Comment

Struts 2 provides plug-ins for integration to any other frameworks. If you are using Spring for your bean management, then it is very easy for you to integrate Spring container to Struts 2 application. Spring can manage the beans and struts actions classes as beans. You have to just specify the bean name in the struts configuration file. The following steps to be taken for the Struts 2 and Spring integration.

  1. Download the Struts2-Spring-plugin.jar. It is the library which integrates both the frameworks.
  2. Add Spring libraries into the lib folder
  3. Add context loader in the web.xml for loading the spring configuration file.

Struts 2 Spring JAR Files

The above steps are the additional tasks which you have to do with the Struts 2 application for enabling the integration. This tutorial shows a very simple example for the integration. Lets look at the example code.

1. Action Class and Bean

Write a action class and declare a bean which will be injected from the spring container with default values.

[code lang=”java”]
package javabeat.net.struts2;
public class Struts2SpringIntegrationAction {
//Spring Injection
private UserDetails userDetails;

public UserDetails getUserDetails() {
return userDetails;
}

public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}

public String execute(){
return "success";
}
}
[/code]

UserDetails.java

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

public class UserDetails {
private String userName;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

}
[/code]

2. Spring Configuration File

It is the traditional spring configuration file for declaring the spring beans. Note that here I have declared Struts action class as the spring beans and injected UserDetails beans to the action class.

applicationContext.xml

[code lang=”xml”]
<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.5.xsd">
<bean id="userDetails" class="javabeat.net.struts2.UserDetails">
<property name="userName" value="Rahul Dravid"/>
</bean>
<bean id="struts2Spring" class="javabeat.net.struts2.Struts2SpringIntegrationAction">
<property name="userDetails" ref="userDetails"/>
</bean>
</beans>[/code]

3. Struts 2 Configuration File

Struts 2 configuration file would use the spring’s bean name in the class attribute of the action mapping.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="uitagsdemo" extends="struts-default">
<action name="Struts2Spring" class="struts2Spring" >
<result name="success">Result.jsp</result>
</action>
</package>
</struts>[/code]

4. JSP File

Write a simple JSP to print the values.

Result.jsp

[code lang=”xml”]
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<h2>JavaBeat – Struts 2 Spring Integration Demo</h2>
<h4>
<s:push value="userDetails">
User Name : <s:property value="userName" /><br>
</s:push>
</h4>
</body>
</html>
[/code]

5. Web.xml

There are two entries in the web.xml

  1. Struts 2 filter and
  2. Spring configuration loader

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<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>

[/code]

6. Struts 2 Spring Integration Demo

If you access the application using URL http://localhost:8080/Struts2App/Struts2Spring, you would see the following output.

Struts 2 Spring Integration Example

Filed Under: Struts Tagged With: Spring Integration, Struts 2 Tutorials, Struts Integration

  • 1
  • 2
  • 3
  • 4
  • Next Page »

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