很久沒寫程式,手有點癢,剛好手底下幾個功能的進度實在拖,就自己動手寫了一段。功能很單純:前台用 JS 做分頁顯示,後台用 Java Servlet 提供資料,前端框架選 jQuery 1.8.7。
寫這篇也是想給剛入行、習慣到處 copy 一段拼一段的朋友做個示範。三句話:坐下來踏實寫;投入才有收穫;有收穫才有動力繼續往下走。
把 JS 直接寫在頁面裡有個好處:除錯時不會被瀏覽器的 JS 檔案快取干擾。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>訂單結算</title>
<script type="text/javascript" src="js/jquery-1.8.7.min.js"></script>
<LINK href="images/style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div align="left" style="width: 83%">
<p style="color: blue">
采購單狀態:
<select id="orderstatus">
<option value="" SELECTED>-search all!-</option>
<option value="未結">未結</option>
<option value="部分">部分</option>
<option value="已結">已結</option>
</select>
<input type="button" style="height: 25px;width:70px" value="查詢" onClick="firstFindPage(1)" />
</p>
</div>
<div>
<table width="100%" cellpadding="0" cellspacing="0" border="1" style="padding:2" bordercolorlight="#3B4D61" bordercolordark="#ffffff" id='contentList'>
</table>
</div>
<br>
<div>
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="padding:2" id='pageList'>
</table>
</div>
</body>
腳本部分拆成幾個職責明確的函數:writePageList 產生頁碼列(首頁、上一頁、下一頁、末頁、跳轉框),writeContent 用 $.each 把後端 JSON 渲染成表格列,findPage 是統一的查詢入口,changeStatus 負責修改訂單狀態,findOrderDetail 開新視窗看明細,gotoPage 與 numint 則處理跳頁輸入的合法性檢查。
//填充頁面信息
function writePageList(curpage,wholePage){
var pageContent = "";
if(curpage != 1){
pageContent += "<a href='#' onclick='findPage(1)' style='text-decoration: none'><b style='font-size: 12'>第一頁</b></a> ";
pageContent += "<a href='#' onclick='findPage("+(parseInt(curpage)-1)+")' style='text-decoration: none'><b style='font-size: 12'>上一頁</b></a> ";
}
if(curpage != wholePage){
pageContent += "<a href='#' onclick='findPage("+(parseInt(curpage)+1)+")' style='text-decoration: none'><b style='font-size: 12'>下一頁</b></a> ";
pageContent += "<a href='#' onclick='findPage("+(parseInt(wholePage))+")' style='text-decoration: none'><b style='font-size: 12'>最後一頁</b></a> ";
}
if(1 == wholePage){
pageContent += "<a href='#' onclick='findPage("+(parseInt(wholePage))+")' style='text-decoration: none'><b style='font-size: 12'>當前只有一頁</b></a> ";
}
pageContent += "頁數:<label id='curpage' style='color: red; font-size: 13'>"+curpage+"</label>/<label id='wholepages' style='color: red; font-size: 13'>"+wholePage+"</label> ";
pageContent += " <input id='ppage' type='text' size='5'/><input type='button' style='height: 25px;width:55px' value='>>跳轉' onclick='gotoPage()'/>";
$('#pageList').empty();
$('#pageList').append("<tr><td>"+ pageContent +"</td></tr>");
}
//修改訂單狀態
function changeStatus(orid){
var status = $('#status'+orid).val();
if(status==null || status==undefined){
alert("狀態信息不能為空!");
return;
}
$.post("DetailChange", { etype : 11, orid : orid, status : status }, function(data) {
if(parseInt(data) > 0) alert("狀態修改成功");
else alert("修改失敗");
});
}
//查詢訂單詳情
function findOrderDetail(orid){
var urls = "FindOrderDetail.jsp?orid="+orid;
window.open(urls,'newwindow','height=400,width=600,top=100,left=200,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no, status=no');
}
//填充表格數據
function writeContent(data){
var content = data.Orders;
$('#contentList').empty();
$('#contentList').append("<tr><td><b style='font-size: 16'>采購編號</b></td><td><b style='font-size: 16'>經手人</b></td><td><b style='font-size: 16'>訂單日期</b></td><td><b style='font-size: 16'>備注</b></td><td><b style='font-size: 16'>狀態</b></td><td><b style='font-size: 16'>操作1</b></td><td><b style='font-size: 16'>操作2</b></td></tr>");
$.each(content,function(idx, item) {
var tdc = "<tr><td>"+String(item.orid)+"</td><td>"+String(item.wname)+"</td><td>"+String(item.date)+"</td><td>"+String(item.remark)+"</td>"
+ "<td><select id='status"+String(item.orid)+"' style='height: 25px;width:80px'><option value='"+String(item.orderstatus)+"' SELECTED>"+String(item.orderstatus)+"</option><option value='未結'>未結</option><option value='部分'>部分</option><option value='已結'>已結</option></select></td>"
+ "<td><input type='button' value='修改狀態' style='height: 25px;width:80px' onclick='changeStatus("+String(item.orid)+")'/></td>"
+ "<td><input type='button' value='查看詳情' style='height: 25px;width:80px' onclick='findOrderDetail("+String(item.orid)+")'/></td></tr>";
$('#contentList').append(tdc);
});
}
//用於翻頁
function findPage(pageId){
var curstatus = $('#orderstatus').val();
$.post("AllCheckAction", { executetype : 5, page : pageId, orderstatus : curstatus, pagerows :1 }, function(data) {
var contents = data.ContentBody;
$.each(contents,function(id, ite) {
var curpage = ite.page;
var wholePages = ite.wholepage;
con = ite.searchtext;
$.post("AllCheckAction", { executetype : 6, scondition : con },function(data2){
writeContent(data2);
},"json");
writePageList(curpage,wholePages);
});
}, "json");
}
//查詢按鈕調用
function firstFindPage(pageId){ findPage(pageId); }
//頁面跳轉響應邏輯
function gotoPage(){
var ppage = $('#ppage').val();
var maxpage = $('#wholepages').innerHTML;
if(ppage == null || ppage == undefined || (!numint(ppage))){
alert("無效的頁碼!");
return;
}
if(parseInt(ppage)>parseInt(maxpage) || parseInt(ppage)<1){
alert("請求頁不存在頁碼!");
return;
}
findPage(ppage);
}
//判斷是否為整數
function numint(value) {
var p = "0123456789";
for ( var i = 0; i < value.length; i++) {
var num = p.indexOf(value.charAt(i));
if (num < 0) return false;
}
return true;
}
用 executetype 做為分派依據:5 負責計算總筆數、總頁數並組出帶 limit 的查詢條件;6 則依條件把實際資料轉成 JSON 輸出。
package com.ljb.ttt.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ljb.ttt.impl.BasicDao;
public class AllCheckAction extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); }
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
int executetype = -1;
String types = req.getParameter("executetype");
if(types == null) return;
else executetype = Integer.valueOf(types);
PrintWriter out = resp.getWriter();
BasicDao bd = new BasicDao();
switch(executetype){
case 5:
String orderStatus = req.getParameter("orderstatus");
Integer page = Integer.valueOf(req.getParameter("page"));
Integer pageSize = Integer.valueOf(req.getParameter("pagerows"));
String condition = "";
String content = "";
Integer wholePages = 0;
if(orderStatus != null && (!orderStatus.equals(""))){
condition = String.format(" and orderstatus='%s'",orderStatus);
}
int wholeSize = bd.count("`order` t1,worker t2", pageSize," and t1.wid=t2.wid" + condition+" and t1.orid in (select orid from orderdetail)");
if(0 == wholeSize%pageSize) wholePages = wholeSize/pageSize;
else wholePages = wholeSize/pageSize + 1;
//對於不正確頁的判斷處理
if (page >= wholePages) page = wholePages;
if(page <= 1) page = 1;
condition += String.format(" limit %d,%d",pageSize*(page-1),pageSize);
content = String.format("{\"ContentBody\":[{\"page\":\"%d\",\"wholepage\":\"%d\",\"searchtext\":\""+condition+"\"}]}", page, wholePages);
out.print(content);
break;
case 6:
String sconditon = (String)req.getParameter("scondition");
if(sconditon != null){
if(sconditon.equals("")) out.print(getJsonData(6, "", "Orders",bd));
else out.print(getJsonData(6, sconditon, "Orders",bd));
}
break;
default:
break;
}
out.flush();
out.close();
} catch (IOException e) { e.printStackTrace(); }
}
//依查詢 SQL 產生 JSON
private String getJsonData(int type,String searchContent,String jsonName,BasicDao bd){
String sql = "";
switch(type){
case 6:
sql = String.format("select t1.orid,t2.wname,t1.date,t1.remark,t1.orderstatus from `order` t1,worker t2 where t1.wid=t2.wid" + " and t1.orid in (select orid from orderdetail)%s",searchContent);
break;
default: break;
}
String temp = bd.getJsonStr(sql,jsonName);
return temp;
}
}
<servlet>
<servlet-name>CheckSaveServlet</servlet-name>
<servlet-class>com.ljb.ttt.servlet.CheckSaveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckSaveServlet</servlet-name>
<url-pattern>/CheckSaveServlet</url-pattern>
</servlet-mapping>
//return DataType {"tittle":[{"colName":"val"},{"colName":"val"}]}
public String getJsonStr(String sql,String jsonName){
String jsonStr = "";
String tjson = "";
Connection con = null;
ResultSet rs = null;
PreparedStatement pst = null;
con = sh.getConnection();
HashMap<String,Object> hm = sh.select(con, pst, rs, sql, null);
rs = (ResultSet)hm.get("ResultSet");
int colNum;
try {
colNum = rs.getMetaData().getColumnCount();
String colName[] = new String[colNum];
for(int i= 0;i<colNum;i++) colName[i] = rs.getMetaData().getColumnName(i+1);
while(rs.next()){
jsonStr += "{";
String temp = "";
for(int i= 0;i<colNum;i++){
temp += "\"";
temp += colName[i];
temp += "\":\"";
temp += rs.getString(i+1);
temp += "\",";
}
jsonStr += temp.substring(0, temp.length()-1);
jsonStr += "},";
}
tjson += "{\""+jsonName + "\":[";
if(jsonStr!="") tjson += jsonStr.substring(0, jsonStr.length()-1);
tjson += "]}";
} catch (SQLException e) { e.printStackTrace(); }
pst = (PreparedStatement)hm.get("PreparedStatement");
sh.closeAll(rs, pst, con);
return tjson;
}
1、程式裡沒出現過的方法(例如 sh.getConnection()、bd.count())不用擔心,寫過 JDBC 的都看得懂。
2、最該改的地方是:頁碼資訊與頁面資料分成兩次 AJAX 請求,這對效能的傷害很明顯。改成一次請求、一次解析拿回全部資料(用嵌套 JSON 就是很好的選擇)會漂亮得多。
3、還有個安全問題必須點出來:這段程式把 orderstatus 直接 String.format 進 SQL,等於完全沒有防禦 SQL injection,前端 writeContent 也把後端字串直接拼進 HTML,存在 XSS 風險。正確做法應改用 PreparedStatement 的佔位符綁定參數,輸出時做一次 HTML 轉義。當年只顧著把功能跑通,這一點是無論如何都該補上的。
由於並非專職做 Web 開發,光是調 CSS 樣式就花了不少力氣。最後附上當時的執行結果截圖:
