关闭

第八章AJAX(3)

133人阅读 评论(0) 收藏 举报
分类:

【第 19-25 节19-AJAX案例:学生增删改查1 -7】

     案例:用AJAX实现t_students的增删改查CRUD

     练习:AJAX注册、带验证码,实现AJAX检查用户名是否可用;

     练习:用AJAX实现t_teachers、t_classes的CRUD

 

项目:

【StudentAjax.jsp】
【AjaxResult.java】
【JdbcUtils.java】
【MinZuDAO.java】
【MinZuInfo.java】
【RupengUtils.java】
【StudentAjaxServlet.java】
【StudentDAO.java】
【StudentInfo.java】
【ClassDAO.java】
【ClassInfo.java】
【ClassServlet.java】

 

【StudentAjax.jsp】

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生管理</title>
<style type="text/css" >
#dialog{position: absolute;
top: 0;
left: 0;
right:0;
bottom:0;
width:100%;
height:100%;
background-color: #8FB0D1;
-moz-opacity: 0.8;
opacity:0.8;
z-index:1001;
filter: alpha(opacity=40);}
</style>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
var deleteById = function(id)
{
	$.ajax({type:"POST",dataType:"json",url:"student",data:{action:'deleteById',id:id},
		success:reloadData,//删除成功刷新列表
		error:function(){alert("删除失败");}
	});
}

var editByIdSuccess=function(obj)
{
	if(obj.errorCode=="idNotFound")
	{
		alert("查无此人");
	}
	else if(obj.errorCode=="ok")
	{
		$("#divEdit").show();//显示"编辑"这个层
		
		$("#editId").val(obj.data.id);
		$("#editName").val(obj.data.name);
		$("#editGender").val(obj.data.gender?"male":"female");
		$("#editBirthDay").val(obj.data.birthDay);
		$("#editTeChangSheng").val(obj.data.teChangSheng);
		$("#editMinZuId").val(obj.data.minZuId);
	}
}

var editById = function(id)
{
	$.ajax({type:"POST",dataType:"json",url:"student",data:{action:'getById',id:id},
		success:editByIdSuccess,
		error:function(){alert("编辑加载数据出错!");}
	});
}

var reloadDataSuccess = function(obj){
	
	$("#stuBody").html("");//清除上一次reloadDataSuccess的时候生成tr
	var students = obj.data;
	for(var i=0;i<students.length;i++)
	{
		var student = students[i];
		/*
		$("#stuBody").append($("<tr><td><input type='button' onclick='deleteById("+student.id+")' name='delete' value='删除' /></td><td>"+student.name+"</td><td>"
			+(student.gender?"男":"女")+"</td><td>"+student.birthDay+"</td><td>"+
			(student.teChangSheng?"是":"不是")+"</td></tr>"));*/
			/*
		$("#stuBody").append($("<tr><td><input type='button' name='delete' value='删除' studentId="+student.id+" /></td><td>"+student.name+"</td><td>"
			+(student.gender?"男":"女")+"</td><td>"+student.birthDay+"</td><td>"+
			(student.teChangSheng?"是":"不是")+"</td></tr>"));*/
			$("#stuBody").append($("<tr><td><input type='button' name='delete' value='删除' studentId='"+student.id
				+"'/></td><td><input type='button' name='edit' value='编辑' studentId='"+student.id+"'/></td><td>"+student.name+"</td><td>"
			+(student.gender?"男":"女")+"</td><td>"+student.birthDay+"</td><td>"+
			(student.teChangSheng?"是":"不是")+"</td></tr>"));
	}
	
	//动态生成元素生成后,再添加删除按钮的监听
	//$("input[name=delete]").click(function(){alert($(this).attr("haha"));});
	$("input[name=delete]").click(function(){ var stuId =$(this).attr("studentId");  deleteById(stuId);});
	$("input[name=edit]").click(function(){var stuId=$(this).attr("studentId");editById(stuId);});
};

