jsp页面 列表 展示 ajax异步实现方法

1. 服务端先返回页面基本结构(如message.jsp),

<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
      + path + "/";
%>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="ie ie6 lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]>  <html class="ie ie7 lt-ie9 lt-ie8"    lang="en"> <![endif]-->
<!--[if IE 8]>  <html class="ie ie8 lt-ie9"        lang="en"> <![endif]-->
<!--[if IE 9]>  <html class="ie ie9"           lang="en"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en" class="no-ie">
<!--<![endif]-->

<head>
<!-- Meta-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="author" content="">
<title>消息中心</title>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]><script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script><script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script><![endif]-->
<!-- Bootstrap CSS-->
<link rel="stylesheet" href="<%=path %>/app/css/bootstrap.css">
<!-- Vendor CSS-->
<link rel="stylesheet" href="<%=path %>/vendor/fontawesome/css/font-awesome.min.css">
<link rel="stylesheet" href="<%=path %>/vendor/animo/animate+animo.css">

<!-- START Page Custom CSS-->
<!-- Data Table styles-->
<link rel="stylesheet" href="<%=path %>/vendor/datatable/extensions/datatable-bootstrap/css/dataTables.bootstrap.css">
<link rel="stylesheet" href="<%=path %>/vendor/datatable/extensions/ColVis/css/dataTables.colVis.css">
<!-- END Page Custom CSS-->
<!-- App CSS-->
<link rel="stylesheet" href="<%=path %>/app/css/app.css">
<link rel="stylesheet" href="<%=path %>/app/css/beadmin-theme-c2.css">
<link rel="stylesheet" href="<%=path %>/vendor/sweetalert/lib/sweet-alert.css" />
<link rel="stylesheet" href="<%=path %>/css/page.css"/>

<!-- Modernizr JS Script-->
<script src="<%=path %>/vendor/modernizr/modernizr.js" type="application/javascript"></script>
<!-- FastClick for mobiles-->
<script src="<%=path %>/vendor/fastclick/fastclick.js" type="application/javascript"></script>.
 <script>
  var basePath = '<%=basePath %>';
  var pageNo = ${page.pageNo};
  var totalCount = ${page.totalCount};
  var totalPage = ${page>totalPage};
  var pageSize = ${page.pageSize};
</script>
</head>

<body>
<!-- START Main wrapper-->
<div class="wrapper" > 

 <!-- START Main section-->
 <section>
  <!-- START Page content-->
  <div class="content-wrapper" style="margin-left:-250px;margin-top:-40px;">
   <h3>消息中心
   <!-- <div style="float:right; margin-top:5px;" class="form-group">
         <button type="button" onclick="$('#myModal').modal({backdrop: 'static', keyboard: false});;" class="btn btn-labeled btn-success"> <span class="btn-label"><i class="fa fa-plus"></i> </span>添加</button>

        </div>-->
       <small>消息管理</small>
   </h3>

   <!-- START panel--> 

   <!-- START DATATABLE 3-->
   <div class="row">
    <div class="col-lg-12">
     <div class="panel panel-default">
       <div class="panel-heading" style="border-bottom:1px solid #eee;">
       <form class="form-inline" id="searchForm" method="post" action="<%=path %>/page/messageSearch.action">
        <div class="form-group"> <b>创建时间:  </b>
         <div class="datetimepicker input-group date mb-lg" data-pick-time="false">
          <input type="text" class="form-control" id="searchDateStart" name="searchDateStart" value='' disabled="disabled">
          <span class="input-group-addon"> <span class="fa-calendar fa"></span> </span> </div>
         <span style="margin-top:-8px;">—</span>
         <div class="datetimepicker input-group date mb-lg" data-pick-time="false">
          <input type="text" class="form-control" id="searchDateEnd" name="searchDateEnd" value='' disabled="disabled">
          <span class="input-group-addon"> <span class="fa-calendar fa"></span> </span> </div>
        </div>
        <div class="form-group">
                <b>接收者: </b>
                <input type="text" class="form-control mb-lg" id="receiver" name="receiver" value=''>
              </div>
        <div class="form-group"> <a style="margin:-10px 0 0 5px; float:left;" href="javascript:void(0);" class="mb-sm btn btn-primary" type="button" id="searchMessage">搜索</a> </div>
         <input type="hidden" id="pageNo" name="pageNo" value=''>
       </form>
      </div>
      <div class="table-responsive">
       <table class="table table-bordered table-hover dataTable no-footer" id="table-ext-1" >
        <thead>
         <tr>
          <th style="width:300px;">描述</th>
          <th class="sorting center" tabindex="0" aria-controls="datatable1" rowspan="1" colspan="1" style="width: 86px;" aria-label="Rendering engine: activate to sort column ascending">发送者</th>
          <th class="sorting center" tabindex="0" aria-controls="datatable1" rowspan="1" colspan="1" style="width: 86px;" aria-label="Rendering engine: activate to sort column ascending">接收者</th>
          <th class="sorting center" tabindex="0" aria-controls="datatable1" rowspan="1" colspan="1" style="width: 86px;" aria-label="Rendering engine: activate to sort column ascending">创建时间</th>
          <th class="th150 center">操作</th>
         </tr>
        </thead>
        <tbody id="message_body">

        </tbody>
        <tfoot>
         <tr> </tr>
        </tfoot>
       </table>
      </div>

      <div class="panel-footer">
       <div class="row">
        <div style="line-height:35px;" class="col-lg-3">
         <div class="input-group pull-left" id="message_showLines"> </div>
        </div>
        <div class="col-lg-9"></div>
         <div class="tcdPageCode"></div>
       </div>
      </div>
     </div>
    </div>
   </div>
   <!-- END DATATABLE 3--> 

  </div>
  <!-- END Page content-->
 </section>
 <!-- END Main section-->
