環境:Eclipse + Struts2
目標:點擊按鈕把輸入框的內容送到後端,後端處理後把結果回傳並顯示在頁面上。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX 與 Struts2 互動</title>
</head>
<body>
<input type="text" id="userinput">
<input type="button" id="submit" value="送出">
<div id="msg"></div>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript">
window.onload = function () {
document.getElementById("submit").onclick = test;
};
function test() {
var userinput = document.getElementById("userinput");
$.post("https://localhost:8080/TestSpring/TestAction",
{ username: userinput.value },
function (data, textStatus) {
document.getElementById("msg").innerHTML = data;
}
);
}
</script>
</body>
</html>$.post() 是 $.ajax() 的簡寫形式,適合這種「送一組參數、取一段回應」的簡單情境。回呼裡直接把 data 塞進容器中,畫面就更新了。
<action name="TestAction" class="com.action.Test">
<result>index.jsp</result>
</action>package com.action;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Test extends ActionSupport {
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
// 中文參數與回應都要指定編碼,否則會出現亂碼
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.write(request.getParameter("username"));
out.flush();
out.close();
return null; // 直接寫回應,不必再走視圖
}
}這裡有兩個實務上很常出問題的細節:一是 request.setCharacterEncoding("utf-8") 必須在讀取任何參數之前呼叫,放到後面就沒有效果;二是 Action 直接寫入 response 時回傳 null,避免框架再做一次視圖轉發,否則回應內容會被污染。