//刷新学生数据
var reloadData=function(){
	$.ajax({type:"POST",dataType:"json",url:"student",
		data:{action:"getAll"},
		success:reloadDataSuccess,
		error:function(){alert("加载列表失败");}
	});
}

//加载学生数据到两个下拉列表
var getAllClassSuccess =function(obj)
{
	var classes = obj.data;
	for(var i=0;i<classes.length;i++)
	{
		var classInfo = classes[i];
		var option = "<option value="+classInfo.id+">"+classInfo.name+"</option>";
		
		$("#classId").append($(option));//新增的班级下拉列表
		$("#editClassId").append($(option));//编辑的班级下拉列表
	}
}

//加载民族数据到两个下拉列表
var getAllMinZuSuccess = function(obj)
{
	var minzus = obj.data;
	for(var i=0;i<minzus.length;i++)
	{
		var minzu = minzus[i];
		var option = "<option value="+minzu.id+">"+minzu.name+"</option>";
		$("#minZuId").append($(option));
		
		$("#editMinZuId").append($(option));
	}
}

var addnewSubmitSuccess = function(obj)
{
	//$("#dialog").hide();//隐藏“loading”遮罩层
	if(obj.errorCode=="error")
	{
		alert("保存出错:"+obj.data);
	}
	else if(obj.errorCode=="ok")
	{
		alert("保存成功");
		reloadData();//重新数据列表
		$("#divAddNew").hide();//隐藏"新增"的层
	}
}

var editSubmitSuccess=function(obj)
{
	alert("保存成功");
	reloadData();//重新数据列表
	$("#divEdit").hide();
}

$(function(){
	//$("body").bind("ajaxSend",function(){alert("ajaxSend");});//页面中任何ajax请求发起之前ajaxSend都会触发
	//$("body").bind("ajaxComplete",function(){alert("ajaxComplete");});//页面中任何ajax请求处理完成后,ajaxComplete都会触发
	$("body").bind("ajaxSend",function(){$("#dialog").show();});//ajax请求之前显示遮罩层
	$("body").bind("ajaxComplete",function(){$("#dialog").hide();});//ajax请求完成后隐藏遮罩层
	$("body").bind("ajaxError",function(){alert("服务器处理失败AJAX");});
	
	reloadData();
	$("#btnRefresh").click(reloadData);
	//alert($("input[name=delete]").length);  //删除按钮还没有创建
	//$("input[name=delete]").click(function(){alert($(this).attr("haha"));});
	//jquery 中$().click()给已经存在的元素添加事件
	//$().live("click",)是给动态生成的元素添加事件
	//jquery 1.9之后不支持live
	//$("input[name=delete]").live("click",function(){alert($(this).attr("haha"));});
	
	$("#btnAddNew").click(function(){
		$("#name").val("");//清空上一次新增填的内容
		$("#birthDay").val("");
		$("#divAddNew").show();//点击新增的时候显示“新增”的层
	});
	$("#btnCancel").click(function(){
		$("#divAddNew").hide();//隐藏“新增”的层
	});
	
	$.ajax({type:"POST",dataType:"json",url:"class",data:{action:"getAll"},
		success:getAllClassSuccess,
		error:function(){alert("加载班级列表失败");}
	});

	$.ajax({type:"POST",dataType:"json",url:"minzu",data:{action:"getAll"},
		success:getAllMinZuSuccess,
		error:function(){alert("加载民族列表失败");}
	});
	
	$("#btnSave").click(function(){
		//todo:检查所有字段都填写了
		var name = $("#name").val();
		var gender = $("#gender").val();
		var birthDay = $("#birthDay").val();
		var classId = $("#classId").val();
		var teChangSheng = $("#teChangSheng").attr("checked")=="checked";
		var minZuId = $("#minZuId").val();
		
		//$("#dialog").show();//显示“loading”遮罩层
		$.ajax({type:"POST",dataType:"json",url:"student",
			data:{action:"addnewSubmit",name:name,gender:gender,birthDay:birthDay,classId:classId,teChangSheng:teChangSheng,minZuId:minZuId},
			success:addnewSubmitSuccess,
			error:function(){$("#dialog").hide();alert("保存AJAX请求失败");}
		});
	});
	
	$("#btnEditSave").click(function(){
		var id = $("#editId").val();
		var name = $("#editName").val();
		var gender = $("#editGender").val();
		var birthDay = $("#editBirthDay").val();
		var classId = $("#editClassId").val();
		var teChangSheng = $("#editTeChangSheng").attr("checked")=="checked";
		var minZuId = $("#editMinZuId").val();
		
		$.ajax({type:"POST",dataType:"json",url:"student",
			data:{action:"editSubmit",id:id,name:name,gender:gender,birthDay:birthDay,classId:classId,teChangSheng:teChangSheng,minZuId:minZuId},
			success:editSubmitSuccess,
			error:function(){alert("保存AJAX请求失败");}
		});
	});
	
	
});
</script>
</head>
<body>
<div id="dialog" style="display:none">
   <img src="loading.gif"/>
