一、导入所需包,包括Struts2所需的各jar包,再导入struts2-convention-plugin-2.1.jar和jsonplugin-0.34.jar
二、在Web.xml添加Struts2
web.xml
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
三、修改struts.xml,配置struts2-convention-plugin。并修改convention-plugin默认的结果资源路径为webroot/
struts.xml
<struts> <!-- 结果资源所在路径 --> <constant name="struts.convention.result.path" value="/"/> </struts>
四、编写Action代码
com.fish.action.json.JsonTestAction
package com.fish.action.json; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import com.opensymphony.xwork2.ActionSupport; @ParentPackage("json-default") @Result(type="json",name="test") public class JsonTestAction extends ActionSupport { private static final long serialVersionUID = 4242612202520616657L; private String name = "fish119"; public String getName() { return name; } public void setName(String name) { this.name = name; } @Action(value="test",results={@Result(type="json",name="test")}) public String test() throws Exception{ this.name += ": Test method!!"; return "test"; } @Action(results={@Result(type="json",name="success")}) public String execute() throws Exception{ this.name +=": This is the default method!"; return SUCCESS; } }
五、编写页面文件
index.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=UTF-8"> <script type="text/javascript" src="js/jquery.js"></script> <title>Insert title here</title> <script type="text/javascript"> function alt() { $.getJSON("json/json-test.action", function(json){alert(json.name);}); }; function altTest() { $.getJSON("json/json-test!test.action", function(json){alert(json.name);}); }; </script> </head> <body> <button id="a" onclick="alt();">点我-Default</button> <button id="b" onclick="altTest();">点我-Test</button> </body> </html>
六、测试
在地址栏输入 http://localhost:8080/ConventionTest/index.html
点击“点我-Default”按钮,调用action中的execute方法,弹出“This is the default method!”
点击“点我-Test”按钮,调用action中的test方法,弹出“Test method!!”