分页和二级联动

来源:互联网 发布:cad软件购买 编辑:程序博客网 时间:2024/04/30 03:12

建一个动态Web工程和三张表:

表一:t_employee字段:e_id,e_name,e_birthday,e_job

以下为二级联动所需的表

表二:t_city字段:id,cityName,countryId(外键连接表三)

表三:t_country字段:c_id,c_name






按图中所示建包和类还有接口页面等,下面是详细的页面代码

package com.lovo.bean;


public class CityBean {
private int id;
private String cityName;
private int countryId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
@Override
public String toString() {
return "CityBean [id=" + id + ", cityName=" + cityName + ", countryId=" + countryId + "]";
}
}



package com.lovo.bean;


public class CountryBean {
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;
}
@Override
public String toString() {
return "CountryBean [id=" + id + ", name=" + name + "]";
}
}



package com.lovo.bean;


import java.util.ArrayList;
import java.util.List;


public class CutPageBean<T> {
/**当前页需要显示的数据*/
private List<T> list = new ArrayList<T>();
/**总记录数*/
private int count;
/**总页数*/
private int totalPage;

public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
@Override
public String toString() {
return "CutPageBean [list=" + list + ", count=" + count + ", totalPage=" + totalPage + "]";
}
}



package com.lovo.bean;


import java.sql.Date;


public class EmployeeBean {
private int id;
private String name;
private Date birthday;
private String job;
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;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public EmployeeBean() {
super();
// TODO Auto-generated constructor stub
}
public EmployeeBean(String name, Date birthday, String job) {
super();
this.name = name;
this.birthday = birthday;
this.job = job;
}
@Override
public String toString() {
return "EmployeeBean [id=" + id + ", name=" + name + ", birthday=" + birthday + ", job=" + job + "]";
}
}



package com.lovo.dao;


import java.util.List;


import com.lovo.bean.CityBean;


public interface ICityDao {
public List<CityBean> findByCountry(int countryId);
}



package com.lovo.dao;


import java.util.List;


import com.lovo.bean.CountryBean;


public interface ICountryDao {
public List<CountryBean> findAll();
}



package com.lovo.dao;


import com.lovo.bean.CutPageBean;
import com.lovo.bean.EmployeeBean;


public interface IEmployeeDao {
public static final int PAGESIZE = 3;
/**
* 分页产生所有员工
* @param pageNO 页码
* @return 分页对象
*/
public CutPageBean<EmployeeBean> findAll(int pageNO);
}



