I am working on struts 2 with JSON response
Below is my code
ACTION CLASS
public class JSONDataAction implements ServletRequestAware{
private String firstName;
private String lastName;
protected HttpServletRequest request;
public String execute() {
System.out.println("FIRST NAME IN ACTION CLASS IS::"+firstName);
System.out.println("LAST NAME IN ACTION CLASS IS::"+lastName);
request.setAttribute("temp", "temp data");
return "success";
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getServletRequest() {
return request;
}
}
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>
<constant name="struts.devMode" value="true" />
<package name="jsonView" namespace="/" extends="struts-default,json-default">
<action name="getJSONResult" class="com.javatechig.struts2web.actions.JSONDataAction">
<result name="success" type="json">/pages/details.html</result>
</action>
</package>
</struts>
employee.html
<html>
<body>
<h4>
Struts 2 HTML5 Example
</h4>
<form action="getJSONResult" method="post">
Enter first name: <input type = "text" name="firstName"><br>
Enter last name : <input type = "text" name="lastName"><br>
<input type="submit">
</form>
</body>
</html>
details.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Details</title>
</head>
<body>
EMPLOYEE DETAILS :::
</body>
</html>
I have added the struts2-json-plugin-2.3.24.jar to the lib folder as required
When I submit the form(employee.html), the form data is captured in action class (JSONDataAction)
and I see the json response in browser as shown below
{lastName":"User", firstName: "Test"}
I have the following doubts
- Why details.html is not displayed on the browser(I see only json response on the browser).
- Request attribute - temp is not present in the json response. How to pass request attribute in json response.
- How to process json response in details.html.
- How to pass the JSON response to the different views(HTML5) based on result type returned from action class.