Action类代码:
1 package com.example.action; 2 3 public class JsonAction { 4 private String name; 5 private int id; 6 7 public String test() { 8 name = "hello world"; 9 id = 100; 10 return "success"; 11 } 12 13 public String getName() { 14 return name; 15 } 16 17 public void setName(String name) { 18 this.name = name; 19 } 20 21 public int getId() { 22 return id; 23 } 24 25 public void setId(int id) { 26 this.id = id; 27 } 28 29 }
struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 3 <struts> 4 <package name="demo" extends="json-default" namespace="/"> 5 <action name="jsonTest" class="com.example.action.JsonAction" method="test"> 6 <result name="success" type="json"> 7 <param name="contentType">text/plain</param> 8 </result> 9 </action> 10 </package> 11 </struts>
jsonTest.jsp页面代码:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <script type="text/javascript" src="js/jquery-1.7.min.js"></script> 8 <script type="text/javascript"> 9 $(function(){ 10 $("#test").click(function(){ 11 $.ajax({ 12 url:"jsonTest.action", 13 type:"post", 14 dataType:"json", 15 success:function(data){ 16 alert(data.name); 17 alert(data.id); 18 } 19 }); 20 }); 21 }); 22 </script> 23 <title>JsonTest</title> 24 </head> 25 <body> 26 <input type="button" value="JsonTest" id="test"/> 27 </body> 28 </html>
当返回JSON数据时,Struts2将Action对象转换成JSON对象,返回到浏览器。