</div>
<!-- END Main wrapper--> 

<!-- START modal-->
<div id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" class="modal" >
 <div class="modal-dialog" style="width:600px;">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" data-dismiss="modal" aria-hidden="true" class="close">×</button>
    <h4 id="myModalLabel" class="modal-title">新建应用</h4>
   </div>
   <div class="modal-body" style="padding-right:20px;">
    <form method="get" action="/" class="form-horizontal">
     <fieldset>
      <div class="form-group" style="padding-bottom:5px;">
       <label class="col-sm-2 control-label">名称</label>
       <div class="col-sm-10">
        <input type="text" class="form-control">
       </div>
      </div>
       <div class="form-group" style="margin-top:10px;">
       <label class="col-sm-2 control-label">描述</label>
       <div class="col-sm-10">
        <input type="text" class="form-control">
       </div>
      </div>

      <div class="form-group" style="margin-top:10px;">
       <label class="col-sm-2 control-label">URL</label>
       <div class="col-sm-10">
        <input type="text" class="form-control">
       </div>
      </div>

      <div class="form-group" style="margin-top:5px;">
        <label class="col-sm-2 control-label">类别</label>
        <div class="col-sm-10">
         <select class="form-control m-b" name="account">
           <option>Web</option>
           <option>Mobile</option>
         </select></div>
         </div>

         <div class="form-group" style="margin-top:5px;">
        <label class="col-sm-2 control-label">授权模式</label>
        <div class="col-sm-10">
         <select class="form-control m-b" name="account">
           <option>授权</option>
           <option>不授权</option>
         </select></div>
         </div>

         <div class="form-group" style="margin-top:10px;">
       <label class="col-sm-2 control-label">LOGO</label>
       <div class="col-sm-10">
        <input type="button" class="form-control">
       </div>
      </div>

     </fieldset>
    </form>
   </div>

   </fieldset>
   <div class="modal-footer">
    <button type="button" data-dismiss="modal" class="btn btn-default">取消</button>
    <button type="button" class="btn btn-primary">确定</button>
   </div>
  </div>
 </div>
</div>
</div>
<div id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" class="modal">
 <div class="modal-dialog" style="width:650px;">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" data-dismiss="modal" aria-hidden="true" class="close">×</button>
    <h4 id="myModalLabel" class="modal-title">修改密码</h4>
   </div>
   <div class="modal-body">
    <form method="get" action="/" class="form-horizontal">
     <fieldset>
      <div class="form-group" style="padding-bottom:5px;">
       <label class="col-sm-2 control-label">原密码</label>
       <div class="col-sm-10">
        <input type="text" class="form-control">
       </div>
      </div>
      <div class="form-group" style="padding-bottom:5px;">
       <label class="col-sm-2 control-label">新密码</label>
       <div class="col-sm-10">
        <input type="password" name="password" class="form-control">
       </div>
      </div>
      <div class="form-group" style="padding-bottom:5px;">
       <label class="col-sm-2 control-label">确认密码</label>
       <div class="col-sm-10">
        <input type="password" name="password" class="form-control">
       </div>
      </div>
     </fieldset>
    </form>
   </div>
   <div class="modal-footer">
    <button type="button" data-dismiss="modal" class="btn btn-default">关闭</button>
    <button type="button" class="btn btn-primary">Save changes</button>
   </div>
  </div>
 </div>
