JSON応答でStruts 2に取り組んでいます
以下は私のコードです
アクションクラス
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>
従業員.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>
必要に応じて、struts2-json-plugin-2.3.24.jar を lib フォルダーに追加しました。
フォーム (employee.html) を送信すると、フォーム データがアクション クラス (JSONDataAction) に取り込まれ、以下に示すようにブラウザーに json 応答が表示されます。
{lastName":"User", firstName: "Test"}
次の疑問があります
- details.html がブラウザーに表示されないのはなぜですか (ブラウザーに json 応答しか表示されません)。
- リクエスト属性 - temp が json レスポンスにありません。json レスポンスでリクエスト属性を渡す方法。
- details.html での json レスポンスの処理方法。
- アクション クラスから返された結果の種類に基づいて、JSON 応答をさまざまなビュー (HTML5) に渡す方法。