Here we will fetch a action variable’s value in jsp page using JSON and jquery
Here I am using struts 2.3.4 for that we have to include struts-2-json-plugin-2.3.4.jar in class path or include it to your lib folder if you are using any IDE.
Action class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package example; import com.opensymphony.xwork2.ActionSupport; public class HelloJSON extends ActionSupport { private String name; private String welcomeMessage; @Override public String execute() { System.out.println("Inside Action name is " + getName()); setWelcomeMessage("Welcome " + getName() + "!!"); System.out.println(getWelcomeMessage()); return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWelcomeMessage() { return welcomeMessage; } public void setWelcomeMessage(String welcomeMessage) { this.welcomeMessage = welcomeMessage; } } |
In struts.xml we have to extend json-default and result type shold be json. No need to specify path inside <result &rt;</result<
struts.xml
1 2 3 4 5 | <package name="example1" extends="json-default"> <action name="test" class="example.HelloJSON"> <result type="json"></result> </action> </package> |
Jsp page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <%@ page contentType="text/html; charset=UTF-8" %> <html> <head> <title><s:text name="Hello JSON/></title> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> </head> <body> <form action="" id="myForm"> <label for="name">Enter Your Name</label> <input name="name" id="name"> <input type="button" id="button1" value="Submit"> </form> <div class="result"></div> <script> $("#button1").click(function() { var name1=$("#name").val(); $.getJSON('test', { name: name1}, function(data) { $('.result').html(data.welcomeMessage); return false; }); }); </script> </body> </html> |
Here we are using $.getJSON(‘test’, { name: name1}, function(data) method to fetch json data.