</div>
<div id="myModal3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" class="modal">
 <div class="modal-dialog" style="width:600px;">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" data-dismiss="modal" aria-hidden="true" class="close">×</button>
    <h4 id="myModalLabel" class="modal-title">编辑节目特殊单</h4>
   </div>
   <div class="modal-body">
    <form method="get" action="/" class="form-horizontal">
     <fieldset>
      <div class="form-group" style="padding-bottom:5px;">
       <label class="col-sm-2 control-label">表单标题</label>
       <div class="col-sm-10">
        <input type="text" class="form-control">
       </div>
      </div>
     </fieldset>
    </form>
   </div>
   <div class="modal-footer">
    <button type="button" data-dismiss="modal" class="btn btn-default">关闭</button>
    <button type="button" class="btn btn-primary">确定</button>
   </div>
  </div>
 </div>
</div>
<!-- END modal -->
<form method="post" id="pageForm" name="pageForm"
    action="<%=path%>/page/message_search.action">
    <input type="hidden" id="pageNo" name="pageNo" value="" />
  </form>
<!-- START Scripts-->
<!-- Main vendor Scripts-->
<script src="<%=path %>/vendor/jquery/jquery.min.js"></script>
<script src="<%=path %>/vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugins-->
<script src="<%=path %>/vendor/chosen/chosen.jquery.min.js"></script>
<script src="<%=path %>/vendor/slider/js/bootstrap-slider.js"></script>
<script src="<%=path %>/vendor/filestyle/bootstrap-filestyle.min.js"></script>
<!-- Animo-->
<script src="<%=path %>/vendor/animo/animo.min.js"></script>
<!-- Sparklines-->
<script src="<%=path %>/vendor/sparklines/jquery.sparkline.min.js"></script> 

<!-- MomentJs and Datepicker-->
<script src="<%=path %>/vendor/moment/min/moment-with-langs.js"></script>
<script src="<%=path %>/vendor/datetimepicker/js/bootstrap-datetimepicker.min.js"></script> 

<!-- Slimscroll-->
<script src="<%=path %>/vendor/slimscroll/jquery.slimscroll.min.js"></script>
<!-- Store + JSON-->
<script src="<%=path %>/vendor/store/store+json2.min.js"></script>
<!-- ScreenFull-->
<script src="<%=path %>/vendor/screenfull/screenfull.min.js"></script>
<!-- START Page Custom Script-->
<!-- Data Table Scripts-->
<script src="<%=path %>/vendor/datatable/media/js/jquery.dataTables.min.js"></script>
<script src="<%=path %>/vendor/datatable/extensions/datatable-bootstrap/js/dataTables.bootstrap.js"></script>
<script src="<%=path %>/vendor/datatable/extensions/datatable-bootstrap/js/dataTables.bootstrapPagination.js"></script>
<script src="<%=path %>/vendor/datatable/extensions/ColVis/js/dataTables.colVis.min.js"></script>
<!-- START Page Custom Script-->
<script src="<%=path %>/vendor/wizard/js/bwizard.min.js"></script>
<!-- Form Validation-->
<script src="<%=path %>/vendor/parsley/parsley.min.js"></script>
<!-- END Page Custom Script-->
<!-- App Main-->
<script src="<%=path %>/app/js/app.js"></script>
<script src="<%=path %>/vendor/sweetalert/lib/sweet-alert.min.js"></script>
 <script src="<%=path %>/script/message.js"></script>
 <script src="<%=path %>/page/js/page.js"></script>
<!-- END Scripts-->

</body>
</html>

2. example.js加载的时候,再去异步请求获取页面数据(表格、分页等),再动态创建表,分页链接等

