Struts 2中註解result type爲json類型的小示例

java類代碼:

package com.rain.json.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

@ParentPackage("json-default")
@Results({ @Result(name = "jsonExample", type = "json") })
public class JsonExampleAction {
	private String result;
	private String type;

	@Action(value = "/json/jsonExample")
	public String jsonExample() {
		if ("json".equals(type)) {
			result = "json";
		} else {
			result = "other";
		}
		return "jsonExample";
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}

jsp頁面代碼:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>jsonExample</title>
    <script type="text/javascript" src="<%=basePath%>js/base/jquery-1.4.4.min.js"></script>
    <script type="text/javascript">
    	function jsonExample(){
    		$.ajax({
    			type : "POST",
				dataType : "json",
				data : {type:"json"},
				url : "<%=basePath%>json/jsonExample.do",
				async : false,
				success : function(data) {
					if (data.result == "json") {
						alert("json");
					} else if (data.result == "other") {
						alert("other");
					}
				}
    		});
    	}
    </script>
  </head>
  
  <body>
    <input type="button" value="json" οnclick="jsonExample();"/>
  </body>
</html>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章