日期:2014-05-16  浏览次数:20389 次

tapestry 对外json接口实现

为了实现一个对外的json接口,仔细读了tapestry5.2的源代码,考虑了几种实现,最简便清晰的方法如下。

?

为json接口做一个Page, 例如命名为 JsonPage。在JsonPage里只放一个actonlink,给一个命名例如"do"

JsonPage.tml如下:

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">

<t:actionlink t:id="do">do</t:actionlink>

</html>

?

这样外部访问json接口url可以用 http://www.yourdomain.com/jsonpage.do/xx/xxx/xx/

?

jsonpage.do后面的/xx/xxx/xx是参数,和标准page的参数一样格式

?

JsonPage里做一个方法

?

JSONObject onAction(Object[] params) {

...

}

?

在这个方法中,实现逻辑,生成JSONObject。注意这个page的onActivate(Object[] params[])的params是空,要用url里名字为t:ac的参数的值来给onActivate()的params赋值。

?

最后需要做一个ServletFilter里面有类似这样的代码,以使tapestry认为这是个ajax请求,否则tapestry会不能处理JSONObject onAction()。

?

?

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

HttpServletRequestWrapper wrappedRequest=null;

if (httpRequest.getRequestURI().toLowerCase().contains("jsonpage")) {

wrappedRequest = new HttpServletRequestWrapper(httpRequest) {

public String getHeader(String name) {

if ("X-Requested-With".equals(name)) {

return "XMLHttpRequest";

}

return super.getHeader(name);

};

};

}

? ? ? ? ? ? ? ? chain.doFilter(wrappedRequest!=null?wrappedRequest:request, response);

}

?