$(function(){
  initTable();

  $("#searchMessage").on("click",function(){
    messageSearch(pageNo);
  });

  //获取message列表 "pageNo" : pageNo
  function initTable(){
    $.ajax({
      url : basePath + "page/message_list.action",
      type : "get",
      dataType : "json",
      success : function(dataMap){
        createTBody(dataMap);
        createTFoot(dataMap);
      },
      error : function(errorData){
      }
    });
  }
  //查询message
  function messageSearch(pageNo){
    var searchDateStart = $("#searchDateStart").val();
    var searchDateEnd = $("#searchDateEnd").val();
    var startDate = new Date(searchDateStart);
    var endDate = new Date(searchDateEnd);
    var num = endDate - startDate;
    if(num<0){
      $("#searchDateEnd").val('');
      swal({
        title: "结束日期不能晚于开始日期",
        text: "",
        type: "error"
      });
      return false;
    }
    var receiver = $("#receiver").val();
    $.ajax({
      url : basePath + "page/message_search.action",
      type : "POST",
      data : {
        "pageNo" : pageNo,
        "searchDateStart" : searchDateStart,
        "searchDateEnd" : searchDateEnd,
        "receiver" : receiver
      },
      dataType : "json",
      success : function(dataMap){
        createTBody(dataMap);
        createTFoot(dataMap);
      },
      error : function(errorData){

      }
    });
  }

  function createTBody(dataMap){
    if(dataMap!=null){
      var messageListPage = dataMap.messageListPage;
      var html = [];
      for(var i=0; i<messageListPage.length; i++){
        var message = messageListPage[i];
        var cTime = message.createtime.replace(/T/g," ");
        html.push('<tr class="gradeX center">');
        html.push('<td style="text-align:left;">'+message.content+'</td>');
        html.push('<td>' + message.provider + '</td>');
        html.push('<td>' + message.receiver + '</td>');
        html.push('<td>' + cTime + '</td>');
        html.push('<td message_id=' + message.id + '><a href="#" class="message_del btn btn-danger btn-xs"> 删除 </a></td>');
        html.push('</tr>');
      }
      $("#message_body").empty().html(html.join(''));
    }
  }

  function createTFoot(dataMap){
    if(dataMap!=null){
      startNum = dataMap.startNum;
      stopNum = dataMap.stopNum;
      totalCount = dataMap.totalCount;
      pageNo = dataMap.pageNo;
      pageSize = dataMap.pageSize;
      var str = '显示 ' + startNum + '至' + stopNum + '项 , 共' + totalCount +' 项。';
      $("#message_showLines").html(str);
    }
  }

  $('#message_body').on('click','a.message_del',function(){
    var message_id = $(this).parent("td").attr("message_id");
    swal({
      title : "确认要删除吗?",
      text : "删除后将不能恢复!",
      type : "warning",
      showCancelButton : true,
      confirmButtonColor : "#DD6B55",
      confirmButtonText : "Yes, delete it!",
      cancelButtonText : "No, cancel plx!",
      closeOnConfirm : false,
      closeOnCancel : false
    }, function(isConfirm) {
      if (isConfirm) {
        $.ajax({
          url:basePath + "page/message_del.action",
          data:{
            "id":message_id
          },
          type:"get",
          dataType:"json",
          success:function(dataMap){
            if(dataMap!=null && dataMap.message=="success"){
              swal("删除!",
                  "已经成功删除.",
              "success");
              initTable();
            }else{
              swal("删除!",
                  "删除失败.",
              "error");
            }
          },
          error : function(errorMsg){
            swal("删除失败!",
                errorMsg,
            "error");
          }

        });
      } else {
        swal("Cancelled", "Your imaginary file is safe :)",
            "error");
      }
    });
  });

  $('.tcdPageCode').extendPagination({
    pageId : pageNo,
    totalCount : totalCount,
    showPage : 5,
    limit : pageSize,
    callback : function(pageNo, limit, totalCount) {
      messageSearch(pageNo);
    }
  });

});

注意: 表格是动态创建的,其中的按钮绑定事件时,一定要先找到它的父节点(或祖先节点),再到指定节点,绑定事件

如上面的  $("#serviceRepo_body").on('click','a.record_view',function(){});

分页js插件(page.js), 同时引入jquery-1.11.1.min.js 和 bootstrap.js

/**
 * Created by Hope on 2014/12/28.
 */
