Ajax in Struts 2

On the Eclipse, create a Maven project

Click Next button and select Workspace location for project

Click Next button and select maven-archetype-webapp

Click Next button and enter Project Information:

  • GroupId: LearnStrutsFrameworkWithRealApps
  • Artifact Id: LearnStrutsFrameworkWithRealApps
  • Package: com.demo

Click Finish button to finish create Maven project




Select current project, Right click and select Properties menu. In Properties dialog, select Targeted Runtime in left side after select Tomcat server from server list in right side

Click Ok button to finish

Select current project, Right click and select Build Path\Configure Build Path menu Select JRE System Library in Libraries tab:

Click Edit button and select JRE System Library you need use as below:

Click Finish button to finish




Open pom.xml file and add configurations for Struts 2 as below:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>LearnStrutsFrameworkWithRealApps</groupId>
	<artifactId>LearnStrutsFrameworkWithRealApps</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>LearnStrutsFrameworkWithRealApps Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>1.2.1</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- Struts 2 Framework -->

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.5.20</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>2.5.20</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-json-plugin</artifactId>
			<version>2.5.20</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>LearnStrutsFrameworkWithRealApps</finalName>
	</build>
</project>




Open web.xml file in src\main\webapp\WEB-INF folder and add configurations for Struts 2 as below:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
		 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Learn Struts 2 Framework with Real Apps</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<init-param>
			<param-name>struts.devMode</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>struts.action.extension</param-name>
			<param-value>html</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

Create new package named entities. In this package, create new java class named Product.java as below:

package entities;

public class Product {

	private String id;
	private String name;
	private double price;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public Product(String id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}

	public Product() {
		super();
	}

}




Create new package named controllers.action in src/main/java folder. The action class in Struts 2 must be put in a package named action. In this package, create new java class named DemoAction.java as below:

package controllers.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

import entities.Product;

@ParentPackage("json-default")
@Namespace("/demo")
public class DemoAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private String fullName;
	private Map<String, Object> jsonData = new HashMap<String, Object>();

	public Map<String, Object> getJsonData() {
		return jsonData;
	}

	public void setJsonData(Map<String, Object> jsonData) {
		this.jsonData = jsonData;
	}

	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName = fullName;
	}

	@Action(value = "index", results = {
		@Result(name = SUCCESS, location = "/WEB-INF/views/demo/index.jsp")
	})
	public String index() {
		return SUCCESS;
	}

	@Action(value = "demo1")
	public void demo1() {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/plain;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print("Demo 1");
			out.flush();
			out.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	@Action(value = "demo2")
	public void demo2() {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/plain;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print("Hi " + this.fullName);
			out.flush();
			out.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	@Action(value = "demo3", results = {
		@Result(name = "success", type = "json", params = { "root", "jsonData" })
	})
	public String demo3() {
		jsonData.put("product", new Product("p01", "name 1", 100));
		return SUCCESS;
	}

	@Action(value = "demo4", results = {
		@Result(name = "success", type = "json", params = { "root", "jsonData" })
	})
	public String demo4() {
		List<Product> products = new ArrayList<Product>();
		products.add(new Product("p01", "name 1", 100));
		products.add(new Product("p02", "name 2", 200));
		products.add(new Product("p03", "name 3", 300));
		jsonData.put("listProduct", products);
		return SUCCESS;
	}

}




Create new folder named views in src\main\webapp\WEB-INF folder. In views folder, create new folder named demo. In demo folder create new JSP file named index.jsp as below:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Learn Struts 2 with Real Apps</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {

	$('#buttonDemo1').click(function() {
		$.ajax({
			type : "POST",
			url : '${pageContext.request.contextPath}/demo/demo1.html',
			success : function(response) {
				$('#result1').html(response);
			}
		});
	});

	$('#buttonDemo2').click(function() {
		var fullName = $('#fullName').val();
		$.ajax({
			type : "GET",
			data:{fullName: fullName},
			url : '${pageContext.request.contextPath}/demo/demo2.html',
			success : function(response) {
				$('#result2').html(response);
			}
		});
	});

	$('#buttonDemo3').click(function() {
		$.ajax({
			type : "GET",
			headers : {
				Accept : "application/json; charset=utf-8",
				"Content-Type" : "application/json; charset=utf-8"
			},
			url : '${pageContext.request.contextPath}/demo/demo3.html',
			success : function(response) {
				var result = 'Id: ' + response.product.id +
					'<br>Name: ' + response.product.name +
					'<br>Price: ' + response.product.price;
				$('#result3').html(result);
			}
		});
	});

	$('#buttonDemo4').click(function() {
		$.ajax({
			type : "GET",
			headers : {
				Accept : "application/json; charset=utf-8",
				"Content-Type" : "application/json; charset=utf-8"
			},
			url : '${pageContext.request.contextPath}/demo/demo4.html',
			success : function(response) {
				var n = response.listProduct.length;
				var result = '';
				for(var i=0; i<n; i++) {
					result += '<br>Id: ' + response.listProduct[i].id;
					result += '<br>Name: ' + response.listProduct[i].name;
					result += '<br>Price: ' + response.listProduct[i].price;
					result += '<br>---------------------';
				}
				$('#result4').html(result);
			}
		});
	});

});
</script>
</head>
<body>

	<fieldset>
		<legend>Demo 1</legend>
		<input type="button" value="Demo 1" id="buttonDemo1">
		<br>
		<span id="result1"></span>
	</fieldset>

	<fieldset>
		<legend>Demo 2</legend>
		Full Name <input type="text" id="fullName">
		<input type="button" value="Demo 2" id="buttonDemo2">
		<br>
		<span id="result2"></span>
	</fieldset>

	<fieldset>
		<legend>Demo 3</legend>
		<input type="button" value="Demo 3" id="buttonDemo3">
		<br>
		<span id="result3"></span>
	</fieldset>

	<fieldset>
		<legend>Demo 4</legend>
		<input type="button" value="Demo 4" id="buttonDemo4">
		<br>
		<span id="result4"></span>
	</fieldset>

</body>
</html>




Create new jsp file named index.jsp in src\main\webapp folder as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="demo/index.html"></jsp:forward>




Select project, right click and select Run on Server menu

Access index method in demo action with following url:

http://localhost:8080/LearnStrutsFrameworkWithRealApps/demo/index.html

Input data to form and click buttons