</div>
<input type="button" id="btnAddNew" value="新增"/>
<input type="button" id="btnRefresh" value="刷新"/>
<table>
	<thead>
		<tr><td>删除</td><td>编辑</td><td>姓名</td><td>性别</td><td>出生日期</td><td>是否特长生</td></tr>
	</thead>
	<tbody id="stuBody">
		
	</tbody>
</table>
<br/>
<div id="divAddNew" style="display:none;background-color:gray">
	姓名:<input type="text" id="name"/>性别:<select id="gender"><option value='male'>男</option><option value='female'>女</option></select><br/>
	出生日期:<input type="text" id="birthDay"/> 班级:<select id="classId"></select><br/>
	是否特长生:<input type="checkbox" id="teChangSheng"/>民族:<select id="minZuId"></select><br/>
	<input type="button" value="保存" id="btnSave"/>
	<input type="button" value="取消" id="btnCancel"/>
</div>

<div id="divEdit" style="display:none;background-color:gray">
	<input type="hidden" id="editId"/>
	姓名:<input type="text" id="editName"/>
	性别:<select id="editGender"><option value='male'>男</option><option value='female'>女</option></select><br/>
	出生日期:<input type="text" id="editBirthDay"/> 班级:<select id="editClassId"></select><br/>
	是否特长生:<input type="checkbox" id="editTeChangSheng"/>民族:<select id="editMinZuId"></select><br/>
	<input type="button" value="保存" id="btnEditSave"/>
	<input type="button" value="取消" id="btnCancelEdit"/>
</div>


</body>
</html>

【AjaxResult.java】

package com.rupeng.web6;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

//把逻辑错误码放到errorCode中,把返回给浏览器的数据放到data中
public class AjaxResult
{
	private String errorCode;//"ok","error"
	private Object data;//返回的数据
	public String getErrorCode()
	{
		return errorCode;
	}
	public void setErrorCode(String errorCode)
	{
		this.errorCode = errorCode;
	}
	public Object getData()
	{
		return data;
	}
	public void setData(Object data)
	{
		this.data = data;
	}
	
	@Override
	public String toString()
	{		
		//Gson gson = new Gson();
		Gson gson = new GsonBuilder()  
		  .setDateFormat("yyyy-MM-dd")  
		  .create(); 
		return gson.toJson(this);
	}
}

【JdbcUtils.java】

 

【MinZuDAO.java】

package com.rupeng.web6;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class MinZuDAO
{
	public List<MinZuInfo> getAll()
	{
		List<MinZuInfo> list = new LinkedList<MinZuInfo>();
		ResultSet rs = null;
		try
		{
			rs = JdbcUtils.executeQuery("select * from T_MinZus");
			while(rs.next())
			{
				list.add(toModel(rs));
			}
			return list;
		} catch (SQLException e)
		{
			throw new RuntimeException(e);
		} finally
		{
			JdbcUtils.closeAll(rs);
		}
	}
	
	private MinZuInfo toModel(ResultSet rs) throws SQLException
	{
		MinZuInfo info = new MinZuInfo();
		info.setId(rs.getInt("Id"));
		info.setName(rs.getString("Name"));
		return info;
	}
}

