Extjs+jsp+Servlet完整前臺與後臺交換並顯示到表格
阿新 • • 發佈:2019-02-02
//使用者實體類
public class user(){
//資料庫表省略,型別應該都知道,構造方法有參無參自己要記得加,示例我就省略。
public int useid;
public String usename;
public String usepwd;
public String sex;
public int age;
}
//dao,裡面寫的是查詢資料庫的sql語句 public class UsersDao{ private Connection con; public DBHelper dbh;//連線資料庫幫助類 提供通用增刪改方法 public UsersDao(){} public UsersDao(Connection con){ this.con=con; } /** * 查詢所有使用者物件,特別提供無參查詢方法,有參的網上很多我就不寫,無參真的少 * @return */ public List<Usersa> selectUsersInfo(){ con=dbh.getConnection();//連線資料庫 List<Usersa> list=new ArrayList<Usersa>(); String sql="select * from USERSA"; ResultSet rs=null; try { Statement statement=(Statement)con.createStatement(); rs=statement.executeQuery(sql); //執行sql語句 Usersa stu=null; while(rs.next()){ stu=new Usersa(); stu.setUseid(rs.getInt("useid")); stu.setUsename(rs.getString("usename")); stu.setUsepwd(rs.getString("usepwd")); stu.setSex(rs.getString("sex")); stu.setAge(rs.getInt("age")); list.add(stu); } } catch (SQLException e) { e.printStackTrace(); } finally{ try { if(rs!=null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); } } return list; } }
//servlet,由於extjs普遍支援get方式的url傳遞,所有也寫成get,當然也可以寫成post
public class QueryUseServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); resp.setCharacterEncoding("utf-8"); req.setCharacterEncoding("utf-8"); UsersDao usersdao=new UsersDao(); List<Usersa> list = usersdao.selectUsersInfo(); //迭代器 Iterator it = list.iterator(); while(it.hasNext()){ System.out.println(it.next()+"content"); } JSONObject obj = new JSONObject(); JSONArray js = new JSONArray(); obj.put("data", js.fromObject(list)); //obj.put("count", 10); //統計數量,這裡寫死10條 resp.getWriter().write(obj.toString());//json格式化後輸出 } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
我這裡就只提供登入(其中登入就沒有驗證)和主頁顯示資料到表格,關鍵是資料顯示到表格上
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!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>Insert title here</title> </head> <body> <!--ExtJs框架開始--> <script type="text/javascript" src="/ExtText/ext-2.3.0/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="/ExtText/ext-2.3.0/ext-all.js"></script> <link rel="stylesheet" type="text/css" href="/ExtText/ext-2.3.0/resources/css/ext-all.css" /> <style type="text/css"> .loginicon { background-image: url(image/login.gif) !important;//此為驗證碼,如不需要可以不引入 } </style> <!--ExtJs框架結束--> <script type="text/javascript"> Ext.onReady(function () { //初始化標籤中的Ext:Qtip屬性。 Ext.QuickTips.init(); Ext.form.Field.prototype.msgTarget = 'side'; //提交按鈕處理方法 var btnsubmitclick = function () { if (form.getForm().isValid()) { //傳送到伺服器端獲取返回值再進行處理 Ext.Ajax.request({ url: "<%=path%>/UsersServlet", //這個是你後臺的controller, 用mvc 對映下就可以到後臺的java了 params: { usename: document.getElementById('txtusername').value,
<span style="white-space:pre"> </span>usepwd: document.getElementById('txtpassword').value }, // 這個就是你傳回去的引數,這個就是json物件
method:"post",
success:function(req){
if(req.responseText!=null||req.responseText!="")
{
Ext.Msg.alert('success','You got it!');
window.location.href="<%=path%>/index.jsp";//跳轉至主頁
}
else
{
Ext.Msg.alert('sorry','You lost!');
window.location.href="<%=path%>/login.jsp";
}
}
});
}
}
//重置按鈕"點選時"處理方法
var btnresetclick = function () {
form.getForm().reset();
}
//提交按鈕
var btnsubmit = new Ext.Button({
text: '提 交',
handler: btnsubmitclick
});
//重置按鈕
var btnreset = new Ext.Button({
text: '重 置',
handler: btnresetclick
});
//使用者名稱input
var txtusername = new Ext.form.TextField({
width: 140,
allowBlank: false,
maxLength: 20,
id:'txtusername',
name: 'txtusername',
fieldLabel: '使用者名稱',
blankText: '請輸入使用者名稱',
maxLengthText: '使用者名稱不能超過20個字元'
});
//密碼input
var txtpassword = new Ext.form.TextField({
width: 140,
allowBlank: false,
maxLength: 20,
inputType: 'password',
name: 'txtpassword',
id:'txtpassword',
fieldLabel: '密 碼',
blankText: '請輸入密碼',
maxLengthText: '密碼不能超過20個字元'
});
//驗證碼input
var txtcheckcode = new Ext.form.TextField({
fieldLabel: '驗證碼',
id: 'checkcode',
allowBlank: false,
width: 76,
blankText: '請輸入驗證碼!',
maxLength: 4,
maxLengthText: '驗證碼不能超過4個字元!'
});
//表單
var form = new Ext.form.FormPanel({
url: '******',
labelAlign: 'right',
labelWidth: 45,
frame: true,
cls: 'loginform',
buttonAlign: 'center',
bodyStyle: 'padding:6px 0px 0px 15px',
items: [txtusername, txtpassword, txtcheckcode],
buttons: [btnsubmit, btnreset]
});
//窗體
var win = new Ext.Window({
title: '使用者登陸',
iconCls: 'loginicon',
plain: true,
width: 276,
height: 174,
resizable: false,
shadow: true,
modal: true,
closable: false,
animCollapse: true,
items: form
});
win.show();
//建立驗證碼
var checkcode = Ext.getDom('checkcode');
var checkimage = Ext.get(checkcode.parentNode);
checkimage.createChild({
tag: 'img',
src: 'image/checkcode.gif',
align: 'absbottom',
style: 'padding-left:23px;cursor:pointer;'
});
});
</script>
</body>
</html>
userServlet
public class UsersServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
String usename=req.getParameter("usename");
String usepwd=req.getParameter("usepwd");
System.out.println(usename+"name");
System.out.println(usepwd+"pwd");
JSONObject json=new JSONObject();
<span style="white-space:pre"> </span>//如需做校檢,需在這裡呼叫userDao裡面的方法,並傳參。
json.put("usename",usename);
json.put("usepwd",usepwd);
json.put("success",true);
resp.getWriter().println(json);
}
}
下面是關鍵的,把後臺QuerySerServlet 資料顯示到前臺表格上
<pre name="code" class="html"><%@ 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>Insert title here</title>
</head>
<body>
<!--ExtJs框架開始-->
<script type="text/javascript" src="/ExtText/ext-2.3.0/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="/ExtText/ext-2.3.0/ext-all.js"></script>
<link rel="stylesheet" type="text/css" href="/ExtText/ext-2.3.0/resources/css/ext-all.css" />
<!--ExtJs框架結束-->
<script type="text/javascript">
Ext.onReady(function () {
Ext.MessageBox.alert('標題', 'Hello World!');//進入提示
});
</script>
<h1>
登入成功
</h1>
<script>
Ext.onReady(function(){
//多選框
var sm = new Ext.grid.CheckboxSelectionModel({
listeners:{
'selectionchange':function(obj){
var select = grid.getSelectionModel().getSelections();
}
}
});
//定義讀取資料格式
var dataReader = new Ext.data.JsonReader({
totalProperty:'count',
root: 'data'
},[
{ name: 'useid' },
{ name: 'usename' },
{ name: 'usepwd' },
{ name: 'sex' },
{ name: 'age' }
]);
//資料來源
var store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: 'QueryUseServlet',//servlet
method: 'GET' //get
}),
reader: dataReader,
sortInfo: {field: 'strostype', direction: 'DESC'},
autoLoad:false
});
store.load({params:{start:0,limit:8}});//載入資料時傳送分頁引數
//顯示欄
var dataColumns = new Ext.grid.ColumnModel({
columns: [
new Ext.grid.RowNumberer(),//行號
sm,
{ header: "員工", dataIndex: 'useid',resizable:false,sortable: true},
{ header: "員工姓名", dataIndex: 'usename',sortable: true},
{ header: "密碼", dataIndex: 'usepwd',sortable: true},
{ header: "性別", dataIndex: 'sex',sortable: true},
{ header: "年齡", dataIndex: 'age',sortable: true}
],
defaults: {
align: 'center'
}
});
//組裝表格
var grid = new Ext.grid.GridPanel({
store: store,
cm: dataColumns,
renderTo: Ext.getBody(),
autoExpandColumn: 1,
stripeRows: true,
autoHeight: true,
buttonAlign:'center',
// border: false,
sm:sm,
disableSelection: true,
frame: true,
loadMask:true,// '正在載入資料,請稍侯……提示
//stripeRows: true, //斑馬線效果
width: 950,
title:'表格',
viewConfig: { forceFit: true }//使列自動均分
,buttons: [{
text: "重新載入"
,handler:function(){
store.load({params:{start:0,limit:8}});
alert(store.getAt());
}
}],
tbar:new Ext.Toolbar({//頂部工具欄
items:[
new Ext.form.Label({ text:'名稱: ' }),
id,{
text: '查詢'
}
]
}),
bbar:['->',//底部工具欄
new Ext.PagingToolbar({//分頁元件
pageSize:8,
store:store,
displayInfo:true,
emptyMsg:'沒有資料顯示'
})]
});
});
</script>
</body>
</html>
到這裡介紹。