Struts 2 and jQuery JSON integration Example


In this Struts 2 tutorials, we are going to integrate the jQuery JSON to fetch the data without page refresh. To do this jQuery provide the predefined method $.getJSON().

This method similarly works as $.ajax() method provide in jQuery.

In this example when we select the Country name it will internally fetch the State list related to the selected country.

Struts 2 and jQuery JSON integration Example

Software and Library Used

  1. Eclipse IDE
  2. jQuery Library(ver 3.1.1)
  3. Tomcat 8
  4. JDK 8
  5. Struts 2 Jar
  6. MySQL Database

Note: The response to be sent to jQuery is of type JSON, to handle it you need struts2-json-plugin-2.x.x.jar.

Project Structure in Eclipse

Struts 2 and jQuery JSON integration Example
JS Snippet
function reflect(that) {

		var countryName = $(that, "#countryVal").val();
		var requestedData = "countryVal=" + countryName;

		$.getJSON("stateviacountry", requestedData, function(data) {
			var sparrow = "";

			$.each(data.dtoList, function() {

				sparrow += "" + this.state + "";

			});
			sparrow += "";

			$("#stateval").html(sparrow);
		});
	}

Step 1: Create the table and insert data into the table.

countrymaster.sql
CREATE TABLE `countrymaster` (
  `country` varchar(30) DEFAULT NULL,
  `state` varchar(30) DEFAULT NULL
);

insert  into `countrymaster`(`country`,`state`) values ('India','Uttar Pradesh'),('India','Bihar'),('India','Rajsthan'),
('India','Delhi'),('USA','Missouri'),('USA','Ohio'),('USA','Pennsylvania'),('USA','New York'),('Russia','Kaluga'),
('Russia','Moscow'),('Australia','Victoria');

Step 2: Add Struts 2 filter in web.xml

web.xml
  <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>

 

Step 3: Create the class for DB connection and DAO.

StrutsJsonDAO.java
package org.websparrow;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class StrutsJsonDAO {
	
	// database connection method
	public static Connection conn() throws Exception {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/websparrow", "root", "");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// fetch the country list
	public static ResultSet fetchCountry() {
		ResultSet rs = null;
		try {
			Statement stmt = conn().createStatement();
			rs = stmt.executeQuery("SELECT DISTINCT(country) AS country FROM countrymaster");
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// fetch the state list
	public static ResultSet fetchState(String country) {
		ResultSet rs = null;
		try {
			Statement stmt = conn().createStatement();
			String q = "SELECT state FROM countrymaster WHERE country='" + country + "'";
			rs = stmt.executeQuery(q);
			System.out.println(q);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}

Step 4: Define the entity of table in DTO class.

StrutsJsonDTO.java
package org.websparrow;

public class StrutsJsonDTO {
	String state, country;

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}
}

Step 5: Create the Action class.

StrutsJsonAction.java
package org.websparrow;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class StrutsJsonAction extends ActionSupport {
	private static final long serialVersionUID = -3385807446537067813L;
	List<StrutsJsonDTO> dtoList = null;
	ResultSet rs = null;
	StrutsJsonDTO dtoObj = null;
	String countryVal = null;

	@Override
	// method for the country data
	public String execute() throws Exception {
		try {
			rs = org.websparrow.StrutsJsonDAO.fetchCountry();

			if (rs != null) {
				dtoList = new ArrayList<StrutsJsonDTO>();
				while (rs.next()) {
					dtoObj = new StrutsJsonDTO();
					dtoObj.setCountry(rs.getString("country"));
					dtoList.add(dtoObj);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "SUCCESS";
	}

	// method for the state data
	public String fetchStateList() throws Exception {
		try {
			rs = org.websparrow.StrutsJsonDAO.fetchState(countryVal.trim());
			if (rs != null) {
				dtoList = new ArrayList<StrutsJsonDTO>();
				while (rs.next()) {
					dtoObj = new StrutsJsonDTO();
					dtoObj.setState(rs.getString("state"));
					dtoList.add(dtoObj);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "SUCCESS";
	}

	public String getCountryVal() {
		return countryVal;
	}

	public void setCountryVal(String countryVal) {
		this.countryVal = countryVal;
	}

	public List<StrutsJsonDTO> getDtoList() {
		return dtoList;
	}

	public void setDtoList(List<StrutsJsonDTO> dtoList) {
		this.dtoList = dtoList;
	}
}

Step 6: Map the class in struts.xml

struts.xml
<struts>
	<constant name="struts.devMode" value="true" />
	<package name="default" extends="json-default" namespace="/">
		<action name="countrystate" class="org.websparrow.StrutsJsonAction">
			<result name="SUCCESS">/index.jsp</result>
		</action>
		<action name="stateviacountry" class="org.websparrow.StrutsJsonAction" method="fetchStateList">
			<result name="SUCCESS" type="json"></result>
		</action>
	</package>
</struts>

Step 7: Design the front end page for the user.

index.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
	function reflect(that) {

		var countryName = $(that, "#countryVal").val();
		var requestedData = "countryVal=" + countryName;

		$.getJSON("stateviacountry", requestedData, function(data) {
			var sparrow = "";

			$.each(data.dtoList, function() {

				sparrow += "<option>" + this.state + "</option>";

			});
			sparrow += "";

			$("#stateval").html(sparrow);
		});
	}
</script>

</head>
<body style="margin-left: 20px;">
	<h1>Struts2 and jQuery JSON integration Example</h1>
	<form action="countrystate" method="post">
		<input type="submit" value="Click Me" />
	</form>
	<div style="margin-top: 10px;">
		Country:
		<select onchange="reflect(this);">
			<option>Select County</option>
			<s:iterator value="dtoList">
				<option id="countryVal"><s:property value="country" /></option>
			</s:iterator>
		</select>
		State:
		<select id="stateval">
			<option>Select State</option>
		</select>
	</div>
</body>
</html>

Output:

Finally, everything is set. Now run the application and click on the Click Me button. It will fetch the all country list form the database, and when you select any country it will fetch the state list of that country. You will notice the page is not refreshing.

Screen 1

Struts 2 and jQuery JSON integration Example

Screen 2

Struts 2 and jQuery JSON integration Example

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.