使用Jsp/Js/Ajax/Json/Jquery/Easyui + Servlet + JDBC + Lucen

来源:互联网 发布:淘宝助理免费吗 编辑:程序博客网 时间:2024/05/29 18:55

要求

1)         使用jQuery-EasyUI组件,构建自已的Web页面(下)

2)         使用Jsp/Js/Ajax/Json/Jquery/Easyui +Servlet + JDBC + Lucene/Mysql/Oracle完成数据库分页

3)         欣赏几款优秀的jQuery组件,构建自已的Web页面

 

 

一)学会查阅文档,使用jQuery-EasyUI,构建自已的Web页面

  (1)网址:www.jeasyui.com,下载并参考学习<<jQuery EasyUI v1.3.5官方API中文版.exe>>手册

 

   (2)什么是jQuery-EasyUI

        参见<<什么是EasyUI.JPG>>

        是一种第三方组织开发的一款基于jQuery的,简单易用的,功能强大的

WEB前端JavaScript现成的组件库

        注意:今天的EasyUI组件库的版本较高,需要高版本浏览器支持,

中低版本浏览器会有不能正常执行的情况

 

  (3)JavaScript,AJAX,JSON,jQuery,EasyUI分别能解决什么问题

            JS:基于浏览器对web页面中的节点进行操作,比较麻烦

            jQuery:基于浏览器简化对web页面中的节点进行操作,做到了write less do more

            AJAX:基于浏览器与服务端进行局部刷新的异步通讯编程模式

            JSON:简化自定义对象的创建与AJAX数据交换轻量级文本

            EasyUI:快速基于现成的组件创建自已的web页面

组件:是指已经由第三方开源组织写好的,直接可以使用的功能界面,例如:form,layout,tree...

     注意:我们学的都是零散的组件,项目中需要将其装配起来,方可构建完整的web页面,

EasyUI只是众多前端WEB组件之一

 

   (4)jQuery-EasyUI快速入门----可折叠功能的面板

        第一步:创建一个js-day05这么一个web工程

        第二步:在WebRoot目录下创建00-base.html

        第三步:在WebRoot目录下创建js和themes目录,导入官方文件

参见<< jquery-easyui-1.3.6文件夹>>

        第四步:在00-base.html 文件的<head>标签中引入如下文件

    <!-- 引入外部CSS文件 -->

    <linkrel="stylesheet"href="../themes/icon.css"type="text/css"></link>

    <linkrel="stylesheet"href="../themes/default/easyui.css"type="text/css"></link>

 

    <!-- 引入外部JS文件 -->

    <scripttype="text/javascript"src="../js/jquery.min.js"></script>

    <script type="text/javascript"src="../js/jquery.easyui.min.js"></script>

 

        第五步:在00-base.html 文件的<body>标签中创建如下<div>标签

    <div

       id="p"

       class="easyui-panel"

        style="width:500px;height:200px;padding:10px;"  

        title="我的面板"

        iconCls="icon-save"

        collapsible="true">  

        内容<br/>

        内容<br/>

        内容<br/>

        内容<br/>

    </div>

 

(5)EasyUI组件

 

       (06)form表单

                  

             》validatebox验证框

                    姓名:必填/1-6个字符/必填中文

                    邮箱:必填/1-30个字符/必填符合邮箱格式/后缀必须是com或cn

    <divstyle="margin:100px"></div>

    用户名: 

    <inputid="vv"/>

    <scripttype="text/javascript">

       $("#vv").validatebox({

           required:true,

           validType:["length[1,4]","zhongwen"]

       });

    </script>

    <scripttype="text/javascript">

       //自定义验证规则

       $.extend($.fn.validatebox.defaults.rules,{   

           zhongwen : {   

               validator: function(value){//value表示在文本框中输入的内容   

                   if(/^[\u3220-\uFA29]+$/.test(value)){

                       return true;

                   }

               },   

               message: "用户名必须填中文

           }   

       });

    </script>

        思考:检查邮箱的扩展名只能是{'com','cn'}       

 

             》combobox下拉列表框

                   设置下拉列表框默认值 

    你所在的城市:

    <selectid="cc" class="easyui-combobox"name="city"style="width:150px;">  

        <option>aitem1</option>   

        <option>bitem1</option>  

        <option>bitem2</option>  

        <option>citem1</option>  

        <option>citem2</option>  

        <option>citem3</option>  

        <option>ditem1</option>  

        <option>ditem2</option>  

        <option>ditem3</option>  

        <option>ditem4</option>  

    </select> 

    <scripttype="text/javascript">

       $(function(){

           $("#cc").combobox("setValue","长沙");

        });

    </script>

              

    你所在的城市:

    <inputid="cc" name="city" value="广州"/>  

   

    <scripttype="text/javascript">

       $("#cc").combobox({

           url:"combobox_data.json",

           valueField:"id",   

           textField:"text"

       });

       //textField表示在下拉框中看得见的内容,<option>长沙</option>

       //valueField表示在下拉框中看不见的内容,用于向后台传递数据<option value="cs">长沙</option>

    </script>

                combobox_data.json:

[

  {   

    "id":"gz",   

    "text":"广州"  

  },

  {   

    "id":"zs",   

    "text":"中山"  

  },

  {   

    "id":"fs",   

    "text":"佛山"

  },

  {   

    "id":"sz",   

    "text":"深圳",

    "selected":true  

  },

  {   

    "id":"yj",   

    "text":"阳江"  

  }

]

 

             》datebox日期选择框

                    显示yyyy-mm-dd格式,

               添加<script type="text/javascript"src="locale/easyui-lang-zh_CN.js"></script>   

                   选中日期并显示选中的日期

入职时间:<inputid="dd" type="text"></input> 

    <scripttype="text/javascript">

       $("#dd").datebox({

           required:true

       });

    </script>

    <scripttype="text/javascript">

       $("#dd").datebox({

           onSelect:function(date){

              alert(date.getFullYear()+""+(date.getMonth()+1)+""+date.getDate());

           }

       });

    </script>

 

        

             》numberspinner数字微调框

                   设置数字微调框中的值

                   获取数字微调框中的值

    商品数量:<inputtype="text"size="2px" value="1"/><span></span>

    <hr/>

    <inputid="ss" required="required"style="width:80px;"> 

    <scripttype="text/javascript">

       $("#ss").numberspinner({

           value:1,

           min:1,

           max:100,

           editable:true

       });

    </script>

    <scripttype="text/javascript">

           $("#ss").numberspinner({

              onSpinUp:function(){

                  //获取numberspinner的当前值

                  varvalue = $("#ss").numberspinner("getValue");

                  //numberspinner的当前值设置到商品数量文本框中

                  $("input:first").val(value).css("color","red");

                  //如果value值为100

                  if( value == 100 ){

                     $("span:first").html("商品已满,不能再购买了").css("color","blue");  

                      $("input:first").attr("disabled","disabled");

                  }

              },

              onSpinDown:function(){

                  //获取numberspinner的当前值

                  var value = $("#ss").numberspinner("getValue");

                  //numberspinner的当前值设置到商品数量文本框中

                  $("input:first").val(value).css("color","red");

                  //如果value值小于100

                  if( value < 100 ){

                     $("span:first").html(""); 

                      $("input:first").removeAttr("disabled");

                  }

              }

           });

    </script>

 

                 》slider滑动条框

                   拖动滑块,将值同步显示到span标签中

    身高:<span>150</span><spanid="tip"></span>

    <divstyle="margin:50px">

       <input

           id="ss"

           class="easyui-slider"

           value="0" 

           style="width:600px;height:500px"

            data-options="max:180,min:150,mode:'v',showTip:true,rule:[150,'|',160,'|',170,'|',180]"/> 

    </div>

   

    <scripttype="text/javascript">

       $("#ss").slider({

           onChange:function(newValue){

              $("span:first").text(newValue);

              if(newValue == 180){

                  $("#tip").text("你真高呀");

              }else if(newValue >= 170){

                  $("#tip").text("你不错呀");

              }else if(newValue >= 160){

                  $("#tip").text("你可以呀");

              }

           }

       });

    </script>

 

       (07)progressbar进度条

                 》每隔1秒让进度条按随机数填充,直至充满进度条刻度

    进度条:

    <divid="p" style="width:400px;"></div>

    <scripttype="text/javascript">

       $("#p").progressbar({

           width:"auto",

           height:44,

           value:0

       });

    </script>

 

    <inputtype="button"value="开始"style="font-size:111px"/>

    <scripttype="text/javascript">

       var timeID = null;

       //随机产生1-9之间的整数,包含19

       functiongetNum(){

           return Math.floor(Math.random()*9)+1;

       }

       $(":button").click(function(){

           timeID = window.setInterval(function(){

              //获取随机数,例如:9

              varnum = getNum();

              //获取进度条当前值,例如:99

              varvalue = $("#p").progressbar("getValue");

              //如果随机数加当前值小于100的话      

              if(value + num < 100){

                  //填充进度条当前值

                  $("#p").progressbar("setValue",value+num);

              }else{

                  //将进度条当前值设置为100

                  $("#p").progressbar("setValue",100);

                  //停止定时器

                  window.clearInterval(timeID);

                  //"开始"按钮生效

                  $(":button").removeAttr("disabled");

              }     

           },200);  

           //"开始"按钮失效

           $(this).attr("disabled","disabled");   

       });

    </script>

 

       (08)window窗口

                 》单击按钮,打开或关闭一个窗口

    <inputid="open1" type="button" value="打开窗口1"/>

    <inputid="open2" type="button" value="打开窗口2"/>

    <hr/> 

    <divid="win1"></div>

    <divid="win2"></div>

    <scripttype="text/javascript">

       $("#open1").click(function(){

           $("#win1").window({

              title:"我的窗口1",

              width:200,

              height:300,

              top:100,

              left:400,

              collapsible:false,

              minimizable:false,

              maximizable:false,

              closable:true,

              draggable:false,

              resizable:false,

              shadow:false,

              modal:false,

              href:"08_datebox.html"

           });

       });

       $("#open2").click(function(){

           $("#win2").window({

              title:"我的窗口2",

              width:200,

              height:300,

              top:100,

              left:800,

              collapsible:false,

              minimizable:false,

              maximizable:false,

              closable:true,

              draggable:false,

              resizable:false,

              shadow:false,

              modal:false

           });

       });

    </script>

 

       (09)dialog对话框

             》单击按钮,打开或关闭一个对话框

    <inputid="open1" type="button" value="打开对话框1"/>

    <hr/>

    <divid="dd1"></div>  

    <scripttype="text/javascript">

       $("#open1").click(function(){

           $("#dd1").dialog({

              width:300,

              height:400,

              left:400,

              top:100,

              title:"对话框1",

              toolbar:[

                  {

                     text:'编辑',

                     iconCls:'icon-edit',

                      handler:function(){alert('edit')}

                  },

                  {

                     text:'帮助',

                     iconCls:'icon-help',

                      handler:function(){alert('help')}

                 

                  }

              ],

              buttons:[

                  {

                     text:'确定',

                     handler:function(){alert('ok')}

                  },

                  {

                     text:'关闭',

                     handler:function(){

                         //关闭本对话框

                         $("#dd1").dialog("close");

                     }

                  }

              ],

              href:"07_combobox_2.html"

           });

       });

    </script>

 

       (10)messager消息窗口

                 》单击按钮,弹出警告框

                 》单击按钮,弹出确认框

                 》单击按钮,弹出显示框

                 》单击按钮,弹出输入框

