js前台分頁顯示後端JAVA資料響應

來源:互聯網
上載者:User

好久沒有寫過代碼了,手有些癢了,正好底下小弟們某些功能的實現著實影響工程進度,便自己動手給寫了一段。

功能:js前台分頁顯示 + 後台資料響應(JAVA Servlet即可)
架構:jquery1.8.7
此文目的:給那些剛入行軟體開發,喜歡這也看看,那也看看,這兒copy一下,那兒copy一下初級小菜鳥們做一個表帥;
1 為程式者需認真踏實坐下來;
2 程式需要有投入才有收穫;
3 有收穫才有鼓舞,才有動力一步一步往下走!

下面上代碼,具體會有小注釋
1、web頁面的邏輯處理(js代碼寫到頁面裡時,有個好處,調試時不會受js檔案快取的影響) 複製代碼 代碼如下:<%@ 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>訂單結算</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)" />
<br>

</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>
<script type="text/javascript">
//填充頁面資訊
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()'/>";
// alert(pageContent);
$('#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){
// alert(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>未結</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>";
// alert(tdc);
$('#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;
//numint()函數判斷是否為數字
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;
}
</script>
</html>

2 後台頁面響應的JAVA代碼(即一個標準的Servlet) 複製代碼 代碼如下: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);
System.out.println(content);
break;
//for OrderClose.jsp in get order data
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();
}
}
//generate data from a search sql
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);
// System.out.println(temp);
return temp;
}
}

3 讓Servlet在web.xml中的配置參考 複製代碼 代碼如下:<!-- 各種盤點 -->
<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>

4 付上本次後台調用的一個關鍵方法,將查詢轉化為JSON資料格式的方法 複製代碼 代碼如下://return DataType {"tittle":[{"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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pst = (PreparedStatement)hm.get("PreparedStatement");
sh.closeAll(rs, pst, con);
return tjson;
}


1 裡面沒有見到過的方法調用,不用擔心,搞過java串連資料庫的都沒有問題;
2 這個裡面有一個比較不足的地方,將頁數資訊與頁面資料分兩次AJAX請求得到,這個是非常影響效能的,如果能做到將一次ajax請求,一次解析擷取全部需要資料,那就比較出彩了(嵌套JSON就是不錯的選擇)。
3 由於並非專職搞web開發,發現這個CSS樣式搭配起來還是非常費勁的。
最後貼個上來:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.