通过 servlet 和 jsp 更新 html table

Update html table via servlet and jsp

我正在创建一个简单的 Java 网页,它必须从用户那里获取输入,然后将数据推送到同一页面上的 table。一切都运行良好。每次用户输入页面时,servlet 都会完成它的工作并重新加载页面并更新 table 。我的问题是,如何在不重新加载页面的情况下更新 table。

其次,我有一个输入字段,用于搜索 table。再次,它正在工作。但是,我也在尝试将 jquerys tablesorter 添加到我的 table。我已根据教程完成所有操作,但没有进行排序。这可能是因为搜索字段吗?我也在使用 Bootstrap 来设计我的 table,这可能是原因吗(尽管 jquerys tablesorter 声明,它也适用于 Bootstrap)。

Servlet returns 具有:

request.getRequestDispatcher("WEB-INF/views/Login.jsp").forward(request, response);;

更新 我的 JSP 看起来像这样: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>My title</title>
  <link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"    rel="stylesheet">
  <link href="css/myStyle.css" rel="stylesheet">    
</head>
<body>
  <form  method="post" >
   <div class="container">
    <div class="jumbotron">
            <label for="name">Nimi</label>
            <input type="text" name="name" class="form-control"/>
            <label for="email">Email</label>
            <input type="email" name="email" class="form-control"/>
            <label for="syKP">Sünnikuupäev</label>
            <input type="text" name="syKP" class="form-control"/>
            <label for="aadress">Aadress</label>
            <input type="text" name="aadress" class="form-control"/><br>
            <button type="submit" class="btn btn-info btn-md">Add</button>
    </div>
</div>
</form>
<div class="container">
 <div class="jumbotron">
  <input type="text" id="search" placeholder="Type to search"><br>
   <table class="table table-hover tablesorter" id="tabel">
<thead>
 <tr>
    <th>Nimi</th>
    <th>Aadress</th>
    <th>Synd</th>
    <th>Email</th>
    <th>Muuda</th>
    <th>Kustuta</th>
 </tr>
</thead>
<c:forEach items="${dataLst.getData()}" var="person">
 <tbody id="table">
  <tr >
    <td><c:out value="${person.getNimi()}"/></td>
    <td><c:out value="${person.getAadress()}"/></td>
    <td><c:out value="${person.getSynniKP() }"/></td>
    <td><c:out value="${person.getEmail()}"/></td>
    <td><button class="btn button-default"><span class="glyphicon glyphicon-pencil"></span></button></td>
    <td><button class="btn button-default"><span class="glyphicon glyphicon-    remove-sign"></span></button></td>
  </tr>
 </tbody>
</c:forEach>   
</table>
</div>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="javascript/main.js"></script>
</body>
</html>

我的 servlet 文件是这样的:

package com.energy;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(urlPatterns="/login.do")
public class LoginServlet extends HttpServlet{

DataList dataLst = new DataList();

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException{
    request.getRequestDispatcher("/WEB-INF/views/Login.jsp").forward(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse  response) 
throws ServletException, IOException {
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String aadress = request.getParameter("aadress");
    String syKP = request.getParameter("syKP");



    PersonData person = new PersonData(name, aadress, syKP, email);
    dataLst.addPerson(person);
    //request.setAttribute("name", request.getParameter("name"));
    //request.setAttribute("email", request.getParameter("email"));
    //System.out.println(dataLst.getData().get(0).getNimi());

    request.setAttribute("dataLst",dataLst);
    request.getRequestDispatcher("WEB-INF/views/Login.jsp").forward(request,     response);;
}

}

动态更新table:

通常,JSON用于从服务器发送响应。使用 GSON.jar 将 java 对象转换为相应的 JSON。这正在替换 servlet 中的请求调度程序,如下面更新的 servlet class-

所示
package com.energy;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

@WebServlet(urlPatterns="/login.do")
@MultipartConfig
public class LoginServlet extends HttpServlet{

  private static final long serialVersionUID = 1L;
  DataList dataLst = new DataList();

  protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException{
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse  response) 
        throws ServletException, IOException {
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String address = request.getParameter("aadress");
    String syKP = request.getParameter("syKP");

    PersonData person = new PersonData(name, address, syKP, email);
    dataLst.addPerson(person);
    //request.setAttribute("name", request.getParameter("name"));
    //request.setAttribute("email", request.getParameter("email"));
    //System.out.println(dataLst.getData().get(0).getNimi());

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    Gson data = new Gson();
    String tmp = data.toJson(dataLst); // won't work if you don't assign it to a string.
    response.getWriter().write(tmp);
    //request.getRequestDispatcher("WEB-INF/views/Login.jsp").forward(request,     response);;
  }

}

为了使用 ajax 提交表单(以避免重新加载页面),我已将您的表单修改为 -

<form  method="post" id="loginForm" enctype="multipart/form-data">

multipart-form-data 有助于以标准方式序列化表单 (HTML5)。现在通过添加 @MultipartConfig 注释使您的 servlet 能够接受 multipart 请求,如下所示 -

@WebServlet(urlPatterns="/login.do")
@MultipartConfig
public class LoginServlet extends HttpServlet{
    // Rest of the code.
}

我们快到了!现在,如果您更喜欢 JavaScript,请将以下函数添加到您的 main.js 以进行 ajax 调用。

function addData(){
  if(window.XMLHttpRequest) { //Assuming you're not on one of the old IEs.
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange=function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            var myArr = JSON.parse(xhttp.responseText);
            //console.log(myArr);
            addToTable(myArr); // function to add data to table.

        }
    }
    xhttp.open("POST","login.do",true);
    var formData = new FormData(document.getElementById('loginForm'));
    xhttp.send(formData);
  }
  else console.log('not working');
}

确保在单击 Add 按钮时调用此函数。

<button type="submit" class="btn btn-info btn-md" onclick="addData();">Add</button>

下面是addToTable函数的一种写法。

function addToTable(data) {
  var dataTable = document.getElementById("tabel");
  for(var i = 0; i<data.pList.length; i++) {
    var row = dataTable.insertRow();
    var tmp = data.pList[i];

    var cell0 = row.insertCell(); //nimi
    var cell1 = row.insertCell(); //aadress
    var cell2 = row.insertCell(); //synd
    var cell3 = row.insertCell(); //email
    var cell4 = row.insertCell(); //muuda
    var cell5 = row.insertCell(); //kustuta

    cell0.innerHTML = tmp.name;
    cell1.innerHTML = tmp.address;
    cell2.innerHTML = tmp.syKP;
    cell3.innerHTML = tmp.email;
    cell4.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-pencil"></span></button>';
    cell5.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-remove-sign"></span></button>';
  }
}

请注意,pListDataList.java 中我存储 PersonDetails 的列表名称。

如果你对table和jQuery感到满意,同样的事情可以如下完成-

$(function() {
  $('button[type=button]').on('click',function() {
    var upForm = $('form').get(0);
    var $form = new FormData(upForm);
    $.ajax({
        url:'login.do', 
        data: $form,
        type: 'POST',
        processData: false,
        contentType: false,
        success: function(responseText) {
            var data = responseText.pList;
            $.each(data, function(index, tmp) {
                var table1 = $('table>tbody').get(0);
                var row = table1.insertRow();
                var cell0 = row.insertCell(); //nimi
                var cell1 = row.insertCell(); //aadress
                var cell2 = row.insertCell(); //synd
                var cell3 = row.insertCell(); //email
                var cell4 = row.insertCell(); //muuda
                var cell5 = row.insertCell(); //kustuta

                cell0.innerHTML = tmp.name;
                cell1.innerHTML = tmp.address;
                cell2.innerHTML = tmp.syKP;
                cell3.innerHTML = tmp.email;
                cell4.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-pencil"></span></button>';
                cell5.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-remove-sign"></span></button>';
            });
            $('#tabel').tablesorter();
        }
    });
  });
})

servlethtml 配置将保持不变。

P.S。我已经删除了代码 jstl 代码,因为我一直很难用 jstl 翻译的代码调整 jQuery 和 bootstrap。

此外,tablesorter 对我来说很好用。虽然我没有实现搜索框,但我认为它不会对 tablesorter.

造成任何问题