JavaWeb學習筆記及案例(二)MVC設計模式
1.MVC三層架構
M:Model>>>模型層:封裝資料Java Bean;
V:View>>>檢視層:jsp專注顯示;
C:Controller>>>控制層:Servlet接收頁面請求,找模型層處理,然後響應資料出去;
**好處:**分層,邏輯清楚,便於維護,擴充套件方便;【適用大型專案】
**缺點:**小型專案,程式碼稍多;
三層架構與MVC的關係
2.實戰案例:學生管理系統
整個專案工程佈局圖
環境搭建,準備工作
第一步:1.資料庫建表,新增資料;
mysql> create table stu( -> id int primary key not null auto_increment, -> name varchar(20), -> gender varchar(2), -> phone varchar(12), -> birthday date, -> hobby varchar(50), -> info varchar(200) -> ); Query OK, 0 rows affected
需要匯入必要的jar包
2.資料庫連線c3p0配置檔案【c3p0-config.xml】
一般只需修改預設配置即可
<c3p0-config> <!-- default-config 預設的配置, --> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost/students</property> <property name="user">root</property> <property name="password">123456</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <!-- This app is massive! --> <named-config name="oracle"> <property name="acquireIncrement">50</property> <property name="initialPoolSize">100</property> <property name="minPoolSize">50</property> <property name="maxPoolSize">1000</property> <!-- intergalactoApp adopts a different approach to configuring statement caching --> <property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property> <!-- he's important, but there's only one of him --> <user-overrides user="master-of-the-universe"> <property name="acquireIncrement">1</property> <property name="initialPoolSize">1</property> <property name="minPoolSize">1</property> <property name="maxPoolSize">5</property> <property name="maxStatementsPerConnection">50</property> </user-overrides> </named-config> </c3p0-config>
3.封裝JDBCUtil.java用來獲取來連線,一般放在util包下
package Student.util; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class JDBCUtil { static ComboPooledDataSource dataSource = null; static{ dataSource = new ComboPooledDataSource(); } public static DataSource getDataSource(){ return dataSource; } /** * 獲取連線物件 * @return * @throws SQLException */ public static Connection getConn() throws SQLException{ return dataSource.getConnection(); } /** * 釋放資源 * @param conn * @param st * @param rs */ public static void release(Connection conn , Statement st , ResultSet rs){ closeRs(rs); closeSt(st); closeConn(conn); } public static void release(Connection conn , Statement st){ closeSt(st); closeConn(conn); } private static void closeRs(ResultSet rs){ try { if(rs != null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ rs = null; } } private static void closeSt(Statement st){ try { if(st != null){ st.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ st = null; } } private static void closeConn(Connection conn){ try { if(conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ conn = null; } } }
4.同樣在util包下建立一個TextUtil,用來判斷字元是否為空
/**
* @author Leonard
* 判斷一個字串是否為空
*/
public class TextUtils {
public static boolean isEmpty(CharSequence s){
return s==null || s.length()==0;
}
}
接下開始寫專案了。。。。。。。。。。。。。。。。。
寫專案
專案完成預覽圖
進入第一個列表
分頁顯示頁面
第一步:建立jsp頁面及對應的Servlet
1.建立index.jsp顯示頁面
<body>
//超連結的地址是Servlet控制層
<h3><a href="StudentListServlet">顯示所有學生列表</a></h3><br>
<h3><a href="StudentListPageServlet?currentPage=1">分頁顯示所有學生列表</a></h3>
</body>
StudentListServlet.java
public class StudentListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
StudentService service = new StudentServiceImpl();
List<Student> list = service.findAll();
//把結果存域
request.getSession().setAttribute("list", list);
//重定向方式,把結果存到session域需要
response.sendRedirect("list.jsp");
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
StudentListPageServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.獲取需要顯示的頁碼數
int currentPage = Integer.parseInt(request.getParameter("currentPage"));
//2.根據指定頁數獲取該頁資料回來;
StudentService service = new StudentServiceImpl();
PageBean pageBean = service.findStudentByPage(currentPage);
request.setAttribute("pageBean", pageBean);
//3.跳轉頁面
request.getRequestDispatcher("list_page.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
2.查詢顯示頁面list.jsp
html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function doDelete(sid){
var flag = confirm("是否刪除?");
if(flag){
location.href="DeleteServlet?sid="+sid;
}
}
</script>
<title>學生列表頁面</title>
</head>
<body>
<form action="SearchStudentServlet" method="post">
<table border="1" cellspacing="0">
<tr>
<td colspan="8">
按姓名查詢:<input type="text" name="sname">
按性別查詢:<select name="gender" >
<option value="">--請選擇--
<option value="男">男
<option value="女">女
</select>
<input type="submit" value="查詢">
<a href="add.jsp">新增</a>
</td>
</tr>
<tr>
<td>編號</td>
<td>姓名</td>
<td>性別</td>
<td>電話</td>
<!-- <td>生日</td> -->
<td>愛好</td>
<td>簡介</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="stu">
<tr>
<td>${stu.sid}</td>
<td>${stu.sname}</td>
<td>${stu.gender}</td>
<td>${stu.phone}</td>
<%-- <td>${stu.birthday}</td> --%>
<td>${stu.hobby}</td>
<td>${stu.info}</td>
<td><a href="EditServlet?sid=${stu.sid}">更新</a> <a href="#" onclick="doDelete(${stu.sid})">刪除</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
SearchStudentServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.中文
request.setCharacterEncoding("UTF-8");
//2.獲取前臺資料
String sname = request.getParameter("sname");
String gender = request.getParameter("gender");
//3.呼叫service
StudentService service = new StudentServiceImpl();
List<Student> list = service.SearchStudentList(sname, gender);
System.out.println("list集合大小========"+list.size());
for (Student student : list) {
System.out.println(student);
}
request .setAttribute("list", list);
request.getRequestDispatcher("list.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
EditServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
int sid = Integer.parseInt(request.getParameter("sid"));
//查資料
StudentService service = new StudentServiceImpl();
Student student = service.findStudentById(sid);
//存資料
request.setAttribute("stu", student);
//跳轉
request.getRequestDispatcher("edit.jsp").forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
DeleteServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
int sid = Integer.parseInt(request.getParameter("sid"));
StudentService service = new StudentServiceImpl();
service.delete(sid);
request.getRequestDispatcher("StudentListServlet").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
3.新增資料頁面add.jsp
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增學生頁面</title>
</head>
<body>
<form action="AddServlet" method="post">
<table border="1" width="600">
<tr>
<td>姓名</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>性別</td>
<td>
<input type="radio" name="gender" value="男" checked="checked">男
<input type="radio" name="gender" value="女">女
</td>
</tr>
<tr>
<td>電話</td>
<td><input type="text" name="phone"></td>
</tr>
<!-- <tr>
<td>生日</td>
<td><input type="text" name="birthday"></td>
</tr> -->
<tr>
<td>愛好</td>
<td>
<input type="checkbox" name="hobby" value="籃球">籃球
<input type="checkbox" name="hobby" value="跑步">跑步
<input type="checkbox" name="hobby" value="讀書">讀書
<input type="checkbox" name="hobby" value="程式設計">程式設計
</td>
</tr>
<tr>
<td>簡介</td>
<td><textarea name="info" rows="3" cols="20"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="新增"></td>
</tr>
</table>
</form>
</body>
</html>
AddServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
String sname = request.getParameter("sname");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
/*String birthday = request.getParameter("birthday");*/
/*String hobby = request.getParameter("hobby");*/
String info = request.getParameter("info");
String[] h = request.getParameterValues("hobby");
String s = Arrays.toString(h);
String hobby = s.substring(1, s.length()-1);
/* Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);*/
//新增到資料庫
Student student = new Student(sname, gender, phone,hobby, info);
StudentService service = new StudentServiceImpl();
service.insert(student);
request.getRequestDispatcher("StudentListServlet").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
4.編輯更新更改資料頁面edit.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>更新學生頁面</title>
</head>
<body>
<form action="UpdateServlet" method="post">
<table border="1" width="600">
<input type="hidden" name="sid" value="${stu.sid}" ><!-- 隱藏 -->
<tr>
<td>姓名</td>
<td><input type="text" name="sname" value="${stu.sname}"></td>
</tr>
<tr>
<td>性別</td>
<td>
<input type="radio" name="gender" value="男" checked="checked"
<c:if test="${stu.gender =='男'}">checked</c:if>
>男
<input type="radio" name="gender" value="女"
<c:if test="${stu.gender=='女'}">checked</c:if>
>女
</td>
</tr>
<tr>
<td>電話</td>
<td><input type="text" name="phone" value="${stu.phone}"></td>
</tr>
<!-- <tr>
<td>生日</td>
<td><input type="text" name="birthday"></td>
</tr> -->
<tr>
<td>愛好</td>
<td>
<input type="checkbox" name="hobby" value="籃球"
<c:if test="${fn:contains(stu.hobby,'籃球')}">checked</c:if>
>籃球
<input type="checkbox" name="hobby" value="跑步"
<c:if test="${fn:contains(stu.hobby,'跑步')}">checked</c:if>
>跑步
<input type="checkbox" name="hobby" value="讀書"
<c:if test="${fn:contains(stu.hobby,'讀書')}">checked</c:if>
>讀書
<input type="checkbox" name="hobby" value="程式設計"
<c:if test="${fn:contains(stu.hobby,'程式設計')}">checked</c:if>
>程式設計
</td>
</tr>
<tr>
<td>簡介</td>
<td><textarea name="info" rows="3" cols="20">${stu.info}</textarea></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="更新"></td>
</tr>
</table>
</form>
</body>
</html>
UpdateServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
int sid = Integer.parseInt(request.getParameter("sid"));
String sname = request.getParameter("sname");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
/*String birthday = request.getParameter("birthday");*/
/*String hobby = request.getParameter("hobby");*/
String info = request.getParameter("info");
String[] h = request.getParameterValues("hobby");
String s = Arrays.toString(h);
String hobby = s.substring(1, s.length()-1);
/* Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);*/
//新增到資料庫
Student student = new Student(sid, sname, gender, phone,hobby, info);
StudentService service = new StudentServiceImpl();
service.update(student);
request.getRequestDispatcher("StudentListServlet").forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
5.分頁頁面list_page.jsp
<script type="text/javascript">
function doDelete(sid){
var flag = confirm("是否刪除?");
if(flag){
location.href="DeleteServlet?sid="+sid;
}
}
</script>
<title>學生列表頁面</title>
</head>
<body>
<form action="SearchStudentServlet" method="post">
<table border="1" cellspacing="0">
<tr>
<td colspan="8">
按姓名查詢:<input type="text" name="sname">
按性別查詢:<select name="gender" >
<option value="">--請選擇--
<option value="男">男
<option value="女">女
</select>
<input type="submit" value="查詢">
<a href="add.jsp">新增</a>
</td>
</tr>
<tr>
<td>編號</td>
<td>姓名</td>
<td>性別</td>
<td>電話</td>
<!-- <td>生日</td> -->
<td>愛好</td>
<td>簡介</td>
<td>操作</td>
</tr>
<c:forEach items="${pageBean.list}" var="stu">
<tr>
<td>${stu.sid}</td>
<td>${stu.sname}</td>
<td>${stu.gender}</td>
<td>${stu.phone}</td>
<%-- <td>${stu.birthday}</td> --%>
<td>${stu.hobby}</td>
<td>${stu.info}</td>
<td><a href="EditServlet?sid=${stu.sid}">更新</a> <a href="#" onclick="doDelete(${stu.sid})">刪除</a></td>
</tr>
</c:forEach>
<td colspan="8">
第${pageBean.currentPage }/${pageBean.totalPage }頁
每頁顯示${pageBean.pageSize } 條
總記錄數${pageBean.totalSize } 條
<c:if test="${pageBean.currentPage != 1 }">
<a href="StudentListPageServlet?currentPage=1">首頁</a>
<a href="StudentListPageServlet?currentPage=${pageBean.currentPage-1}">上一頁</a>
</c:if>
<c:if test="${pageBean.currentPage == 1 }">
<a href="StudentListPageServlet?currentPage=1">首頁</a>
上一頁
</c:if>
|
<c:forEach begin="1" end="${pageBean.totalPage }" var="i">
<c:if test="${ pageBean.currentPage == i}">
${i }
</c:if>
<c:if test="${ pageBean.currentPage != i}">
<a href="StudentListPageServlet?currentPage=${ i}">${i }</a>
</c:if>
</c:forEach>
|
<c:if test="${pageBean.currentPage == pageBean.totalPage }">
下一頁
<a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾頁</a>
</c:if>
<c:if test="${pageBean.currentPage != pageBean.totalPage }">
<a href="StudentListPageServlet?currentPage=${pageBean.currentPage+1 }">下一頁</a>
<a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾頁</a>
</c:if>
</td>
</table>
</form>
</body>
</html>
第二步:建立domain層
1.Student類
public class Student {
private int sid;
private String sname;
private String gender;
private String phone;
/*private Date birthday;*/
private String hobby;
private String info;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
/*public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}*/
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", gender="
+ gender + ", phone=" + phone + ", hobby=" + hobby + ", info=" + info
+ "]";
}
public Student(String sname, String gender, String phone, String hobby,
String info) {
super();
this.sname = sname;
this.gender = gender;
this.phone = phone;
this.hobby = hobby;
this.info = info;
}
public Student(int sid, String sname, String gender, String phone,
String hobby, String info) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.phone = phone;
this.hobby = hobby;
this.info = info;
}
public Student() {
super();
}
}
2.建立pageBean
/**
* @author Leonard
*
* 用於封裝分頁的資料
* 裡面包含:1.該頁學生集合資料
* 2.總的記錄數
* 3.總的頁數
* 4.當前頁
* 5.每頁顯示的記錄數
*
*/
public class PageBean<T> {
private int currentPage;//當前頁
private int totalPage;//總頁數
private int pageSize;//每頁記錄數
private int totalSize;//總的記錄數
private List<T> list;//當前頁的學生集合
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
第三步:建立DAO及Dao的實現
1.StudentDao.java
public interface StudentDao {
int PAGE_SIZE = 5;//代表一頁顯示多少資料
/**
* @param 查詢當頁的學生資料
* @return
* @throws SQLException
*/
List<Student> findStudentByPage(int currentPage) throws SQLException;
/**
* 查詢總的學生記錄數
* @return
* @throws SQLException
*/
int findCount() throws SQLException;
List<Student> findAll() throws SQLException;
//根據ID查詢單個學生
Student findStudentById(int sid) throws SQLException;
//根據條件進行模糊查詢
List<Student> SearchStudentList(String sname,String gender) throws SQLException;
void insert(Student student) throws SQLException;
void delete(int sid) throws SQLException;
void update(Student student) throws SQLException;
}
2.StudentDaoImpl.java
public class StudentDaoImpl implements StudentDao {
@Override
public List<Student> findAll() throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
List<Student> list = runner.query("select * from stu",
new BeanListHandler<Student>(Student.class));
return list;
}
@Override
public void insert(Student student) throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
runner.update("insert into stu values(null,?,?,?,?,?)",
student.getSname(),
student.getGender(),
student.getPhone(),
/*student.getBirthday(),*/
student.getHobby(),
student.getInfo()
);
}
@Override
public void delete(int sid) throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
runner.update("delete from stu where sid=?", sid);
}
@Override
public Student findStudentById(int sid) throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
return runner.query("select * from stu where sid=?", new BeanHandler<Student>(Student.class),sid);
}
@Override
public void update(Student student) throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
runner.update("update stu set sname=?,gender=?,phone=?,hobby=?,info=? where sid = ?",
student.getSname(),
student.getGender(),
student.getPhone(),
/*student.getBirthday(),*/
student.getHobby(),
student.getInfo(),
student.getSid()
);
}
@Override
public List<Student> SearchStudentList(String sname, String gender)
throws SQLException {
System.out.println("模糊查詢====="+sname+"=========="+gender);
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
//1=1:代表查詢全部的
String sql="select * from stu where 1=1 ";
List<String> list = new ArrayList<String>();
//判斷是否輸入了姓名查詢,若有資料就拼到sql語句裡
if(!TextUtils.isEmpty(sname)){
sql = sql + " and sname like ?";
list.add("%"+sname+"%");
}
//是否輸入了按性別查詢,如果有,就拼接到sql裡,且把輸入的性別追加到集合裡
if(!TextUtils.isEmpty(gender)){
sql = sql + " and gender = ?";
list.add(gender);
}
List<Student> query = runner.query(sql, new BeanListHandler<Student>(Student.class),
list.toArray()//集合轉為陣列
);
return query;
}
@Override
public List<Student> findStudentByPage(int currentPage) throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
//第一個問號代表返回多少記錄,第二個問號代表前面跳過多少記錄;;;
List<Student> list = runner.query("select * from stu limit ? offset ?",
new BeanListHandler<Student>(Student.class),
PAGE_SIZE,(currentPage-1)*PAGE_SIZE
);
return list;
}
/*
查詢總的記錄數
*/
@Override
public int findCount() throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
// ScalarHandler()用於處理 平均值,總的個數等
Long query = (Long) runner.query("select count(*) from stu",
new ScalarHandler()
);
//轉為int型
return query.intValue();
}
}
第三步:建立service層及service的實現
1.StudentService.java
public interface StudentService {
List<Student> findAll() throws SQLException;
//根據ID查詢單個學生
Student findStudentById(int sid) throws SQLException;
//根據條件進行模糊查詢
List<Student> SearchStudentList(String sname,String gender) throws SQLException;
void insert(Student student) throws SQLException;
void delete(int sid) throws SQLException;
void update(Student student) throws SQLException;
/**
* @param 查詢當頁資料
* @return
* @throws SQLException
*/
PageBean findStudentByPage(int currentPage) throws SQLException;
}
2.StudentServiceImpl.java
public class StudentServiceImpl implements StudentService {
@Override
public List<Student> findAll() throws SQLException {
StudentDao dao = new StudentDaoImpl();
return dao.findAll();
}
@Override
public void insert(Student student) throws SQLException {
StudentDao dao = new StudentDaoImpl();
dao.insert(student);
}
@Override
public void delete(int sid) throws SQLException {
StudentDao dao = new StudentDaoImpl();
dao.delete(sid);
}
@Override
public Student findStudentById(int sid) throws SQLException {
StudentDao dao = new StudentDaoImpl();
return dao.findStudentById(sid);
}
@Override
public void update(Student student) throws SQLException {
StudentDao dao = new StudentDaoImpl();
dao.update(student);
}
@Override
public List<Student> SearchStudentList(String sname, String gender)
throws SQLException {
StudentDao dao = new StudentDaoImpl();
return dao.SearchStudentList(sname, gender);
}
@Override
public PageBean findStudentByPage(int currentPage) throws SQLException {
//封裝分頁的該頁資料
PageBean<Student> pageBean = new PageBean<Student>();
pageBean.setCurrentPage(currentPage);//1.設定當前頁
int pageSize = StudentDaoImpl.PAGE_SIZE;
pageBean.setPageSize(pageSize);//2.設定每頁顯示多少資料
StudentDao dao = new StudentDaoImpl();
List<Student> list = dao.findStudentByPage(currentPage);
pageBean.setList(list);//3.設定該頁的學生資料
int count = dao.findCount();
pageBean.setTotalSize(count);//4.設定總的記錄數
pageBean.setTotalPage(count%pageSize==0? count/pageSize : (count/pageSize)+1);//5.設定總頁數
return pageBean;
}
}
第四步:由Servlet調service層
參考第一步:jsp頁面對應著Servlet
3.分頁設計詳解
1.建立StudentListPageServlet.java
public class StudentListPageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.獲取需要顯示的頁碼數
int currentPage = Integer.parseInt(request.getParameter("currentPage"));
//2.根據指定頁數獲取該頁資料回來;
StudentService service = new StudentServiceImpl();
PageBean pageBean = service.findStudentByPage(currentPage);
request.setAttribute("pageBean", pageBean);
//3.跳轉頁面
request.getRequestDispatcher("list_page.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
2.domain層建立用於封裝分頁的資料pageBean類
/**
* @author Leonard
* 用於封裝分頁的資料
* 裡面包含:1.該頁學生集合資料
* 2.總的記錄數
* 3.總的頁數
* 4.當前頁
* 5.每頁顯示的記錄數
*/
public class PageBean<T> {
private int currentPage;//當前頁
private int totalPage;//總頁數
private int pageSize;//每頁記錄數
private int totalSize;//總的記錄數
private List<T> list;//當前頁的學生集合
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
3.dao層定義一頁顯示多少資料,及查詢當頁學生資料顯示
int PAGE_SIZE = 5;//代表一頁顯示多少資料
List<Student> findStudentByPage(int currentPage) throws SQLException;
/**
* 查詢總的學生記錄數
* @return
* @throws SQLException
*/
int findCount() throws SQLException;
4.dao層的實現:
//第一個問號代表返回多少記錄,第二個問號代表前面跳過多少記錄
List<Student> list = runner.query("select * from stu limit ? offset ?",
new BeanListHandler<Student>(Student.class),
PAGE_SIZE,(currentPage-1)*PAGE_SIZE
);
/*
查詢總的記錄數
*/
@Override
public int findCount() throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
// ScalarHandler()用於處理 平均值,總的個數等
Long query = (Long) runner.query("select count(*) from stu",
new ScalarHandler()
);
//轉為int型
return query.intValue();
}
5.service層:查詢當頁資料:返回domain層的pageBean
/**
* @param 查詢當頁資料
* @return
* @throws SQLException
*/
PageBean findStudentByPage(int currentPage) throws SQLException;
6.實現service層
public PageBean findStudentByPage(int currentPage) throws SQLException {
//封裝分頁的該頁資料
PageBean<Student> pageBean = new PageBean<Student>();
pageBean.setCurrentPage(currentPage);//1.設定當前頁
int pageSize = StudentDaoImpl.PAGE_SIZE;
pageBean.setPageSize(pageSize);//2.設定每頁顯示多少資料
StudentDao dao = new StudentDaoImpl();
List<Student> list = dao.findStudentByPage(currentPage);
pageBean.setList(list);//3.設定該頁的學生資料
int count = dao.findCount();
pageBean.setTotalSize(count);//4.設定總的記錄數
pageBean.setTotalPage(count%pageSize==0? count/pageSize : (count/pageSize)+1);//5.設定總頁數
return pageBean;
}
7.建立第一步StudentListPageServlet.java裡跳轉的list_page.jsp頁面【分頁顯示頁面】
<body>
<form action="SearchStudentServlet" method="post">
<table border="1" cellspacing="0">
<tr>
<td colspan="8">
按姓名查詢:<input type="text" name="sname">
按性別查詢:<select name="gender" >
<option value="">--請選擇--
<option value="男">男
<option value="女">女
</select>
<input type="submit" value="查詢">
<a href="add.jsp">新增</a>
</td>
</tr>
<tr>
<td>編號</td>
<td>姓名</td>
<td>性別</td>
<td>電話</td>
<!-- <td>生日</td> -->
<td>愛好</td>
<td>簡介</td>
<td>操作</td>
</tr>
<c:forEach items="${pageBean.list}" var="stu">
<tr>
<td>${stu.sid}</td>
<td>${stu.sname}</td>
<td>${stu.gender}</td>
<td>${stu.phone}</td>
<%-- <td>${stu.birthday}</td> --%>
<td>${stu.hobby}</td>
<td>${stu.info}</td>
<td><a href="EditServlet?sid=${stu.sid}">更新</a> <a href="#" onclick="doDelete(${stu.sid})">刪除</a></td>
</tr>
</c:forEach>
<td colspan="8">
第${pageBean.currentPage }/${pageBean.totalPage }頁
每頁顯示${pageBean.pageSize } 條
總記錄數${pageBean.totalSize } 條
<c:if test="${pageBean.currentPage != 1 }">
<a href="StudentListPageServlet?currentPage=1">首頁</a>
<a href="StudentListPageServlet?currentPage=${pageBean.currentPage-1}">上一頁</a>
</c:if>
<c:if test="${pageBean.currentPage == 1 }">
<a href="StudentListPageServlet?currentPage=1">首頁</a>
上一頁
</c:if>
|
<c:forEach begin="1" end="${pageBean.totalPage }" var="i">
<c:if test="${ pageBean.currentPage == i}">
${i }
</c:if>
<c:if test="${ pageBean.currentPage != i}">
<a href="StudentListPageServlet?currentPage=${ i}">${i }</a>
</c:if>
</c:forEach>
|
<c:if test="${pageBean.currentPage == pageBean.totalPage }">
下一頁
<a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾頁</a>
</c:if>
<c:if test="${pageBean.currentPage != pageBean.totalPage }">
<a href="StudentListPageServlet?currentPage=${pageBean.currentPage+1 }">下一頁</a>
<a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾頁</a>
</c:if>
</td>
</table>
</form>
</body>
========================================
============================================================~~***
刪除線============:這裡為前期分析步驟=====
***~~
第二步:1.建立Servlet【控制層】以及Dao層實現,StudentListServlet.java
/**
* @author Leonard
* 控制層:【C】
* 負責查詢所有學生的資訊,然後呈現到jsp頁面上
*
*/
public class StudentListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
2.建立Dao【資料訪問層】,StudentDao.java
【注:提前建立一個Domain,即Student類
private int id;
private String name;
private String gender;
private String phone;
private Date birthday;
private String hobby;
private String info;
生成set,get方法,預設空參構造
】
/**
* @author Leonard
* 資料訪問層【M】
* 針對學生表的資料庫操作
*/
public interface StudentDao {
/**
* 查詢所有學生,List裡面放Student
* @return
*/
List<Student> findAll();
}
3.實現2中的Dao;
/**
* @author Leonard
* StudentDao的實現,查詢所有學生
*/
public class StudentDaoImpl implements StudentDao {
@Override
public List<Student> findAll() throws Exception {
QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
List<Student> list = runner.query("select * from stu", new BeanListHandler<Student>(Student.class));
return list;
}
}
第三步:Service層
好處:因為Dao層只針對單一的邏輯,資料操作層面;Service層是業務層面,一個業務包含多個單一的邏輯;
例如:分頁
知道一頁學生的集合-----Dao
1.建立業務邏輯層
StudentService.java
/**
* @author Leonard
* 學生業務處理規則
*/
public interface StudentService {
List<Student> findAll() throws Exception;
}
2.實現:StudentServiceImpl.java
/**
* @author Leonard
* 學生的業務實現
*/
public class StudentServiceImpl implements StudentService {
/*
* Service裡調Dao
*/
@Override
public List<Student> findAll() throws Exception {
StudentDao dao = new StudentDaoImpl();
//返回查詢的所有
return dao.findAll();
}
}
第四步:對第二步中的Servlet的程式碼,即StudentListServlet.java,進行完善
/**
* @author Leonard
* 控制層:【C】
* 負責查詢所有學生的資訊,然後呈現到jsp頁面上
*
*/
public class StudentListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1.查詢所有的學生
StudentService service = new StudentServiceImpl();
List<Student> list = service.findAll();
//2.把Service層查到的資料儲存到作用域中
request.setAttribute("list", list);
//3.跳轉頁面
request.getRequestDispatcher("list.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
第五步:第四步中的跳轉頁面list.jsp
<body>
<table border="1" cellspacing="0" align="center">
<tr align="center">
<td>編號</td>
<td>姓名</td>
<td>性別</td>
<td>電話</td>
<td>生日</td>
<td>愛好</td>
<td>簡介</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.gender}</td>
<td>${stu.phone}</td>
<td>${stu.birthday}</td>
<td>${stu.hobby}</td>
<td>${stu.info}</td>
<td><a href="#">更新</a> <a href="#">刪除</a></td>
</tr>
</c:forEach>
</table>
</body>
以上便實現了學生列表的查詢操作
實現增加學生資訊操作
第六步:在list.jsp新增新增按鈕,實現向增加學生資訊add.jsp頁面跳轉
<tr>
<td colspan='8'><a href="add.jsp">新增</a></td>
</tr>
add.jsp頁面
<body>
<form action="addServlet" method="post">
<table border="1" cellspacing="0">
<tr>
<td>姓名</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>性別</td>
<td>
<input type="radio" name="gender" value="男" checked="checked">男
<input type="radio" name="gender" value="女">女
</td>
</tr>
<tr>
<td>電話</td>
<td><input type="text" name="phone"/></td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birthday"/></td>
</tr>
<tr>
<td>愛好</td>
<td>
<input type="checkbox" name="hobby" value="游泳">游泳
<input type="checkbox" name="hobby" value="看書">看書
<input type="checkbox" name="hobby" value="寫字">寫字
<input type="checkbox" name="hobby" value="籃球">籃球
</td>
</tr>
<tr>
<td>簡介</td>
<td><textarea rows="3" cols="20" name="info"></textarea></td>
</tr>
<tr>
<td colspan="2"><button>新增</button></td>
</tr>
</table>
</form>
</body>
第七步:新增學生的實現
建立Servlet,處理新增學生請求addServlet.java
/**
* @author Leonard
* 用於處理學生的新增請求
*/
public class addServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.處理中文問題
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;utf-8");
//2.獲取前臺add.jsp提交的資料
String name = request.getParameter("name");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
String birthday = request.getParameter("birthday");
String hobby = request.getParameter("hobby");
String info = request.getParameter("info");
//3.獲取的資料新增到資料庫
//4.跳轉到列表頁
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
第八步:Dao層與Dao層的實現
StudentDao.java
/**
* 新增學生
* @param student 需要新增到資料庫
* @throws Exception
*/
void insert(Student student) throws Exception;
StudentDaoImpl.java
@Override
public void insert(Student student) throws Exception {
QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
runner.update("insert into stu values(null,?,?,?,?,?,?)",
student.getName(),
student.getGender(),
student.getPhone(),
student.getBirthday(),
student.getHobby(),
student.getInfo());
}
第九步:Service層與Service層的實現
Service層介面StudentService.java
void insert(Student student) throws Exception;//增加
Service層的實現StudentServiceImpl.java
@Override
public void insert(Student student) throws Exception {
StudentDao dao = new StudentDaoImpl();
dao.insert(student);//直接呼叫Dao的insert方法
}
第十步:Student類需要有參構造
/**
* @author Leonard
* 封裝的學生物件Bean
*/
public class Student {
private int id;
private String name;
private String gender;
private String phone;
private Date birthday;
private String hobby;
private String info;
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
//不需要id
public Student(String name, String gender, String phone, Date birthday,
String hobby, String info) {
super();
this.name = name;
this.gender = gender;
this.phone = phone;
this.birthday = birthday;
this.hobby = hobby;
this.info = info;
}
public Student() {
super();
}
}
第十一步:完善第七步的addServlet.java
在這裡插入程式碼片