(function ($) {
  $.fn.extendPagination = function (options) {
    var defaults = {
      pageId:'',
      totalCount: '',
      showPage: '10',
      limit: '5',
      callback: function () {
        return false;
      }
    };
    $.extend(defaults, options || {});
//    alert(defaults.pageId);
    if (defaults.totalCount == '') {
      //alert('总数不能为空!');
      $(this).empty();
      return false;
    } else if (Number(defaults.totalCount) <= 0) {
      //alert('总数要大于0!');
      $(this).empty();
      return false;
    }
    if (defaults.showPage == '') {
      defaults.showPage = '10';
    } else if (Number(defaults.showPage) <= 0)defaults.showPage = '10';
    if (defaults.limit == '') {
      defaults.limit = '5';
    } else if (Number(defaults.limit) <= 0)defaults.limit = '5';
    var totalCount = Number(defaults.totalCount), showPage = Number(defaults.showPage),
      limit = Number(defaults.limit), totalPage = Math.ceil(totalCount / limit);
    if (totalPage > 0) {
      var html = [];
      html.push(' <ul class="pagination">');
      html.push(' <li class="previous"><a href="#">«</a></li>');
      html.push('<li class="disabled hidden"><a href="#">...</a></li>');
      if (totalPage <= showPage) {
        for (var i = 1; i <= totalPage; i++) {
          if (i == defaults.pageId) html.push(' <li class="active"><a href="#">' + i + '</a></li>');
          else html.push(' <li><a href="#">' + i + '</a></li>');
        }
      } else {
        for (var j = 1; j <= showPage; j++) {
          if (j == defaults.pageId) html.push(' <li class="active"><a href="#">' + j + '</a></li>');
          else html.push(' <li><a href="#">' + j + '</a></li>');
        }
      }
      html.push('<li class="disabled hidden"><a href="#">...</a></li>');
      html.push('<li class="next"><a href="#">»</a></li></ul>');
      $(this).html(html.join(''));
      if (totalPage > showPage) $(this).find('ul.pagination li.next').prev().removeClass('hidden');

      var pageObj = $(this).find('ul.pagination'), preObj = pageObj.find('li.previous'),
        currentObj = pageObj.find('li').not('.previous,.disabled,.next'),
        nextObj = pageObj.find('li.next');

      function loopPageElement(minPage, maxPage) {
        var tempObj = preObj.next();
        for (var i = minPage; i <= maxPage; i++) {
          if (minPage == 1 && (preObj.next().attr('class').indexOf('hidden')) < 0)
            preObj.next().addClass('hidden');
          else if (minPage > 1 && (preObj.next().attr('class').indexOf('hidden')) > 0)
            preObj.next().removeClass('hidden');
          if (maxPage == totalPage && (nextObj.prev().attr('class').indexOf('hidden')) < 0)
            nextObj.prev().addClass('hidden');
          else if (maxPage < totalPage && (nextObj.prev().attr('class').indexOf('hidden')) > 0)
            nextObj.prev().removeClass('hidden');
          var obj = tempObj.next().find('a');
          if (!isNaN(obj.html()))obj.html(i);
          tempObj = tempObj.next();
        }
      }

      function callBack(curr) {
        defaults.callback(curr, defaults.limit, totalCount);
      }

      currentObj.click(function (event) {
        event.preventDefault();
        var currPage = Number($(this).find('a').html()), activeObj = pageObj.find('li[class="active"]'),
          activePage = Number(activeObj.find('a').html());
        if (currPage == activePage) return false;
        if (totalPage > showPage) {
          var maxPage = currPage, minPage = 1;
          if (($(this).prev().attr('class'))
            && ($(this).prev().attr('class').indexOf('disabled')) >= 0) {
            minPage = currPage - 1;
            maxPage = minPage + showPage - 1;
            loopPageElement(minPage, maxPage);
          } else if (($(this).next().attr('class'))
            && ($(this).next().attr('class').indexOf('disabled')) >= 0) {
            if (totalPage - currPage >= 1) maxPage = currPage + 1;
            else maxPage = totalPage;
            if (maxPage - showPage > 0) minPage = (maxPage - showPage) + 1;
            loopPageElement(minPage, maxPage)
          }
        }
        activeObj.removeClass('active');
        $.each(currentObj, function (index, thiz) {
          if ($(thiz).find('a').html() == currPage) {
            $(thiz).addClass('active');
            callBack(currPage);
          }
        });
      });
      preObj.click(function (event) {
        event.preventDefault();
        var activeObj = pageObj.find('li[class="active"]'), activePage = Number(activeObj.find('a').html());
        if (activePage <= 1) return false;
        if (totalPage > showPage) {
          var maxPage = activePage, minPage = 1;
          if ((activeObj.prev().prev().attr('class'))
            && (activeObj.prev().prev().attr('class').indexOf('disabled')) >= 0) {
            minPage = activePage - 1;
            if (minPage > 1) minPage = minPage - 1;
            maxPage = minPage + showPage - 1;
            loopPageElement(minPage, maxPage);
          }
        }
        $.each(currentObj, function (index, thiz) {
          if ($(thiz).find('a').html() == (activePage - 1)) {
            activeObj.removeClass('active');
            $(thiz).addClass('active');
            callBack(activePage - 1);
          }
        });
      });
      nextObj.click(function (event) {
        event.preventDefault();
        var activeObj = pageObj.find('li[class="active"]'), activePage = Number(activeObj.find('a').html());
        if (activePage >= totalPage) return false;
        if (totalPage > showPage) {
          var maxPage = activePage, minPage = 1;
//          if ((activeObj.next().next().attr('class'))
//            && (activeObj.next().next().attr('class').indexOf('disabled')) >= 0) {
//            maxPage = activePage + 2;
//            if (maxPage > totalPage) maxPage = totalPage;
//            minPage = maxPage - showPage + 1;
//            loopPageElement(minPage, maxPage);
//          }
          if ((activeObj.next().next().attr('class'))
              && (activeObj.next().next().attr('class').indexOf('disabled')) >= 0) {
            maxPage = activePage + 2;
            if (maxPage > totalPage) maxPage = totalPage;
            minPage = maxPage - showPage + 1;
            loopPageElement(minPage, maxPage);
          }
        }
        $.each(currentObj, function (index, thiz) {
          if ($(thiz).find('a').html() == (activePage + 1)) {
            activeObj.removeClass('active');
            $(thiz).addClass('active');
            callBack(activePage + 1);
          }
        });

      });
    }
  };
})(jQuery);