【MinZuInfo.java】

package com.rupeng.web6;

public class MinZuInfo
{
	private int id;
	private String name;
	public int getId()
	{
		return id;
	}
	public void setId(int id)
	{
		this.id = id;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	
}

【RupengUtils.java】

package com.rupeng.web6;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RupengUtils
{
	/**
	 * 从请求中获取名字为name的值,解决中文乱码问题
	 * @param req
	 * @param name
	 * @return
	 */
	public static String getParameter(HttpServletRequest request, String name)
	{
		try
		{
			String value = request.getParameter(name);
			byte[] bytes;
			bytes = value.getBytes("ISO-8859-1");
			return new String(bytes, "UTF-8");
		} catch (UnsupportedEncodingException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 在/Error.jsp中显示错误消息
	 * @param request
	 * @param response
	 * @param msg
	 * @throws ServletException
	 * @throws IOException
	 */
	public static void showError(HttpServletRequest request,HttpServletResponse response,String msg)
	throws ServletException, IOException
	{
		request.setAttribute("errorMsg", msg);
		request.getRequestDispatcher("/Error.jsp").forward(request, response);
	}
	
	/**
	 * 判断一个字符串是否是null或者是否是长度为0的字符串
	 * @param s
	 * @return
	 */
	public static boolean isNullOrEmpty(String s)
	{
		return s==null||s.length()<=0;
	}
	
	/**
	 * 设置返回ajax的响应的ContentType以及编码
	 * @param resp
	 */
	public static void initAjaxResponse(HttpServletResponse resp)
	{
		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");

	}
}

【StudentAjaxServlet.java】

package com.rupeng.web6;

import java.io.IOException;
import java.sql.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StudentAjaxServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		String action = req.getParameter("action");
		if(RupengUtils.isNullOrEmpty(action))
		{
			req.getRequestDispatcher("/StudentAjax.jsp").forward(req, resp);
		}
		else if(action.equals("getAll"))
		{
			try
			{
				Thread.sleep(5000);
			} catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			RupengUtils.initAjaxResponse(resp);
			
			StudentDAO studentDao = new StudentDAO();
			List<StudentInfo> students =  studentDao.getAll();
			AjaxResult result = new AjaxResult();
			result.setErrorCode("ok");
			result.setData(students);
			resp.getWriter().print(result.toString());
		}else if(action.equals("deleteById"))
		{
			int id = Integer.parseInt(req.getParameter("id"));
			new StudentDAO().delete(id);
			AjaxResult result = new AjaxResult();
			result.setErrorCode("ok");
			resp.getWriter().print(result.toString());
		}
		else if(action.equals("addnewSubmit"))
		{
			try
			{
				Thread.sleep(5000);
			} catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			AjaxResult result = new AjaxResult();
			try
			{			
				String name = req.getParameter("name");
				String gender = req.getParameter("gender");
				String birthDay = req.getParameter("birthDay");
				String classId = req.getParameter("classId");
				String teChangSheng = req.getParameter("teChangSheng");
				String minZuId = req.getParameter("minZuId");
				
				StudentInfo student = new StudentInfo();
				student.setName(name);
				student.setGender("male".equals(gender));
				student.setBirthDay(Date.valueOf(birthDay));
				student.setClassId(Integer.parseInt(classId));
				student.setTeChangSheng(Boolean.parseBoolean(teChangSheng));
				student.setMinZuId(Integer.parseInt(minZuId));
				
				new StudentDAO().addnew(student);
				result.setErrorCode("ok");
			}
			catch(Exception ex)
			{
				result.setErrorCode("error");
				result.setData(ex.getMessage());
			}	
			RupengUtils.initAjaxResponse(resp);
			resp.getWriter().print(result.toString());
		}
		else if(action.equals("getById"))
		{
			RupengUtils.initAjaxResponse(resp);
			int id = Integer.parseInt(req.getParameter("id"));
			StudentInfo stu = new StudentDAO().getById(id);
			
			AjaxResult result = new AjaxResult();
			if(stu==null)
			{
				result.setErrorCode("idNotFound");//没有这样的id
			}
			else
			{
				result.setErrorCode("ok");
				result.setData(stu);
			}	
			
			resp.getWriter().print(result.toString());
		}
		else if(action.equals("editSubmit"))
		{
			RupengUtils.initAjaxResponse(resp);
			int id = Integer.parseInt(req.getParameter("id"));
			String name = req.getParameter("name");
			String gender = req.getParameter("gender");
			String birthDay = req.getParameter("birthDay");
			String classId = req.getParameter("classId");
			String teChangSheng = req.getParameter("teChangSheng");
			String minZuId = req.getParameter("minZuId");
			
			StudentInfo student = new StudentInfo();
			student.setId(id);			
			student.setName(name);
			student.setGender("male".equals(gender));
			student.setBirthDay(Date.valueOf(birthDay));
			student.setClassId(Integer.parseInt(classId));
			student.setTeChangSheng(Boolean.parseBoolean(teChangSheng));
			student.setMinZuId(Integer.parseInt(minZuId));
			
			new StudentDAO().update(student);
			AjaxResult result = new AjaxResult();
			result.setErrorCode("ok");
			resp.getWriter().print(result);
		}
	}
}

【StudentDAO.java】

package com.rupeng.web6;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class StudentDAO
{

	public void addnew(StudentInfo student)
	{
		try
		{
			JdbcUtils.executeUpdate(
							"Insert into T_Students(Name,Gender,BirthDay,ClassId,TeChangSheng,MinZuId) values(?,?,?,?,?,?)",
							student.getName(), student.isGender(), student.getBirthDay(),student.getClassId(),
							student.isTeChangSheng(),student.getMinZuId());
		} catch (SQLException e)
		{
			//封装成RuntimeException主要为了调用者方便
			throw new RuntimeException(e);
		}
	}
	
	public void update(StudentInfo student)
	{
		try
		{
			JdbcUtils.executeUpdate("Update T_Students set Name=?,Gender=?,BirthDay=?,ClassId=?,TeChangSheng=?,MinZuId=? where Id=?",
					student.getName(),student.isGender(),student.getBirthDay(),student.getClassId(),student.isTeChangSheng(),
					student.getMinZuId(),student.getId());
		} catch (SQLException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	public void delete(int id)
	{
		try
		{
			JdbcUtils.executeUpdate("delete from T_Students where Id=?", id);
		} catch (SQLException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	public StudentInfo getById(int id)
	{
		ResultSet rs = null;
		try
		{
			rs = JdbcUtils.executeQuery("select * from T_Students where Id=?", id);
			if(rs.next())
			{
				return toModel(rs);
			}
			else
			{
				return null;//一条数据都没有,也就是没有找到id=id的数据
			}
		} catch (SQLException e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
			JdbcUtils.closeAll(rs);
		}
	}
	
	private StudentInfo toModel(ResultSet rs) throws SQLException
	{
		StudentInfo info = new StudentInfo();
		info.setId(rs.getInt("Id"));
		info.setName(rs.getString("Name"));
		info.setGender(rs.getBoolean("Gender"));
		info.setBirthDay(rs.getDate("BirthDay"));
		info.setClassId(rs.getInt("ClassId"));
		info.setTeChangSheng(rs.getBoolean("TeChangSheng"));
		info.setMinZuId(rs.getInt("MinZuId"));
		return info;
	}
	
	public List<StudentInfo> getAll()
	{
		ResultSet rs = null;
		try
		{
			rs = JdbcUtils.executeQuery("select * from T_Students");
			List<StudentInfo> list = new LinkedList<StudentInfo>();
			while(rs.next())
			{
				list.add(toModel(rs));
			}
			return list;
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
			JdbcUtils.closeAll(rs);
		}
	}
}

【StudentInfo.java】

package com.rupeng.web6;

import java.sql.Date;

public class StudentInfo
{
	private int id;
	private String name;
	private boolean gender;
	private Date birthDay;
	private int classId;
	private boolean teChangSheng;
	private int minZuId;

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		//return "rupeng";
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public boolean isGender()
	{
		return gender;
	}

	public void setGender(boolean gender)
	{
		this.gender = gender;
	}

	public Date getBirthDay()
	{
		return birthDay;
	}

	public void setBirthDay(Date birthDay)
	{
		this.birthDay = birthDay;
	}

	public int getClassId()
	{
		return classId;
	}

	public void setClassId(int classId)
	{
		this.classId = classId;
	}

	//对于boolean类型的属性,获取方法既可以以get开头又可以以is开头
	//如果既有get方法又有is方法,则is方法优先级高
	
	//vip、gender(性别)。He is vip。He is Gender。His Gender is male。
	//isVIP、getGender()
	//isTeChangSheng
	
	//
	/*
	public boolean isTeChangSheng()
	{
		return true;
	}*/
	
	public boolean isTeChangSheng()
	//public boolean getTeChangSheng()
	{
		return teChangSheng;
	}

	public void setTeChangSheng(boolean teChangSheng)
	{
		this.teChangSheng = teChangSheng;
	}

	public int getMinZuId()
	{
		return minZuId;
	}

	public void setMinZuId(int minZuId)
	{
		this.minZuId = minZuId;
	}

}

【ClassDAO.java】

package com.rupeng.web6;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class ClassDAO
{
	private ClassInfo toModel(ResultSet rs) throws SQLException
	{
		ClassInfo info = new ClassInfo();
		info.setId(rs.getInt("Id"));
		info.setName(rs.getString("Name"));
		info.setRoomNum(rs.getString("RoomNum"));
		info.setTeacherId(rs.getInt("TeacherId"));
		return info;
	}
	
	public List<ClassInfo> getAll()
	{
		List<ClassInfo> list = new LinkedList<ClassInfo>();
		ResultSet rs = null;
		try
		{
			rs = JdbcUtils.executeQuery("select * from T_Classes");
			while(rs.next())
			{
				list.add(toModel(rs));
			}
			return list;
		} catch (SQLException e)
		{
			throw new RuntimeException(e);
		} finally
		{
			JdbcUtils.closeAll(rs);
		}
	}
}

【ClassInfo.java】

package com.rupeng.web6;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class ClassDAO
{
	private ClassInfo toModel(ResultSet rs) throws SQLException
	{
		ClassInfo info = new ClassInfo();
		info.setId(rs.getInt("Id"));
		info.setName(rs.getString("Name"));
		info.setRoomNum(rs.getString("RoomNum"));
		info.setTeacherId(rs.getInt("TeacherId"));
		return info;
	}
	
	public List<ClassInfo> getAll()
	{
		List<ClassInfo> list = new LinkedList<ClassInfo>();
		ResultSet rs = null;
		try
		{
			rs = JdbcUtils.executeQuery("select * from T_Classes");
			while(rs.next())
			{
				list.add(toModel(rs));
			}
			return list;
		} catch (SQLException e)
		{
			throw new RuntimeException(e);
		} finally
		{
			JdbcUtils.closeAll(rs);
		}
	}
}

【ClassServlet.java】

package com.rupeng.web6;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ClassServlet extends HttpServlet
{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		String action = req.getParameter("action");
		if(action.equals("getAll"))
		{
			List<ClassInfo> classes =  new ClassDAO().getAll();
			AjaxResult r = new AjaxResult();
			r.setErrorCode("ok");
			r.setData(classes);
			RupengUtils.initAjaxResponse(resp);
			resp.getWriter().print(r.toString());
		}
	}
}





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6546次
    • 积分:335
    • 等级:
    • 排名:千里之外
    • 原创:28篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条