Extjs+jsp+Servlet完整前台与后台交换并显示到表格

来源:互联网 发布:越贵妃知乎 编辑:程序博客网 时间:2024/05/01 17:34


//用户实体类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>


到这里介绍。




2 0