3.项目采用struts2, 返回json, 在struts中配置, 并在action中使用map来封装数据, 并添加get方法

struts.xml

<package name="message" namespace="/" extends="struts-default, json-default">
    <action name="message_*" class="messageAction" method="{1}">
      <result name="index">/WEB-INF/jsp/message.jsp</result>
      <result name="success" type="json">
        <param name="root">dataMap</param>
      </result>
    </action>
  </package>

action

package com.cdv.mediastar.action;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cdv.mediastar.model.Message;
import com.cdv.mediastar.service.MessageService;
import com.cdv.mediastar.util.PageParameter;
import com.opensymphony.xwork2.ActionSupport;

@Scope("request")
@Controller("messageAction")
public class MessageAction extends ActionSupport {

  /**
   *
   */
  private static final long serialVersionUID = 3731009117710718470L;

  private Logger logger = Logger.getLogger(MessageAction.class);
  @Resource
  private MessageService messageService;

  Map<String, Object> dataMap = new HashMap<String, Object>();

  public Map<String, Object> getDataMap() {
    return dataMap;
  }

  public String index(){
    HttpServletRequest request = ServletActionContext.getRequest();
    PageParameter page = new PageParameter();
    int pageNo = page.getPageNo();
    int totalCount = messageService.count(null, null, null, 0);
    int totalPage = totalCount%page.getPageSize()==0?totalCount/page.getPageSize():totalCount/page.getPageSize()+1;
    int startNum = 1, stopNum = 1;
    startNum = (pageNo-1)*page.getPageSize()+1;
    if((startNum+page.getPageSize()-1)<=totalCount){
      stopNum = startNum+page.getPageSize()-1;
    }else{
      stopNum = totalCount;
    }
    page.setTotalCount(totalCount);
    page.setTotalPage(totalPage);
    request.setAttribute("page", page);
    request.setAttribute("startNum", startNum);
    request.setAttribute("stopNum", stopNum);
    return "index";
  }

  public String list(){
    dataMap.clear();
    PageParameter page = new PageParameter();
    int s = 0, max = page.getPageSize();
    List<Message> messageListPage = messageService.find(null, null, null, s, max);
    int totalCount = messageService.count(null, null, null, 0);
    int totalPage = totalCount%page.getPageSize()==0?totalCount/page.getPageSize():totalCount/page.getPageSize()+1;
    page.setTotalCount(totalCount);
    page.setTotalPage(totalPage);
    int startNum = 0, stopNum = 0;
    startNum = 1;
    if((startNum+page.getPageSize()-1)<=totalCount){
      stopNum = startNum+page.getPageSize()-1;
    }else{
      stopNum = totalCount;
    }
    dataMap.put("startNum", startNum);
    dataMap.put("stopNum", stopNum);
    dataMap.put("totalCount", totalCount);
    dataMap.put("totalPage", totalPage);
    dataMap.put("pageNo", page.getPageNo());
    dataMap.put("messageListPage", messageListPage);
    return "success";
  }

  public String del(){
    dataMap.clear();
    HttpServletRequest request = ServletActionContext.getRequest();
    Long id = Long.parseLong(request.getParameter("id"));
    int deleteFlag = messageService.delete(id);
    if(deleteFlag>0){
      dataMap.put("message", "success");
    }else{
      dataMap.put("message", "error");
    }
    logger.info("rocky>>>>>>>>>>>>delete message flag======"+deleteFlag);
    return "success";
  }

