Struts2返回json格式数据代码实例
最近由于工作原因,没时间更新,开始吧~~
关于json的返回需要用到一个工具包来将书转换为json格式,在此用到的jar包为:
import net.sf.json.JSONArray; //将数据转换为JSON数组
import net.sf.json.JSONObject; //将数据转换为JSON对象
dao层的代码
public class ProInfomaDao extends HibernateDaoSupport {
private Logger logger = Logger.getLogger(ProInfomaDao.class);
/**
* 查询所有数据
* @return
*/
@SuppressWarnings("unchecked")
public List<BanknameDto> selBankList() {
String sql = "SELECT DISTINCT ENAME FROM PM_PROINFO"; //填写对应的SQL语句
List<String> queryList = getSession().createSQLQuery(sql).list();
List<BanknameDto> bankList = new ArrayList<BanknameDto>();
queryList.add(0, "--请选择--");
BanknameDto bankDto = null;
if(queryList.size() == 0){
logger.info("查不到相关信息!");
}else{
for(int i = 0;i < queryList.size();i++){
bankDto = new BanknameDto();
if(i == 0){
bankDto.setId(String.valueOf(i+1));
bankDto.setText(queryList.get(i));
bankDto.setSelected("true");
}else{
bankDto.setId(String.valueOf(i+1));
bankDto.setText(queryList.get(i));
}
bankList.add(bankDto);
}
}
return bankList; //此处用到hibernate来查询数据,返回结果为一个[demo1,demo2,demo3]的List集合
}
}
service层代码
public class ProInfomaService {
private ProInfomaDao proInfomaDao;
public void setProInfomaDao(ProInfomaDao proInfomaDao) {
this.proInfomaDao = proInfomaDao;
}
/**
* 查询数据
* @return
*/
public List<BanknameDto> selBankList(){
return proInfomaDao.selBankList();
}
}
web层
public class ProInfomaAction extends ActionSupport implements ServletRequestAware{
private static final long serialVersionUID = 1L;
private ProInfomaService proInfomaService;
private Map<String, Object> resultMap = new HashMap<String, Object>();
private JSONObject dataroot;
private JSONArray bankroot; //此处要返回的属性名称,以bankroot为例,要与struts中
private JSONArray projroot; //<param name="root">bankroot</param>且提供get set方法
private HttpServletRequest request;
/**
* 查询银行名称
* @return
*/
public String selBankList() {
List<BanknameDto> selBank = proInfomaService.selBankList();
bankroot = JSONArray.fromObject(selBank);
return SUCCESS;
}
public JSONArray getBankroot() {
return bankroot;
}
public void setBankroot(JSONArray bankroot) {
this.bankroot = bankroot;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
struts2中action的配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="proInfo" namespace="/" extends="json-default">
<!--此处返回json只可以用json-default result结果集可以改变返回参数的名称 -->
<action name="query" class="noticeAction" method="selBankList">
<result name="success" type="json">
</result>
<result name="returnMap" type="json">
<param name="root">bankroot</param>
</result>
</action>
</struts>
以上是 Struts2返回json格式数据代码实例 的全部内容, 来源链接: utcz.com/z/332300.html