调用action常见问题和返回方式总结
1.action not found
(1)确定Struts2配置文件中是否定义了该action,若存在,则对比一下和页面提交的url的action是否一致,常出现首字母大小写不一致问题
(2)页面提交的url中的参数类型,和action中定义的变量类型是否一致,常遇到int和string不一致的问题
(3)在JSP中定义basepath,在url前加上这个basepath
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
(4)查看自己的Struts拦截器,是否对某些特定的参数进行了过滤拦截
2action返回的类型
(1)常规
request.setAttribute("dataList", resultList);
(2)返回Json串
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
JSONObject responseObject = new JSONObject();
esponseObject.put("result", ispass == true ? "1" : "0");
responseObject.put("resultText", resultStr);
response.getWriter().print(responseObject.toString());
response.getWriter().close();
当然需要加上try catch ,可以将response.setXXX和response.getXXX以及try catch提成一个公用方法这样就可以很方面的使用
public void printJsonResult(String responseText) {
try {
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().print(responseText);
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
若要返回一个List,可以用JSONArray
JSONArray dataArrayList=JSONArray.fromObject(datalist);
responseObject.put("dataArrayList", dataArrayList);
若要返回一个Map
JSONArray obj = JSONArray.fromObject(resultList);
HashMap<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("data", obj);
JSONObject dataObject = JSONObject.fromObject(dataMap);
printJsonResult(dataObject.toString());