  public String search() throws ParseException, IOException{
    dataMap.clear();
    HttpServletRequest request = ServletActionContext.getRequest();
    Date from = null, to = null ;
    String searchDateStart = request.getParameter("searchDateStart");
    if(searchDateStart!=null && searchDateStart!="") {
      from = new SimpleDateFormat("MM/dd/yyyy").parse(searchDateStart);
    }
    String searchDateEnd = request.getParameter("searchDateEnd");
    if(searchDateEnd!=null && searchDateEnd!="") {
      to = new SimpleDateFormat("MM/dd/yyyy").parse(searchDateEnd);
    }
    String receiver = request.getParameter("receiver");
    String pageNoStr = request.getParameter("pageNo");
    PageParameter page = new PageParameter();
    int pageNo = page.getPageNo();
    int s = 0, max = page.getPageSize();
    if(pageNoStr!=null && pageNoStr!=""){
      pageNo = Integer.parseInt(pageNoStr);
      s = (pageNo-1)*page.getPageSize();
    }
    List<Message> messageListPage = messageService.find(receiver, from, to, s, max);
    int totalCount = messageService.count(receiver, from, to, 0);
    int totalPage = totalCount%page.getPageSize()==0?totalCount/page.getPageSize():totalCount/page.getPageSize()+1;
    int startNum = 0, stopNum = 0;
    startNum = (pageNo-1)*page.getPageSize()+1;
    if((startNum+page.getPageSize()-1)<=totalCount){
      stopNum = startNum+page.getPageSize()-1;
    }else{
      stopNum = totalCount;
    }
    dataMap.put("startNum", startNum);
    dataMap.put("stopNum", stopNum);
    dataMap.put("pageNo", pageNo);
    dataMap.put("totalCount", totalCount);
    dataMap.put("pageSize", page.getPageSize());
    dataMap.put("searchDateStart", searchDateStart);
    dataMap.put("searchDateEnd", searchDateEnd);
    dataMap.put("receiver", receiver);
    dataMap.put("messageListPage", messageListPage);
    return "success";
  }
}

以上就是小编为大家带来的jsp页面 列表 展示 ajax异步实现方法全部内容了,希望大家多多支持我们~

(0)

