1、action中有return,则在struts2.xml对应的action中,必须有<result></result>
如果代码中返回值是void,配置文件中允许只有一个 <action></action>标签,没有result
2、对于ajax结合action使用时,返回值为void类型,返回的数据使用response.getWriter().write(data),返回到ajax中。
<action name="getZone" class="com.lc.test.action.CityAction" method="getZone">
</action>
public void getZone(){
JSONObject obj = new JSONObject();
switch(city.getCity()){
case 1:
obj.put("1", "朝阳区");
obj.put("2", "东城区");
break;
}
HttpServletResponse response=ServletActionContext.getResponse();
try {
response.setCharacterEncoding("utf-8");
PrintWriter writer=response.getWriter();
writer.write(obj.toJSONString());
writer.flush();
writer.close();
//执行后一直返回到ajax的error方法中, 在error方法中输出XMLHttpRequest的状态300 4都正确。
//但是输出textStatus后是parseerror,转换错误。json返回时的转换错误。最后使用alibaba的fastjson,返回正确。
} catch (IOException e) {
e.printStackTrace();
}
}
3、对于jquery的autocomplete结合action使用时,返回值为string,正常,然后配置文件中<result type="json"></result>
<package name="auto" extends="json-default">
<action name="getArea" class="com.lc.test.action.CityAction" method="getArea">
1) <result type="json"/>//这种写法,页面上的所有的变量,有setter和getter的都可以在页面上获取使用。所有变量都在一个默认的根目录下。
2)<result type="json"><param name="root">list</param></result>//这种写法,页面上获取的默认根目录是list(list下面的变量都可以以变量名称的形式使用),list之外的任何变量都不能在页面上获取。
</action>
</package> //这里需要引入struts2-json-plugin.jar包,版本不合适,会引入很多其他问题。
public String getArea(){
System.out.println("term:"+term);
AutoBean ab=new AutoBean();
ab.setValue("jquery");
ab.setLabel("jquery");
ab.setDesc("the write less, do more, JavaScript library");
areas.add(ab);
return SUCCESS;
}