先看需求:
本次練習的數據庫sql文件以及代碼地址:
http://pan.baidu.com/s/1jIdV7r4
使用Bootstrap構建顯示層
JSP+Servlet+EL+JSTL+Dao+MySql+JDBC
主頁的jsp代碼
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>新聞列表</title>
<link href="${pageContext.request.contextPath}/bootstrap3/css/bootstrap.min.css" rel="stylesheet">
<link href="${pageContext.request.contextPath}/bootstrap3/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="${pageContext.request.contextPath}/bootstrap3/js/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap3/js/bootstrap.min.js"></script>
</head>
<body>
<h4 class="text-center"><a href="news?action=list">新聞列表</a></h4>
<div class="container" style="margin-top: 60px;">
<div class="row-fluid">
<div class="col-md-8">
<jsp:include page="${mainPage }"></jsp:include>
</div>
<div class="col-md-4">
</div>
</div>
</div>
</body>
</html>
後臺Servlet代碼:
package com.zhiqi.web;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiqi.dao.NewsDao;
import com.zhiqi.model.News;
import com.zhiqi.model.PageBean;
import com.zhiqi.util.DbUtil;
import com.zhiqi.util.PropertiesUtil;
import com.zhiqi.util.StringUtil;
public class NewsServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private DbUtil dbUtil=new DbUtil();
private NewsDao newsDao=new NewsDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String action=req.getParameter("action");
if("list".equals(action)){//新聞列表
try {
newsList(req,resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if("show".equals(action)){//新聞瀏覽
try {
newsList(req,resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void newsList(HttpServletRequest req, HttpServletResponse resp) throws Exception{
//分頁
String page=req.getParameter("page");
if(StringUtil.isEmpty(page)){
page="1";
}
Connection conn=null;
try {
conn=dbUtil.getConn();
int pageCount=0;
int pageSize=Integer.parseInt(PropertiesUtil.getValue("pageSize"));
int total=newsDao.newsCount(conn);
PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(PropertiesUtil.getValue("pageSize")));
ArrayList<News> newsList=newsDao.newsList(conn,pageBean);
//分頁總數
int rowCount=total;
if(rowCount%pageSize==0){
pageCount=rowCount/pageSize;
}else{
pageCount=rowCount/pageSize+1;
}
req.setAttribute("pageCount",pageCount);
//判斷
if(Integer.parseInt(page)<1){
page="1";
}
if(Integer.parseInt(page)>pageCount){
page=pageCount+"";
}
req.setAttribute("page",page);
//分頁的下拉
ArrayList<String> pageNumberList=new ArrayList<String>();;
for(int i=1;i<=pageCount;i++){
pageNumberList.add(i+"");
}
req.setAttribute("pageNumberList", pageNumberList);
req.setAttribute("newsList", newsList);
req.setAttribute("mainPage", "news/newsView.jsp");
req.getRequestDispatcher("main.jsp").forward(req, resp);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
dbUtil.closeConn(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
封裝的PageBean等工具類有助於簡化代碼
jsp界面代碼:
newView.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<div>
<div>
<span class="glyphicon glyphicon-th-list"></span><a href="news?action=list">新聞列表</a>
</div>
<div>
<c:forEach var="news" items="${newsList }">
<div style="margin-top: 15px;">
<a href="news?action=show&ids=${news.ids }">${news.title }</a> -
『<fmt:formatDate value="${news.time }" type="date" pattern="yyyy-MM-dd HH:mm:ss"/>』
</div>
<div>
${fn:substring(news.memo,0,100) }
</div>
<div style="margin-top: 15px;">
<a href="news?action=show&ids=${news.ids }">詳情 >></a>
<hr>
</div>
</c:forEach>
</div>
<nav>
<ul class="pager">
<li><a href="news?action=list&page=${1 }">首頁</a></li>
<c:if test="${page<=1 }">
<a href="news?action=list&page=${1 }">上一頁</a>
</c:if>
<c:if test="${page>1 }">
<li><a href="news?action=list&page=${page-1 }">上一頁</a></li>
</c:if>
<c:if test="${page<pageCount }">
<li><a href="news?action=list&page=${page+1 }">下一頁</a></li>
</c:if>
<c:if test="${page>=pageCount }">
<a href="news?action=list&page=${pageCount }">下一頁</a>
</c:if>
<li><a href="news?action=list&page=${pageCount }">尾頁</a></li>
<li>
<select id="sel" οnchange="pageNumberChange()">
<c:forEach var="elem" items="${pageNumberList }">
<option value="${elem }" ${elem==page?'selected':'' }>第${elem }頁</option>
</c:forEach>
</select>
</li>
<li>當前是第 ${page } 頁,一共${pageCount }頁</li>
</ul>
</nav>
</div>
<script type="text/javascript">
function pageNumberChange(){
var sel=document.getElementById("sel");
//alert(sel.value);
window.location="news?action=list&page="+sel.value;
}
</script>
main.jsp通過<jsp:include page=""></jsp:include>引入使得代碼層次分明
請求new?action=list後
運行如圖:
上一頁與下一頁的判斷使用了<c:if></c:if>標籤
遍歷下拉列表的option選項,selected的某項使用三目運算符在EL表達式內計算(EL表達式支持三目運算)
下拉列表onchange事件觸發時
JavaScript來從新請求後臺Servlet
<select id="sel" οnchange="pageNumberChange()">
<c:forEach var="elem" items="${pageNumberList }">
<option value="${elem }" ${elem==page?'selected':'' }>第${elem }頁</option>
</c:forEach>
</select>
<script type="text/javascript">
function pageNumberChange(){
var sel=document.getElementById("sel");
//alert(sel.value);
window.location="news?action=list&page="+sel.value;
}
</script>
使用JSTL的fn標籤的substring()來進行字符串長度的截取
<div>
${fn:substring(news.memo,0,100) }
</div>