DIV CSS 佈局教程網

AJAX 提交資料到 Struts2 Action 並回顯於頁面
編輯:AJAX基礎知識     

環境:Eclipse + Struts2

目標:點擊按鈕把輸入框的內容送到後端,後端處理後把結果回傳並顯示在頁面上。

index.jsp

<%@ 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 塞進容器中,畫面就更新了。

struts.xml

<action name="TestAction" class="com.action.Test">
    <result>index.jsp</result>
</action>

Test.java

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,避免框架再做一次視圖轉發,否則回應內容會被污染。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved