Pages Navigation Menu

Coding is much easier than you think

How to Call Struts2 action from java script

How to Call Struts2 action from java script

 

Action Class

 

package com.simplecode.action;
import com.opensymphony.xwork2.ActionSupport;

public class MyAction extends ActionSupport
{
	public String trueCall()
	{
		return SUCCESS;
	}

	public String falseCall()
	{
		return SUCCESS;
	}
}

 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Jsp Pages

 
File : confirmBox.jsp
 

<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Calling Action from java script</title>
<script type="text/javascript">
function confirmBox() 
{
var location = confirm("Do you want to go to this page?");
 if (location == true)
 	{
	window.location = "${pageContext.request.contextPath}/trueAction";
	}
        else
	{
	window.location = "${pageContext.request.contextPath}/falseAction";
	}
 }
</script>
</head>

<body>
	<s:submit value="Submit" onclick="confirmBox();" align="left"></s:submit>
</body>
</html>

 
Do read :

 
File : truePage.jsp
 

<html>
<head>
<title>Calling Action from java script</title>
</head>
<body>
	<h2>True Action</h2>
</body>
</html>

 
File :falsePage.jsp
 

<html>
<head>
<title>Calling Action from java script</title>
</head>
<body>
	<h2>False Action</h2>
</body>
</html>

 

Struts.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>
<package name="default" extends="struts-default" namespace="/">
<action name="trueAction" method="trueCall" class="com.simplecode.action.MyAction">
  <result>/truePage.jsp</result>
</action>

<action name="falseAction" method="falseCall" class="com.simplecode.action.MyAction">
  <result>/falsePage.jsp</result>
</action>
</package>
</struts>

 
Recommended Article :

 

Demo

 
On running the application we get
 
javascript in struts 2
 

Here on clicking the submit button, we get a confirm box, in which on clicking “Ok”, trueAction get’s called and on clicking “Cancel”, falseAction gets called.

About Mohaideen Jamil


I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Advertisements
%d bloggers like this: