AJAX通过JSON显示数据,hql语句查询要对应到类

前台界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘index.jsp‘ starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
  <script type="text/javascript">
  function showplus(provinceid){
  //需要传递四个参数
  //1:提交路径,2:使用对象进行参数传递,每个参数作为对象的一个属性来传递
  //3:回调函数 4:数据类型,可以选择text,xml或json格式
  $.post("<%=basePath%>province_showplus.action",{provinceid:provinceid},showplusCallback,"json");
  }
  //jQuery自动将返回的字符串转换为对象或数组,并通过回调函数的参数直接返回,在回调函数中直接使用
  function showplusCallback(array){
 
  //使用选择器取得下拉列表对象
  var citySelect=$("#city");
  //查找到要删除的页面元素,并调用删除操作
  $("#city option:gt(0)").remove();//避免下次选中省份,底下的城市叠加
  //循环取得id和cname
  for(var i=0;i<array.length;i++){
  var cid=array[i].cid;  
  var cname=array[i].cname;  
  //jQuery创建页面元素直接使用字符串拼接即可
  var option="<option value=‘"+cid+"‘>"+cname+"</option>";
  //将option设置为城市select的子节点
  citySelect.append(option);
  }
  }
  </script>
  </head>
  
  <body>欢迎<a href="province_indexPre.action">测试吧</a>
  <br/>
    <select id="province" name="province" onchange="showplus(this.value)">
    <option value="0">--请选择--</option>
    <c:forEach items="${allProvince}" var="p">
    <option value="${p.pid}">${p.pname}</option>
    </c:forEach>
    </select>
    <select id="city" name="city">
    <option value="0">--请选择--</option>
    </select>
  </body>
</html>

action类

package com.kane.action;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONObject;
import com.kane.pojo.City;
import com.kane.pojo.Province;
import com.kane.service.IProvinceService;
import com.opensymphony.xwork2.ActionSupport;


public class ProvinceAction extends ActionSupport{
private IProvinceService provinceServiceImpl;
private List<Province> allProvince;
public List<Province> getAllProvince() {
return allProvince;
}
public void setAllProvince(List<Province> allProvince) {
this.allProvince = allProvince;
}
public int getProvinceid() {
return provinceid;
}
public void setProvinceid(int provinceid) {
this.provinceid = provinceid;
}
private int provinceid;
public IProvinceService getProvinceServiceImpl() {
return provinceServiceImpl;
}
public void setProvinceServiceImpl(IProvinceService provinceServiceImpl) {
this.provinceServiceImpl = provinceServiceImpl;
}

//点击测试吧,先进入这个action
public String indexPre() throws Exception {
allProvince=provinceServiceImpl.findAll();

return "index";
}
/**
 * AJAX调用的方法,返回null、
 * 
 * @return
 * @throws Exception 
 */
public String showplus() throws Exception {
//使用json字符串拼接,单线程stringbuffer效率高,多线程stringbuilder效率高
StringBuilder sBuilder=new StringBuilder();
List<City> list=provinceServiceImpl.showplus(provinceid);
Iterator<City> iter=list.iterator();
/* sBuilder.append("[");

int index=0;
while (iter.hasNext()) {
City city=iter.next();
if(index>0){
sBuilder.append(",");//除了第一个,每个对象前面加逗号
}
sBuilder.append("{‘cid‘:"+city.getCid());
sBuilder.append(",");
sBuilder.append("‘cname‘:‘"+city.getCname()+"‘");
sBuilder.append("}");
index++;
}
sBuilder.append("]");*/

// 使用org.json包提供的类来拼写内容
// 建立一个数组
JSONArray array = new JSONArray();

while (iter.hasNext()) {
City c = iter.next();
JSONObject obj = new JSONObject();
// 为对象设置属性, 类似Map
obj.put("cid", c.getCid());
obj.put("cname", c.getCname());
array.put(obj);
}
HttpServletResponse response=ServletActionContext.getResponse();
//设置编码,防止数据出现乱码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");//字符串和json采用这种方式,xml采用text/xml
//写到前台必须用到printwriter
PrintWriter out=response.getWriter();
out.print(array);//这里的array对应前台回调函数的参数
out.close();//ajax第四步
return null;
}
}


action的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="provinceServiceImpl" class="com.kane.service.Impl.ProvinceServiceImpl">
<property name="provinceImpl">
<ref bean="provinceImpl" />
</property>
<property name="cityImpl">
<ref bean="cityImpl" />
</property>
</bean>


</beans>

显示结果



daoImpl

package com.kane.dao.Impl;

import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.kane.dao.ICity;
import com.kane.pojo.City;

public class CityImpl extends HibernateDaoSupport implements ICity {

public List<City> findById(Integer id) throws Exception {
String hql="FROM City AS c WHERE c.province.pid=?";//对应到pojo类
List<City> all = super.getHibernateTemplate().find(hql, id);
return all;
}


}

//点击省份应该显示对应的城市列表


插句话,建立测试case,新建的时候就得选择testcase 4.0


serviceImpl


package com.kane.service.Impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.kane.dao.ICity;
import com.kane.dao.IProvince;
import com.kane.pojo.City;
import com.kane.pojo.Province;
import com.kane.service.IProvinceService;
/**
 * 由AOP解决预处理和断开连接的工作
 * @author lenovo
 *
 */
public class ProvinceServiceImpl implements IProvinceService{
private IProvince provinceImpl;
private ICity cityImpl;
public ICity getCityImpl() {
return cityImpl;
}

public void setCityImpl(ICity cityImpl) {
this.cityImpl = cityImpl;
}


public IProvince getProvinceImpl() {
return provinceImpl;
}


public void setProvinceImpl(IProvince provinceImpl) {
this.provinceImpl = provinceImpl;
}

public void delete(int id) throws Exception {
// TODO Auto-generated method stub

}


public void insert(Province pro) throws Exception {
// TODO Auto-generated method stub

}

public List<Province> insertPre() throws Exception {
// TODO Auto-generated method stub
return null;
}

public Map<String, Object> list(int pageNo, int pageSize, String keyword,
String column) throws Exception {
Map<String,Object> map=new HashMap<String, Object>();
map.put("allProvince", provinceImpl.findByPage(pageNo, pageSize, column, keyword));
map.put("allCount", provinceImpl.getCount(column, keyword));
return map;
}


public List<City> showplus(int pid) throws Exception {
List<City> list=cityImpl.findById(pid);
return list;
}
}



AJAX通过JSON显示数据,hql语句查询要对应到类,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。