最近使用ssh構建服務器,用於與android客戶端的通訊。期間每每添加action或者new method都必須改配置文件,久而久之很煩,於是於昨夜決定,今日起身后嘗試用annotation返回json(過往不曾嘗試...).
由於之前嘗試使用annotation跳轉到頁面,因此覺得返回json應該是差不多的。不過真的誰試誰知道...哎...
最後通過木有大腿的毅力,終於成果了。遂記,或拯救他人於水深火熱之中。
先說說需要的jars,如下圖:
然後,看一下目錄結構:
對於model 的話,像平常一樣使用json annotation就可以,在此就不截圖了。
現在來看一下action.
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.vincent.model.User;
@ParentPackage("json-default")
@Namespace("/testjson")
public class TestAction {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Action(value = "user", results = { @Result(name = "success", type = "json") })
public String getJson() {
user = new User("vincent");
return "success";
}
}
需要注意的是,ParentPackage一般是struts-default, 但由於我需要返回json,就改成json-default。如果有經驗的朋友應該可以理解到,這個就是相當於struts.xml中<package/>的extend.
另外需要注意的是,像使用配置文件配置返回Json一樣,返回的對象都要有對應的getter/setter,否則只返回{"json":"success"}; 再者,如果是使用頁面進行跳轉的話,@Action 中value的值格式是"/*",*是對應的name.
最後,來看看web.xml的配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts2Example1</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter> <!-- Struts2 annotation --> <filter-name>struts</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <!-- //固定格式 --> <init-param> <param-name>actionPackages</param-name> <!-- com.struts2.action1,com.struts.action2 --> <param-value>com.vincent.action.TestAction</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
注意:如果是有多個action的話,action之間是使用","隔開。
最後,在瀏覽器上敲入:
http://localhost:8080/StrutsAnnotationReturnJson/testjson/user
就可以看到如下結果:
最最最后,各位不嫌棄的話,小弟附上源碼。謝謝。
這次就到這裡吧,看定影去.