Javaweb 第15天 web练习和分页技术
第15天 web練習和分頁技術
復習day14內容:
?
學習新技術的思路?
?
?
?
分析功能的思路?
?
?
?
使用queryRunner操作數據庫的步驟?
?
?
ResultSetHandler接口常用實現類(三個重點)?
?
?
?
?
?
今日任務
?
案例—添加聯系人
畫圖分析
?
添加聯系人功能:
?
回顧聯系人管理系統需求:
1)使用添加聯系人功能,必須要用戶登錄(session中必須要有loginUser),如果,沒有登陸,讓用戶返回登陸頁面。
2)不同用戶,可以有同樣的聯系人,同一個用戶,聯系人不能重復
3)聯系人不重復的情況下,數據庫添加一條聯系人的記錄
?
?
畫圖分析:
?
?
?
代碼實現
Jsp:
?
Servlet代碼:
?
package cn.itcast.web;
?
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
import org.apache.commons.beanutils.BeanUtils;
?
import cn.itcast.domain.Contact;
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class AddContactServlet extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????request.setCharacterEncoding("utf-8");
????????//第一步:校驗登錄
????????User loginUser = (User)request.getSession().getAttribute("loginUser");
????????if(loginUser == null){
????????????
????????????response.sendRedirect(request.getContextPath()+"/login.jsp");
????????????return;
????????}
????????//第二步:封裝數據
????????Contact con = new Contact();
????????try {
????????????BeanUtils.populate(con, request.getParameterMap());
????????} catch (Exception e) {
????????????//抓取異常的時候,根據需求去抓,不同的異常,不同處理
????????????e.printStackTrace();
????????}
????????//單獨封裝了u_id數據,這個數據是,表示當前聯系人是哪個用戶的
????????con.setU_id(loginUser.getId());
????????//第三步:調用service,添加聯系人
????????ContactService contactService = new ContactServiceImpl();
????????int info = contactService.addContact(con);
????????//第四步:根據返回值,處理
????????if(info == 1){
????????????//添加成功,請求一個Servlet,獲取所有當前用戶的聯系人數據
????????????//response.sendRedirect(request.getContextPath()+"/welcome.jsp");
????????????response.sendRedirect(request.getContextPath()+"/findAllContact");
????????????return;
????????}else if(info == -1){
????????????//聯系人重復
????????????request.setAttribute("msg", "聯系人重復");
????????????request.getRequestDispatcher("/addContect.jsp").forward(request, response);
????????????return;
????????}else{
????????????//服務器忙,請稍候再
????????????request.setAttribute("msg", "服務器忙,請稍候再試");
????????????request.getRequestDispatcher("/addContect.jsp").forward(request, response);
????????????return;
????????}
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????doGet(request, response);
????}
?
}
?
?
?
Service代碼:
接口:
?
/**
???? * 添加聯系人方法
???? * @param con
???? * @return
???? */
????int addContact(Contact con);
?
實現類:
private ContactDao contactDao = new ContactDaoImpl();
????
????@Override
????public int addContact(Contact con) {
????????//查詢數據庫,聯系人是否重復
????????int info = contactDao.findContactByNameAndUid(con.getName(),con.getU_id());
????????if(info == 1){
????????????//不重復,可以添加
????????????contactDao.addContact(con);
????????????return 1;
????????}else{
????????????return -1;
????????}
????}
?
?
?
Dao代碼:
接口:
/**
???? * 根據用戶id和聯系人名稱查詢數據的方法
???? * @param name
???? * @param u_id
???? * @return
???? */
????int findContactByNameAndUid(String name, int u_id);
?
????/**
???? * 添加聯系人的方法
???? * @param con
???? */
????void addContact(Contact con);
實現類:
private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
????@Override
????public int findContactByNameAndUid(String name, int u_id) {
????????String sql = "select * from contact where name = ? and u_id = ?";
????????try {
????????????Contact contact = qr.query(sql, new BeanHandler<Contact>(Contact.class), name,u_id);
????????????if(contact == null){
????????????????return 1;
????????????}else{
????????????????return -1;
????????????}
????????} catch (SQLException e) {
????????????//e.printStackTrace();打印堆棧信息,包括了錯誤信息。后期需要寫入日志,數據一定要保留起來
????????????e.printStackTrace();
????????????throw new RuntimeException("查詢聯系人異常");
????????}
????????
????}
?
????@Override
????public void addContact(Contact con) {
????????String sql = "insert into contact values(null,?,?,?,?,?)";
????????try {
????????????qr.update(sql,con.getU_id() ,con.getName(),con.getSex(),con.getAddress(),con.getTel());
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("添加聯系人異常");
????????}
?
????}
?
?
案例—查詢當前用戶的全部聯系人實現
查詢全部聯系人(當前登錄用戶的全部聯系人)
?
查詢全部聯系人功能什么時候被調用?
?
獲取到所有聯系人數據之后將數據轉發到welcome.jsp,顯示所有聯系人的數據。
?
添加聯系人完成之后,要看到添加的數據。
需要重新獲取全部聯系人數據,轉發welcome.jsp頁顯示
?
修改聯系人完成之后,看到修改后的數據。
?
同上
畫圖分析
代碼實現
?
loginServlet:
?
?
findAllContactServlet:
?
package cn.itcast.web;
?
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;
?
import cn.itcast.domain.Contact;
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class FindAllContactServlet extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????//校驗登錄
????????User loginUser = (User)request.getSession().getAttribute("loginUser");
????????if(loginUser == null){
????????????response.sendRedirect(request.getContextPath()+"/login.jsp");
????????????return;
????????}
????????//獲取數據(u_id)
????????int u_id = loginUser.getId();
????????//調用service方法
????????ContactService contactService = new ContactServiceImpl();
????????List<Contact> data = contactService.findAll(u_id);
????????
????????//將數據存入request,轉發到welcome.jsp頁面
????????request.setAttribute("data", data);
????????request.getRequestDispatcher("/welcome.jsp").forward(request, response);
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????doGet(request, response);
????}
?
}
?
?
Service:
?
接口:
/**
???? * 查詢指定用戶的所有聯系人
???? * @param u_id
???? * @return
???? */
????List<Contact> findAll(int u_id);
實現類:
public List<Contact> findAll(int u_id) {
????????return contactDao.findAll(u_id);
????}
Dao:
接口:
/**
???? * 獲取指定用戶聯系人的方法
???? * @param u_id
???? * @return
???? */
????List<Contact> findAll(int u_id);
?
實現類:
?
public List<Contact> findAll(int u_id) {
????????String sql = "select * from contact where u_id = ?";
????????try {
????????????return qr.query(sql, new BeanListHandler<Contact>(Contact.class), u_id);
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("獲取指定的用戶所有聯系人失敗");
????????}
????}
添加聯系人servlet修改:
?
?
?
?
案例--修改聯系人分析(分兩次請求)
效果是什么?
?
?
?
?
?
畫圖分析
修改聯系人流程一:
?
修改聯系人流程二:
?
代碼實現
修改welcome.jsp頁面:
?
?
顯示了當前聯系人數據的id:
?
?
修改updateContact.jsp頁面:
?
FindContactByIdServlet:
?
package cn.itcast.web;
?
import java.io.IOException;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
import cn.itcast.domain.Contact;
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class FindByIDServlet extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????//校驗登錄
????????User loginUser = (User)request.getSession().getAttribute("loginUser");
????????if(loginUser == null){
????????????response.sendRedirect(request.getContextPath()+"/login.jsp");
????????????return;
????????}
????????//獲取參數聯系人id
????????String parameter = request.getParameter("id");
????????int id = Integer.parseInt(parameter);
????????//調用service方法獲取數據
????????ContactService contactService = new ContactServiceImpl();
????????Contact con = contactService.findById(id);
????????//將數據轉發到updateContact.jsp頁面
????????request.setAttribute("con", con);
????????request.getRequestDispatcher("/updateContact.jsp").forward(request, response);
????????
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????doGet(request, response);
????}
?
}
?
?
Service:
接口:
/**
???? * 根據id查詢數據
???? * @param id
???? * @return
???? */
????Contact findById(int id);
?
實現類:
public Contact findById(int id) {
????????return contactDao.findById(id);
????}
?
Dao:
接口:
?
/**
???? * 根據id查詢數據
???? * @param id
???? * @return
???? */
????Contact findById(int id);
實現類:
public Contact findById(int id) {
????????String sql = "select * from contact where id = ?";
????????try {
????????????return qr.query(sql, new BeanHandler<Contact>(Contact.class), id);
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("獲取指定的聯系人數據失敗");
????????}
????}
?
修改操作UpdateContactServlet:
?
package cn.itcast.web;
?
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
import org.apache.commons.beanutils.BeanUtils;
?
import cn.itcast.domain.Contact;
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class UpdateContactServlet extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????request.setCharacterEncoding("utf-8");
????????//校驗登錄
????????User loginUser = (User)request.getSession().getAttribute("loginUser");
????????if(loginUser == null){
????????????
????????????response.sendRedirect(request.getContextPath()+"/login.jsp");
????????????return;
????????}
????????//封裝數據
????????Contact con = new Contact();
????????try {
????????????BeanUtils.populate(con, request.getParameterMap());
????????} catch (Exception e) {
????????????e.printStackTrace();
????????}
????????//調用service
????????ContactService contactService = new ContactServiceImpl();
????????contactService.updateContact(con);
????????//調用findAllContact查看效果
????????response.sendRedirect(request.getContextPath()+"/findAllContact");
????????
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????doGet(request, response);
????}
?
}
?
?
?
Service:
接口:
?
/**
???? * 修改聯系人
???? * @param con
???? */
????void updateContact(Contact con);
?
實現類:
public void updateContact(Contact con) {
????????contactDao.updateContact(con);
????}
?
Dao:
接口:
/**
???? * 修噶聯系人
???? * @param con
???? */
????void updateContact(Contact con);
實現類:
public void updateContact(Contact con) {
????????String sql = "update contact set name = ? , sex = ? , tel = ? , address = ? where id = ?";
????????try {
????????????qr.update(sql, con.getName(),con.getSex(),con.getTel(),con.getAddress(),con.getId());
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("修改指定的聯系人數據失敗");
????????}
????}
?
?
?
案例--刪除聯系人實現
注意:一般來說,公司在做刪除功能時候,不是真實的物理刪除(執行delete語句),只會設置標記,標記這條數據失效。
?
為什么不刪除數據?
數據是公司最寶貴的財富,根據數據可以做大數據分析
例子:根據訂單的下單時間,下單金額,訂單的地址,訂單商品的信息——這個人什么時候發工資,薪資水平,去哪里偷東西,偷哪些貴重物品
?
智能推薦:確定推薦的時間,你需要的品牌,你附近的商家
?
傳智播客:名字,上海地址,老家地址,專業,學歷,年齡,來源,有無工作經驗,是否在校
?
老家地址:下一個分校應該在哪里
專業:分析出,當前培訓的市場擴張程度
學歷:給就業部老師,指定相應的就業方案
年齡:招生的部門,主要的招生的年齡段
來源:老學員介紹,廣告,優酷視頻看到的,通過百度查詢——下一個推廣的主要方向
是否在校:第一,是否要開辟高校市場。第二,就業指導老師,準備相應的就業方案
?
?
功能的效果:
?
畫圖分析
?
?
注意:相關money的功能(加 減 乘 除 ,顯示),相關用戶的功能,一定要把用戶當作小白,把用戶的體驗,能做多好就做多好
?
代碼實現
Welcome.jsp修改:
?
Servlet代碼:
?
package cn.itcast.web;
?
import java.io.IOException;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class DeleteServlet extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????//校驗登錄
????????User loginUser = (User)request.getSession().getAttribute("loginUser");
????????if(loginUser == null){
????????????
????????????response.sendRedirect(request.getContextPath()+"/login.jsp");
????????????return;
????????}
????????//獲取數據 id
????????int id = Integer.parseInt(request.getParameter("id"));
????????//調用service方法刪除數據
????????ContactService contactService = new ContactServiceImpl();
????????contactService.delete(id);
????????
????????//調用findAllContact查看刪除效果
????????response.sendRedirect(request.getContextPath()+"/findAllContact");
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????doGet(request, response);
????}
?
}
?
?
?
Service代碼:
接口:
/**
???? * 刪除操作
???? * @param id
???? */
????void delete(int id);
實現類:
?
public void delete(int id) {
????????contactDao.delete(id);
????}
Dao代碼:
?
接口:
/**刪除操作
???? * @param id
???? */
????void delete(int id);
實現類:
?
public void delete(int id) {
????????String sql = "delete from contact where id = ?";
????????try {
????????????qr.update(sql, id);
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("刪除指定的聯系人數據失敗");
????????}
????????
????}
案例--根據條件查詢聯系人實現
頁面分析:
?
?
條件查詢sql語句實現:
?
select * from contact where key like '%用戶輸入的查詢內容(value)%';
?
要查詢的數據庫字段:是頁面下拉框選擇的內容(key)
用戶輸入的查詢條件:是input輸入框中用戶輸入的內容(value)
畫圖分析
?
?
代碼實現
?
Servlet:
?
package cn.itcast.web;
?
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;
?
import cn.itcast.domain.Contact;
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class FindByKeyServlet extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????request.setCharacterEncoding("utf-8");
????????//校驗登錄
????????User loginUser = (User)request.getSession().getAttribute("loginUser");
????????if(loginUser == null){
????????????response.sendRedirect(request.getContextPath()+"/login.jsp");
????????????return;
????????}
????????//獲取數據(key :查詢字段name tel address || value :用戶輸入的模糊查詢的條件 || u_id 當前用戶)
????????String key = request.getParameter("key");
????????String value = request.getParameter("value");
????????int u_id = loginUser.getId();
????????//調用service方法獲取數據
????????ContactService contactService = new ContactServiceImpl();
????????List<Contact> data = contactService.findByKey(key ,value, u_id);
????????//將數據轉發到welcome.jsp頁面
????????request.setAttribute("data", data);
????????request.getRequestDispatcher("/welcome.jsp").forward(request, response);
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????doGet(request, response);
????}
?
}
?
?
?
Service:
?
接口:
/**
???? * 條件查詢方法
???? * @param key :查詢字段
???? * @param value :用戶輸入的查詢內容
???? * @param u_id :當前用戶id
???? * @return
???? */
????List<Contact> findByKey(String key, String value, int u_id);
?
實現類:
?
public List<Contact> findByKey(String key, String value, int u_id) {
????????
????????return contactDao.findByKey(key,value,u_id);
????}
Dao:
接口:
?
/**
???? * 條件查詢的方法
???? * @param key
???? * @param value
???? * @param u_id
???? * @return
???? */
????List<Contact> findByKey(String key, String value, int u_id);
?
實現類:
public List<Contact> findByKey(String key, String value, int u_id) {
????????String sql = "select * from contact where "+ key +" like ? and u_id = ?";
????????try {
????????????return qr.query(sql, new BeanListHandler<Contact>(Contact.class), "%"+value+"%",u_id);
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("條件查詢聯系人數據失敗");
????????}
????}
案例--大結果集分頁實現
分頁介紹
大結果集: 一次性,從,數據庫中,獲取,大量(上萬的數量)的,數據。
分頁: 將數據分批次展示給用戶
?
?
大結果集分頁的技術需求(它因為什么原因誕生的):
?
1)物理計算機的瓶頸(內存瓶頸),如果給一個只有1千萬數據內存的機器,給了2千萬數據。數據溢出。
?
一個水桶,只能裝1L水,現在我給他灌2L的水,肯定有1L的水溢出,浪費了。
2)封裝數據到對象,過程十分慢長(這個漫長是數據量太大),這樣的用戶體驗非常差
假設:有一個超級機器,內存無限的,1個數據要1秒鐘,1千萬數據,一千萬秒。
?
?
補充:用戶等待一個功能響應,一般只會等多久?
跟據不同的信息內容,不同。
查看商品,用戶不喜歡等待,而且有代替方案,一般5到15秒。
支付,等30秒左右
搶票,不要動我的手機,我正在搶票,等待時間3分鐘。
?
?
?
分頁技術的實現:數據庫實現,內存實現(redis數據庫)
?
?
數據庫實現:通過關鍵字,限制一次性從數據庫中獲取數據的起始位置和長度。
?
起始位置:數據從哪一行開始獲取。
長度:一次性獲取數據的量。
?
MySql關鍵字:limit
?
Select * from contact where key =? limit ?,?
?
第一個問號:起始位置
第二個問號:長度
?
?
代碼測試:
//測試數據庫分頁
//測試數據庫分頁
????@Test
????public void test1(){
????????
????????QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
????????//第一個?:起始位置第二個?:長度
????????String sql = "select * from contact limit ?,?";
????????try {
????????????List<Contact> list = qr.query(sql, new BeanListHandler<Contact>(Contact.class), 10,10);
????????????System.out.println(list);
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????}
????}
效果截圖:
?
?
?
內存分頁實現:
?
先將數據從數據庫中獲取出來,將數據存入緩存(list集合)中,將數據分批次展示給用戶。
?
緩存:內存中開辟的空間,專門用來存儲數據的
?
代碼測試:
?
//測試內存分頁
????????@Test
????????public void test2(){
????????????
????????????QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
????????????//第一個?:起始位置第二個?:長度
????????????String sql = "select * from contact";
????????????try {
????????????????List<Contact> list = qr.query(sql, new BeanListHandler<Contact>(Contact.class));
????????????????//將list集合中的數據分批次展示給用戶
????????????????List<Contact> subList = list.subList(3, 6);
????????????????System.out.println(subList);
????????????} catch (SQLException e) {
????????????????e.printStackTrace();
????????????}
????????}
?
代碼執行效果:
?
頁面修改(功能展示)
?
頁面修改結果:
?
?
分析——使用數據庫分頁技術實現分頁效果,需要那些數據?
?
?
Page類(封裝分頁數據的對象)書寫
?
將復雜的數據,我們封裝一個對象中,這個對象,我們取名字叫Page
符合面向對象思想,封裝。
?
?
畫圖分析
?
?
代碼實現
?
?
Servlet:
package cn.itcast.web;
?
import java.io.IOException;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
import cn.itcast.domain.Page;
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class QueryPageServlet extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????//校驗登錄
????????User loginUser = (User)request.getSession().getAttribute("loginUser");
????????if(loginUser == null){
????????????response.sendRedirect(request.getContextPath()+"/login.jsp");
????????????return;
????????}
????????//獲取數據
????????int pageNum = Integer.parseInt(request.getParameter("pageNum"));
????????int u_id = loginUser.getId();
????????//調用service方法獲取數據
????????ContactService contactService = new ContactServiceImpl();
????????Page page = contactService.queryPage(u_id,pageNum);
????????//將數據轉發到welcome.jsp頁面
????????request.setAttribute("page", page);
????????request.getRequestDispatcher("/welcome.jsp").forward(request, response);
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????doGet(request, response);
????}
?
}
?
?
Service:
接口:
/**
???? * 分頁查詢的方法
???? * @param u_id
???? * @param pageNum
???? * @return
???? */
????Page queryPage(int u_id, int pageNum);
實現類:
?
public Page queryPage(int u_id, int pageNum) {
????????//獲取總記錄數據
????????int total = contactDao.count(u_id);
????????
????????//定義長度
????????int size = 10;
????????//計算尾頁
????????//total size end %
????????//100 10 10 0
????????//101 10 11 1
????????int end = total % size == 0 ? (total / size) :(total / size)+1;
????????//計算起始位置
????????int startIndex = (pageNum - 1) * size;
????????//獲取聯系人數據
????????List<Contact> data = contactDao.queryPage(u_id ,startIndex,size);
????????//封裝數據到page對象
????????Page page = new Page();
????????page.setData(data);
????????page.setEnd(end);
????????page.setPageNum(pageNum);
????????page.setSize(size);
????????page.setTotal(total);
????????//返回page
????????return page;
????}
Dao:
接口:
?
/**
???? * 獲取總記錄數
???? * @param u_id
???? * @return
???? */
????int count(int u_id);
?
????/**
???? * 獲取聯系人數據
???? * @param u_id
???? * @param startIndex
???? * @param size
???? * @return
???? */
????List<Contact> queryPage(int u_id, int startIndex, int size);
?
實現類:
?
public int count(int u_id) {
????????String sql = "select count(*) from contact where u_id = ? ";
????????//ScalarHandler:封裝count avg max min 。。。。函數執行結果
????????try {
????????????//Long:一般數據的總數,使用int 類型存不下的
????????????Long long1 = qr.query(sql, new ScalarHandler<Long>(), u_id);
????????????return long1.intValue();
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("分頁總數獲取失敗");
????????}
????}
?
????@Override
????public List<Contact> queryPage(int u_id, int startIndex, int size) {
????????String sql = "select * from contact where u_id = ? limit ?,?";
????????try {
????????????return qr.query(sql, new BeanListHandler<Contact>(Contact.class), u_id,startIndex,size);
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("分頁聯系人數據獲取失敗");
????????}
????}
loginServlet:
?
?
Welcome.jsp修改:
?
案例—分頁與條件查詢組合實現(了解:內容)
畫圖分析
需求:將條件查詢的結果,進行分頁顯示
?
頁面修改
1)要分頁請求中,必須包含條件請求參數
2)條件查詢的請求中,必須包含分頁請求的參數
組合查詢servlet
package cn.itcast.web;
?
import java.io.IOException;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
import cn.itcast.domain.Page;
import cn.itcast.domain.User;
import cn.itcast.service.ContactService;
import cn.itcast.service.impl.ContactServiceImpl;
?
public class QueryPageServlet2 extends HttpServlet {
?
????public void doGet(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
?
????????// 校驗登陸
????????User loginUser = (User) request.getSession().getAttribute("loginUser");
????????if (loginUser == null) {
????????????response.sendRedirect(request.getContextPath() + "/login.jsp");
????????????return;
????????}
????????// 獲取數據
????????String key = request.getParameter("key");
????????String value = request.getParameter("value");
????????// 處理中文亂碼
????????if(value == null){
????????????value = "";
????????}
????????value = new String(value.getBytes("iso-8859-1"), "utf-8");
????????int pageNum = Integer.parseInt(request.getParameter("pageNum"));
????????int u_id = loginUser.getId();
????????// 調用service方法
????????ContactService contactService = new ContactServiceImpl();
????????Page page = contactService.queryPage2(key, value, pageNum, u_id);
????????// 展示數據
????????// 除了要將分頁(page)數據保存到request對象
????????// 注意:要將查詢key和value都要保存到request對象
????????request.setAttribute("page", page);
????????request.setAttribute("key", key);
????????request.setAttribute("value", value);
????????request.getRequestDispatcher("/welcome.jsp").forward(request, response);
?
????}
?
????public void doPost(HttpServletRequest request, HttpServletResponse response)
????????????throws ServletException, IOException {
????????// 處理中文亂碼
????????request.setCharacterEncoding("utf-8");
????????// 校驗登陸
????????User loginUser = (User) request.getSession().getAttribute("loginUser");
????????if (loginUser == null) {
????????????response.sendRedirect(request.getContextPath() + "/login.jsp");
????????????return;
????????}
????????// 獲取數據
????????String key = request.getParameter("key");
????????String value = request.getParameter("value");
????????int pageNum = Integer.parseInt(request.getParameter("pageNum"));
????????int u_id = loginUser.getId();
????????// 調用service方法
????????ContactService contactService = new ContactServiceImpl();
????????Page page = contactService.queryPage2(key, value, pageNum, u_id);
????????// 展示數據
????????// 除了要將分頁(page)數據保存到request對象
????????// 注意:要將查詢key和value都要保存到request對象
????????request.setAttribute("page", page);
????????request.setAttribute("key", key);
????????request.setAttribute("value", value);
????????request.getRequestDispatcher("/welcome.jsp").forward(request, response);
????}
?
}
?
?
組合查詢service
接口:
/**
???? * 條件查詢和分頁方法
???? * @param key
???? * @param value
???? * @param pageNum
???? * @param u_id
???? * @return
???? */
????Page queryPage2(String key, String value, int pageNum, int u_id);
實現類:
????public Page queryPage2(String key, String value, int pageNum, int u_id) {
????????// 獲取總記錄數
????????int total = contactDao.count2(u_id,key,value);
????????// 定義長度
????????int size = 3;
????????// 根據總記錄數和長度,計算尾頁
????????// 不能直接做除法:
????????// 如果有101條數據,應該有11頁,但是除法運算,結果:10頁
????????int end = total % size == 0 ? (total / size) : (total / size) + 1;
????????// 計算數據庫查詢的起始位置
????????// 第一頁:pageNum=1 ,1-1=0 0*size = 0
????????// 第二頁:pageNum=2 ,2-1=1 1*size = 10
????????// 第三頁:pageNum=3 ,3-1=2 2*size = 20
????????int startIndex = (pageNum - 1) * size;
????????// 獲取聯系人數據
????????List<Contact> data = contactDao.queryPage2(u_id,key,value, startIndex, size);
????????// 創建對象封裝數據(page)
????????Page p = new Page();
????????p.setData(data);
????????p.setEnd(end);
????????p.setPageNum(pageNum);
????????p.setSize(size);
????????p.setTotal(total);
????????// 返回page
????????return p;
????}
組合查詢dao
接口:
?
/**
???? * 條件查詢和分頁——獲取總記錄數據
???? * @param u_id
???? * @param key
???? * @param value
???? * @return
???? */
????int count2(int u_id, String key, String value);
?
????/**
???? * 條件查詢和分頁——獲取聯系人數據
???? * @param u_id
???? * @param key
???? * @param value
???? * @param startIndex
???? * @param size
???? * @return
???? */
????List<Contact> queryPage2(int u_id, String key, String value,
????????????int startIndex, int size);
?
實現類:
?
@Override
????public int count2(int u_id, String key, String value) {
????????QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
????????String sql = "select count(*) from contact where u_id = ?";
????????//思考:用戶登錄之后,默認查詢當前用戶全部聯系人,key value 沒有數據
????????//所以,我們需要根據key和value的值,判斷,應該生成什么樣的sql語句
????????//定義一個集合用來存儲數據,這個集合中的數據,會根據判斷,變化
????????List<Object> list = new ArrayList<Object>();
????????list.add(u_id);
????????if(key !=null && !key.equals("")){
????????????//表示當前key是有數據
????????????//應該拼接上key和value值
????????????//思考:因為有判斷存在,sql語句的參數,有時候是一個問號,有時是兩個問號
????????????sql = sql + " and "+key+" like ?";
????????????list.add("%"+value+"%");
????????}
????????
????????try {
????????????Long long1 = qr.query(sql, new ScalarHandler<Long>(),list.toArray());
????????????return long1.intValue();
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("獲取聯系人總數失敗");
????????}
????}
?
????@Override
????public List<Contact> queryPage2(int u_id, String key, String value,
????????????int startIndex, int size) {
????????QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
????????String sql = "select * from contact where u_id = ?";
????????//在用戶登錄之后,默認查詢所有數據,key和value是沒有值得,sql語句需要根據key和value進行變化
????????List<Object> list = new ArrayList<Object>();
????????list.add(u_id);
????????if(key !=null && !key.equals("")){
????????????sql = sql + " and "+key+" like ?";
????????????list.add("%"+value+"%");
????????}
????????sql = sql + " limit ?,?";
????????list.add(startIndex);
????????list.add(size);
????????try {
????????????return qr.query(sql, new BeanListHandler<Contact>(Contact.class), list.toArray());
????????} catch (SQLException e) {
????????????e.printStackTrace();
????????????throw new RuntimeException("獲取聯系人分頁數據失敗");
????????}
????}
?
修改登錄servlet
?
作業:參考課堂筆記完成案例功能
?
QQ:395793718
電話:13651825024
轉載于:https://www.cnblogs.com/beyondcj/p/6270898.html
總結
以上是生活随笔為你收集整理的Javaweb 第15天 web练习和分页技术的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle 环境下 GoldenGat
- 下一篇: Kattis - bela