<inputtype="button"value="警告框"/>

    <inputtype="button"value="确认框"/>

    <inputtype="button"value="输入框"/>

    <inputtype="button"value="显示框"/>

    <hr/>

    <divstyle="margin:200px"></div>    

    <scripttype="text/javascript">

       $(":button").click(function(){

           var tip = $(this).val();

           tip = $.trim(tip);

           if("警告框"== tip){

              $.messager.alert("我的警告框","不能睡觉了","warning");

           }else if("确认框"== tip){

              $.messager.confirm("我的确认框","你确定在关闭本窗口吗?",function(flag){

                  alert(flag);

              });

           }else if("输入框"== tip){

              $.messager.prompt("我的输入框","你决定要学习Android还是JavaEE?",function(value){

                  alert(value);

              });

           }else if("显示框"== tip){

              $.messager.show({

                  title:"我的显示框",

                  msg:"不要太区分AndroidJavaEE",

                  showType:"fade",

                  width:200,

                  height:200,

                  timeout:1000

              });

           }

       });

    </script>

 

       (11)tree树

                 》选中树中某个子节点,弹出选中的内容 

                  》用树替代linkButton按钮

<ul id="ttt" class="easyui-tree"style="width:222px">  

        <li>  

           <span>第一章</span>

        </li>  

        <li>  

            <span>第二章</span>

            <ul>

                <li>

                   <span>第一节</span>

                </li>

                <li>

                   <span>第二节</span>

                   <ul>

                       <li>第一条</li>

                       <li>第二条</li>

                       <li>第三条</li>

                   </ul>

                </li>

            </ul> 

        </li>  

    </ul>

              

<ul id="ttt"></ul>

    <scripttype="text/javascript">

       $("#ttt").tree({

           url:"tree_data.json",

           lines:true

       });

    </script>

    <scripttype="text/javascript">

       $("#ttt").tree({

           onClick:function(node){

              alert(node.text);

           }

       });

    </script>

               tree_data.json:

[

  {

    "id":1,

    "text":"第一章"

  },

  {

    "id":2,

    "text":"第二章",

    "state":"closed",

    "children":[

       {

       "id":21,

          "text":"第一节"

       },

       {

          "id":22,

          "text":"第二节"       

       },

       {

          "id":23,

          "text":"第三节",

          "state":"closed",

          "children":[

              {

                "id":231,

               "text":"第一条"

 

              },    

              {

                   "id":232,

               "text":"第二条"     

              }

           ]     

       }

    ]

  }

]

 

       (12)datagrid数据表格

》参见E:\开发类库\jquery-easyui-1.3.6\demo\datagrid(9-数据网格)\products.json

              》 DateGrid会异步以POST方式向服务器传入二个参数:page和rows二个参数,服务端需要哪个,就接收哪个参数

                   * page:需要显示的页号

                   * rows:需要获取多少条记录

             

开发过程:

DB:

use js;

drop tableif exists users;

create table users(

       id    int(5) primary key auto_increment,

       name varchar(4) not null,

       sal int(5) not null

);

insert into users(name,sal)values('小赵君',1000);

insert into users(name,sal)values('中赵君',1500);

insert into users(name,sal)values('大赵君',2000);

insert into users(name,sal)values('赵小君',2500);

insert into users(name,sal)values('赵中君',3000);

insert into users(name,sal)values('赵大君',3500);

insert into users(name,sal)values('赵君小',4000);

insert into users(name,sal)values('赵君中',4500);

insert into users(name,sal)values('赵君大',5000);

insert into users(name,sal)values('赵君',5500);

select id,name,sal from users;

                               Entity:

public class User {

    private Integerid;

    private Stringname;

    private Integersal;

    public User(){}

    public Integer getId() {

       returnid;

    }

    public void setId(Integer id) {

       this.id = id;

    }

    public String getName() {

       returnname;

    }

    public void setName(String name) {

       this.name = name;

    }

    public Integer getSal() {

       returnsal;

    }

    public void setSal(Integer sal) {

       this.sal = sal;

    }

}

public class PageBean {

    private IntegercurrPageNO;

    private IntegerperPageNO;

    private IntegerallRecordNO;

    private IntegerallPageNO;

    private List<User>userList = new ArrayList<User>();

    public PageBean(){}

    public Integer getCurrPageNO() {

       returncurrPageNO;

    }

    public void setCurrPageNO(Integer currPageNO) {

       this.currPageNO = currPageNO;

    }

    public Integer getPerPageNO() {

       returnperPageNO;

    }

    public void setPerPageNO(Integer perPageNO) {

       this.perPageNO = perPageNO;

    }

    public Integer getAllRecordNO() {

       returnallRecordNO;

    }

    public void setAllRecordNO(Integer allRecordNO) {

       this.allRecordNO = allRecordNO;

    }

    public Integer getAllPageNO() {

       returnallPageNO;

    }

    public void setAllPageNO(Integer allPageNO) {

       this.allPageNO = allPageNO;

    }

    public List<User> getUserList() {

       returnuserList;

    }

    public void setUserList(List<User> userList) {

       this.userList = userList;

    }

}

              Util:

public class JdbcUtil {

    private static ComboPooledDataSource dataSource =new ComboPooledDataSource();

    public static ComboPooledDataSource getDataSource() {

       returndataSource;

    }

}

src/c3p0-config.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<c3p0-config>

    <default-config>

       <propertyname="driverClass">com.mysql.jdbc.Driver</property>

       <propertyname="jdbcUrl">jdbc:mysql://127.0.0.1:3306/js</property>

       <propertyname="user">root</property>

       <propertyname="password">root</property>

       <propertyname="acquireIncrement">2</property>

       <propertyname="initialPoolSize">5</property>

       <propertyname="minPoolSize">1</property>

       <propertyname="maxPoolSize">5</property>

    </default-config>

</c3p0-config>

Dao:

public class UserDao {

    //select count(id) from users where 1=1 and name like '%%';

    public Integer getAllRecordNO(String sql)throws Exception{

       QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());

       Long temp = (Long) runner.query(sql,new ScalarHandler());

       return temp.intValue();

    }

    //select id,name,sal from users where 1=1 and name like '%%' limit ?,?;

    public List<User> findAllRecord(String sql,Integer start,Integer size)throws Exception{

       QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());

       return runner.query(sql,new BeanListHandler<User>(User.class),new Object[]{start,size});

    }

}

Service:

public class UserService {