package com.lovo.dao.impl;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class BaseDao {
protected Connection con;
protected PreparedStatement ps;
protected ResultSet rs;

public void setConnection(){
try {
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lesson?characterEncoding=utf-8","root","1234567890");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void closeConnection(){
try {
if (rs != null) {
rs.close();
}if (ps != null) {
ps.close();
}if (con != null) {
con.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
// 测试连接
// public static void main(String[] args) {
// BaseDao dao = new BaseDao();
// dao.setConnection();
//// dao.closeConnection();
// System.out.println(dao);
// }
}



package com.lovo.dao.impl;


import java.util.ArrayList;
import java.util.List;


import com.lovo.bean.CityBean;
import com.lovo.dao.ICityDao;


public class CityDaoImpl extends BaseDao implements ICityDao{


@Override
public List<CityBean> findByCountry(int countryId) {
// TODO Auto-generated method stub
List<CityBean> list = new ArrayList<CityBean>();
this.setConnection();
try {
ps = con.prepareStatement("select * from t_city where countryId=?");
ps.setInt(1, countryId);

rs = ps.executeQuery();

while (rs.next()) {
CityBean bean = new CityBean();
bean.setId(rs.getInt("id"));
bean.setCityName(rs.getString("cityName"));
bean.setCountryId(rs.getInt("countryId"));

list.add(bean);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.closeConnection();
}
return list;
}
//public static void main(String[] args) {
// ICityDao dao = new CityDaoImpl();
// List<CityBean> list = dao.findByCountry(3);
// System.out.println(list);
//}

}




package com.lovo.dao.impl;


import java.util.ArrayList;
import java.util.List;


import com.lovo.bean.CountryBean;
import com.lovo.dao.ICountryDao;


public class CountryDaoImpl extends BaseDao implements ICountryDao{


@Override
public List<CountryBean> findAll() {
List<CountryBean> list = new ArrayList<CountryBean>();

this.setConnection();
try {
ps = con.prepareStatement("select * from t_country");
rs = ps.executeQuery();
while (rs.next()) {
CountryBean bean = new CountryBean();
bean.setId(rs.getInt("c_id"));
bean.setName(rs.getString("c_name"));

list.add(bean);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.closeConnection();
}
return list;
}
// public static void main(String[] args) {
// ICountryDao dao = new CountryDaoImpl();
// List<CountryBean> list = dao.findAll();
// System.out.println(list);
// }


}



package com.lovo.dao.impl;


import com.lovo.bean.CutPageBean;
import com.lovo.bean.EmployeeBean;
import com.lovo.dao.IEmployeeDao;


public class EmployeeDaoImpl extends BaseDao implements IEmployeeDao{


@Override
public CutPageBean<EmployeeBean> findAll(int pageNO) {
// TODO Auto-generated method stub
CutPageBean<EmployeeBean> cutBean = new CutPageBean<EmployeeBean>();
this.setConnection();

try {
ps = con.prepareStatement("select * from t_employee limit ?,?");
ps.setInt(1, (pageNO - 1) * PAGESIZE);
ps.setInt(2, PAGESIZE);

rs= ps.executeQuery();
while (rs.next()) {
EmployeeBean emBean = new EmployeeBean();
emBean.setId(rs.getInt("e_id"));
emBean.setName(rs.getString("e_name"));
emBean.setBirthday(rs.getDate("e_birthday"));
emBean.setJob(rs.getString("e_job"));

cutBean.getList().add(emBean);
}
// 得到总条数
ps = con.prepareStatement("select count(*) ecount from t_employee");
rs = ps.executeQuery();
if (rs.next()) {
cutBean.setCount(rs.getInt("ecount"));
}
// 得到总页数
if (cutBean.getCount() % PAGESIZE == 0) {
cutBean.setTotalPage(cutBean.getCount() / PAGESIZE);
}else {
cutBean.setTotalPage(cutBean.getCount() / PAGESIZE + 1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
this.closeConnection();
}

return cutBean;
}
// public static void main(String[] args) {
// IEmployeeDao dao = new EmployeeDaoImpl();
// CutPageBean<EmployeeBean> cutBean = dao.findAll(2);
// System.out.println(cutBean);
// }
}




package com.lovo.service;


import java.util.List;


import com.lovo.bean.CityBean;


public interface ICityService {
public List<CityBean> findByCountry(int countryId);
}



package com.lovo.service;


import java.util.List;


import com.lovo.bean.CountryBean;


public interface ICountryService {
public List<CountryBean> findAll();
}


package com.lovo.service;


import com.lovo.bean.CutPageBean;
import com.lovo.bean.EmployeeBean;


public interface IEmpolyeeService {
public CutPageBean<EmployeeBean> findAll(int pageNO);
}



package com.lovo.service.impl;


import java.util.List;


import com.lovo.bean.CityBean;
import com.lovo.dao.ICityDao;
import com.lovo.dao.impl.CityDaoImpl;
import com.lovo.service.ICityService;


public class CityServiceImpl implements ICityService{
private ICityDao dao = new CityDaoImpl();


@Override
public List<CityBean> findByCountry(int countryId) {
// TODO Auto-generated method stub
return dao.findByCountry(countryId);
}
}


package com.lovo.service.impl;


import java.util.List;


import com.lovo.bean.CountryBean;
import com.lovo.dao.ICountryDao;
import com.lovo.dao.impl.CountryDaoImpl;
import com.lovo.service.ICountryService;


public class CountryServiceImpl implements ICountryService{
private ICountryDao dao = new CountryDaoImpl();
@Override
public List<CountryBean> findAll() {
// TODO Auto-generated method stub
return dao.findAll();
}


}


package com.lovo.service.impl;


import org.codehaus.jackson.map.ObjectMapper;


import com.lovo.bean.CutPageBean;
import com.lovo.bean.EmployeeBean;
import com.lovo.dao.IEmployeeDao;
import com.lovo.dao.impl.EmployeeDaoImpl;
import com.lovo.service.IEmpolyeeService;


public class EmployeeServiceImpl implements IEmpolyeeService {
private IEmployeeDao dao = new EmployeeDaoImpl();
@Override
public CutPageBean<EmployeeBean> findAll(int pageNO) {
// TODO Auto-generated method stub
return dao.findAll(pageNO);
}
public static void main(String[] args) {
IEmpolyeeService service = new EmployeeServiceImpl();
CutPageBean<EmployeeBean> cutBean = service.findAll(1);

ObjectMapper om = new ObjectMapper();
try {
om.writeValue(System.out, cutBean);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}





package com.lovo.servlet;


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


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


import org.codehaus.jackson.map.ObjectMapper;


import com.lovo.bean.CountryBean;
import com.lovo.service.ICountryService;
import com.lovo.service.impl.CountryServiceImpl;


/**
 * Servlet implementation class FindAllCountry
 */
@WebServlet("/country/findAll")
public class FindAllCountryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       private ICountryService service = new CountryServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindAllCountryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
List<CountryBean> list = service.findAll();
ObjectMapper oMapper = new ObjectMapper();
oMapper.writeValue(response.getWriter(), list);
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}


}



package com.lovo.servlet;


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.codehaus.jackson.map.ObjectMapper;


import com.lovo.bean.CutPageBean;
import com.lovo.bean.EmployeeBean;
import com.lovo.service.IEmpolyeeService;
import com.lovo.service.impl.EmployeeServiceImpl;


/**
 * Servlet implementation class FindAllServlet
 */
@WebServlet("/findAll")
public class FindAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private IEmpolyeeService service = new EmployeeServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindAllServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
// 得到页码
int pageNO = Integer.parseInt(request.getParameter("pn"));
CutPageBean<EmployeeBean> cutBean = service.findAll(pageNO);

ObjectMapper om = new ObjectMapper();
om.writeValue(response.getWriter(), cutBean);
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}


}



package com.lovo.servlet;


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


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


import org.codehaus.jackson.map.ObjectMapper;


import com.lovo.bean.CityBean;
import com.lovo.service.ICityService;
import com.lovo.service.impl.CityServiceImpl;


/**
 * Servlet implementation class FindCityServlet
 */
@WebServlet("/city/findByCountryId")
public class FindCityServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       private ICityService service = new CityServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindCityServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int countryId = Integer.parseInt(request.getParameter("cid"));

List<CityBean> list = service.findByCountry(countryId);
ObjectMapper om = new ObjectMapper();
om.writeValue(response.getWriter(), list);
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}


}





package com.lovo.util;


import java.io.IOException;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;


@WebFilter("/*")
public class CharFilter implements Filter {


@Override
public void destroy() {
// TODO Auto-generated method stub

}


@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
// TODO Auto-generated method stub
arg0.setCharacterEncoding("utf-8");
arg1.setContentType("text/html;charset=utf-8");
arg2.doFilter(arg0, arg1);
}


@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}


}





<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>cutPage</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>




<%@ 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>Insert title here</title>
<script type="text/javascript" src="/cutPage/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$.post("/cutPage/country/findAll",null,function(info){
//alert(JSON.stringify(info));
var str="";
for(var i=0;i<info.length;i++){
var obj = info[i];
str += "<option value='"+obj.id+"'>"+obj.name+"</option>";
}
$("#countrySelect").html(str);
},"json");
$("#countrySelect").change(function(){
$.post("/cutPage/city/findByCountryId","cid="+this.value,function(info){
//alert(JSON.stringify(info));
var str="";
for(var i=0;i<info.length;i++){
var obj = info[i];
str += "<option value='"+obj.id+"'>"+obj.cityName+"</option>";
}
$("#citySelect").html(str);
},"json");
});
});
</script>
</head>
<body>
<select id="countrySelect" style="width:60px"></select>
<select id="citySelect" style="width:60px"></select>
</body>
</html>



<%@ 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>Insert title here</title>
<script type="text/javascript" src="/cutPage/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
cutPage(1);
});

function cutPage(pageNO){
$.post("/cutPage/findAll","pn="+pageNO,function(obj){
//将对象转换为json格式的字符串
//alert(JSON.stringify(obj));
var dataStr="";
for(var i=0;i<obj.list.length;i++){
var o = obj.list[i];
dataStr += "<tr><td>"+o.name+"</td><td>"+o.birthday+"</td><td>"+o.job+"</td></tr>";
}
$("#data").html(dataStr);

var cutStr = "";
for(var i=1;i<=obj.totalPage;i++){
cutStr += "<a href='javascript:cutPage("+i+")'>"+i+"</a>"+"&nbsp;";
}
$("#cutPageDiv").html(cutStr);

},"json");
}
</script>
</head>
<body>
<table border="1" cellspacing="0" width="60%">
<thead>
<tr><td>姓名</td><td>生日</td><td>职务</td></tr>
</thead>
<tbody id="data"></tbody>
</table>
<div id="cutPageDiv"></div>
</body>
</html>

0 0
原创粉丝点击