struts系列:返回json格式的響應
阿新 • • 發佈:2018-07-17
epo equals use roo apache class mpi 結構 clas
一、增加依賴庫
// https://mvnrepository.com/artifact/org.apache.struts/struts2-json-plugin compile group: ‘org.apache.struts‘, name: ‘struts2-json-plugin‘, version: ‘2.5.16‘
二、struts.xml配置示例
<package name="default-json" extends="json-default"> <action name="hello" class="com.sanro.strutsDemo.action.HelloAction" method="execute"> <result name="success">/pages/hello.jsp</result> <result name="errLogin" type="json"> <!-- 這裏指定將被Struts2序列化的屬性,該屬性在action中必須有對應的getter方法 --> <param name="root">jsonData</param> <!-- 指定是否序列化空的屬性 --> <param name="excludeNullProperties">true</param> </result> </action> </package>
三、action部分
private String name; //GET請求參數 private String password; //GET請求參數 private Map<String, String> jsonData; //響應的數據結構(由strut-json插件自動轉換成json格式)public String execute() { logger.debug("name=" + name); logger.debug("pwd=" + password); if ("lings".equals(name)) { return SUCCESS; } else { jsonData = new HashMap<String, String>(); jsonData.put("user", name); jsonData.put("password", password); return "errLogin"; } } //略去getter和setter方法
四、請求示例
http://localhost:8080/strutsDemo/hello?name=lings&password=123
五、響應示例
{"password":"123","user":"lings"}
struts系列:返回json格式的響應