    private UserDaouserDao = new UserDao();

    //show("",2);

    public PageBean show(String keywords,Integer currPageNO)throws Exception{

       PageBean pageBean = new PageBean();

      

       String sqlA = "select count(id) from users where 1=1";

       String sqlB = "select id,name,sal from users where 1=1";

      

       if(keywords !=null && keywords.trim().length() > 0){

           sqlA += " and name like '%" + keywords +"%'";

           sqlB += " and name like '%" + keywords +"%'";

       }

      

       pageBean.setCurrPageNO(currPageNO);

      

       Integer allRecordNO = userDao.getAllRecordNO(sqlA);

       pageBean.setAllRecordNO(allRecordNO);

      

       Integer allPageNO = null;

       if(pageBean.getAllRecordNO() % pageBean.getPageSize() == 0){

           allPageNO = pageBean.getAllRecordNO() / pageBean.getPageSize();

       }else{

           allPageNO = pageBean.getAllRecordNO() / pageBean.getPageSize() + 1;

       }

       pageBean.setAllPageNO(allPageNO);

      

       Integer size = pageBean.getPageSize();

       Integer start = (pageBean.getCurrPageNO()-1) * size;

       sqlB += " limit ?,?";

       List<User> userList = userDao.findAllRecord(sqlB,start,size);

       pageBean.setUserList(userList);

      

       return pageBean;

    }

}

Action:

public class UserServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

       try{

           request.setCharacterEncoding("UTF-8");

          

           String keywords = request.getParameter("keywords");

           if(keywords==null || keywords.trim().length()==0){

              keywords = "";

           }

           System.out.println("keywords=" + keywords);//

          

           String temp = request.getParameter("page");

           if(temp ==null || temp.trim().length()==0){

              temp = "1";

           }

           Integer currPageNO = Integer.parseInt(temp);

           System.out.println("currPageNO=" + currPageNO);//2

          

           UserService userService = new UserService();

           PageBean pageBean = userService.show(keywords,currPageNO);

          

           Map<String,Object> map = new LinkedHashMap<String,Object>();

           map.put("total",pageBean.getAllRecordNO());

           map.put("rows",pageBean.getUserList());

          

           JSONArray jsonArray = JSONArray.fromObject(map);

           String jsonJAVA = jsonArray.toString();

           jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1);

          

           response.setContentType("text/html;charset=UTF-8");

           PrintWriter pw = response.getWriter();

           pw.write(jsonJAVA);

           pw.flush();

           pw.close();

          

        }catch(Exception e){

           e.printStackTrace();

       }

    }

}

 WebRoot/userList.jsp

<%@ pagelanguage="java"pageEncoding="UTF-8"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <!-- 引入外部CSS文件 -->

    <linkrel="stylesheet"href="${pageContext.request.contextPath}/themes/icon.css"type="text/css"></link>

    <linkrel="stylesheet"href="${pageContext.request.contextPath}/themes/default/easyui.css"type="text/css"></link>

    <!-- 引入外部JS文件 -->

    <scripttype="text/javascript"src="${pageContext.request.contextPath}/js/jquery.min.js"></script>

    <scripttype="text/javascript"src="${pageContext.request.contextPath}/js/jquery.easyui.min.js"></script>

    <scripttype="text/javascript"src="${pageContext.request.contextPath}/locale/easyui-lang-zh_CN.js"></script>

  </head>

  <body>

   

    姓名:

    <inputtype="text"size="10px"id="name"/>

    <inputtype="button"value="查询"onclick="find()"/>

    <tableid="dg"></table> 

   

    <scripttype="text/javascript">

       function find(){

           $("#dg").datagrid("load",{

              "keywords": $.trim( $("#name").val() )

           });

       }

    </script>

    <scripttype="text/javascript">

       $("#dg").datagrid({  

           width:400,

           url:"${pageContext.request.contextPath}/UserServlet",   

           fitColumns:true,

           columns:[[   

               {field:'id',title:'编号',width:100},   

               {field:'name',title:'姓名',width:100},   

               {field:'sal',title:'薪水',width:100}   

           ]],

           singleSelect:true,

           pagination:true,

           pageNumber:1,

           pageSize:2,

           pageList:[2]   

       });   

    </script>

      

  </body>

</html>

 

             

 

                             

 

 

二)欣赏几款优秀的jQuery组件,构建自已的Web页面

      牛图库素材网----->http://niutuku.com/

 

 

 

 

作业:

1)将今天讲的EasyUI组件,查阅文档,练习一遍

2)参见<<作业题.JPG>>

 

 

0 0