相关推荐

  • Ajax+Servlet+jsp显示搜索效果

    一.Ajax简介 Ajax被认为是(Asynchronous JavaScript and XML)的缩写,允许浏览器与服务器通信而无需刷新当前的页面的技术都被叫做Ajax eg:百度搜索.实时地图.etc,在Ajax模型中,数据在客户端与服务器之间独立传输,服务器用不刷新整个页面便可更新数据: 二.Ajax的工作原理图 三.Ajax发送和接收相应的方法 1.发送请求相应的方法 1).onreadystatechange事件处理函数:该函数由服务器触发而不是用户,每次readyState属性的改

  • jquery ajax 如何向jsp提交表单数据

    AJAX越来越火了,作为一个WEB程序开发者要是不会这个感觉就要落伍,甚至有可能在求职的时候屡被淘汰.我也是一个WEB程序开发者,当然我也要 "随波逐流"一把,不然饭碗不保啊! 之前实现AJAX使用Javascript脚本一个一个敲出来的,很繁琐.学习Jquery之后就感觉实现AJAX并不是那么的困难了,当然除了 Jquery框架外还有其它的优秀框架这里我就着重说下比较流行的Jquery.Jquery AJAX提交表单有两种方式,一是url参数提交数据,二是form提交(和平常一样在后

  • 在(ASP/PHP/JSP/html/js)中禁止ajax缓存的方法集锦

    ajax缓存有好处,但也有坏处,缓存有时候会导致误操作,影响用户体验,若你的WEB项目不需要ajax缓存功能,可按下述方法来禁止ajax缓存. 一.在ASP中禁止ajax缓存: '放在ASP网页最开头部分 Response.expires=0 Response.addHeader("pragma","no-cache") Response.addHeader("Cache-Control","no-cache, must-revalid

  • 基于jsp的AJAX多文件上传的实例

    最近的项目开发中,遇到了一个多文件上传的问题,即在不刷新页面的情况下,上传多个文件至服务器.现总结分享如下: 本文主要采用了基于jsp的ajax,jquery,servlet等技术. 1.upload.jsp 点击上传时,调用对应的fileupload函数,通过ajax将文件异步传送到servlet中处理.注意在文件上载时,所使用的编码类型应当是"multipart/form-data",它既可以发送文本数据,也支持二进制数据上载. <%@ page language="

  • JSP+jquery使用ajax方式调用json的实现方法

    本文实例讲述了JSP+jquery使用ajax方式调用json的实现方法.分享给大家供大家参考,具体如下: 前台: <script type="text/javascript" src="jquery-1.5.1.min.js"></script> <script type="text/javascript"> //test function test(uid) { if(confirm("确定该用户

  • 使用js声明数组,对象在jsp页面中(获得ajax得到json数据)

    1.在jsp页面的js中可以用jsp标签 var patientInfoList={patientId:"${session.patientId}"};var docDepList=[],noTypeMap=["","普通号","主治医生号","副主任医师号","主任医师号"]; <c:forEach varStatus="idx" var="list

  • ajax 提交数据到后台jsp页面及页面跳转问题

    ajax 提交数据到后台jsp页面及页面跳转问题 我logincheck.jsp页面取传参数代码: String user=request.getParameter("user1"); String pwd=request.getParameter("pwd1"); login.jsp input 取2参数何用ajax 传给logincheck.jsp $.ajax({ type : "POST", url : baseUrl+"m/m

  • jsp+ajax发送GET请求的方法

    本文实例讲述了ajax发送GET请求,然后通过jsp页面来接收处理的实现方法.分享给大家供大家参考.具体实现方法如下: Ajax发送GET请求 这里用一个实例演示Ajax发送get请求,实例具体要求为一个注册页面,当用户填写完用户名称时,该输入框失去焦点后会通过Ajax向后台发送验证信息,如果用户名不是admin则通过验证,否则不通过验证. 下面先看JSP页面具体信息: 复制代码 代码如下: <form action="servlet/LoginServlet" method=&

  • jsp+ajax实现的局部刷新较验验证码(onblur事件触发较验)

    本文实例讲述了jsp+ajax实现的局部刷新较验验证码(onblur事件触发较验).分享给大家供大家参考,具体如下: 前台显示页面: welcome.jsp <%@ page language="java" contentType="text/html; utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transiti

  • jsp中利用jquery+ajax在前后台之间传递json格式参数

    经过一段时间的实验琢磨,终于将前后台之间的参数传递搞定了,实验所用工具myeclipse+structs1.2. 总结:容易出错的地方:1.ajax中data的格式一定要写对,这里举了两种形式,一种是 data:{参数:""} 另一种是 data:"参数="+变量. 2.后台传递到前台数据转化为json格式,步骤要掌握好. 3.在js使用jquery必须要引用进来,否则会不执行jquery语句,这个问题困扰了我半天才解决掉,菜鸟的悲哀啊.jquery引用流程如下:网

  • JSP使用ajaxFileUpload.js实现跨域问题

    废话不多说了,直接给大家贴代码了. jsp代码如下 $.ajaxFileUpload ( { url:'http://lh.abc.com:8080/gap/gap/fileUpload.do',//用于文件上传的服务器端请求地址(本机为fxb.abc.com) secureuri:false,//一般设置为false fileElementId:'file',//文件上传空间的id属性 <input type="file" id="file" name=&q

  • jsp实现checkbox的ajax传值实例

    本文实例讲述了jsp实现checkbox的ajax传值用法.分享给大家供大家参考.具体分析如下: 今天我想用ajax把选中的所有的chekbox的值全部都传到后台做一个处理,但在后台接收值的时候,我遇到了麻烦,以为没有经过跳转所以request中是没有值的. 查了一下,查到了解决方法,如下 页面代码: 复制代码 代码如下: <input type="checkbox" name="atitle" value="历史名胜"><la

  • jsp+ajax实现无刷新上传文件的方法

    本文实例讲述了jsp+ajax实现无刷新上传文件的方法.分享给大家供大家参考,具体如下: 列表页:selectaddress.jsp js页:ajax_edit.js jsp处理页:editaddress.jsp 上传工具类:UploadUtil.java 思想:由于安全问题,javascript操纵不了文件, 导致ajax不能动态上传文件,所以选择了iframe, 列表页把form表单提交到一个隐式的iframe里面,设置表单的属性 复制代码 代码如下: enctype='multipart/

  • AJAX和JSP混合使用方法实例

    首先要知道AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术. 什么是 AJAX ? AJAX = 异步 JavaScript 和 XML. AJAX即"Asynchronous Javascript And XML"(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.AJAX 是一种用于创建快速动态网页的技术. 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况下,对网页的某部分

随机推荐