1. 针对的问题
前端页面为html页面,由于是静态页面,数据的传入传出都必须引入ajax来实现。这里主要实现<button></button>按键触发,调用servlet层的Java代码,完成html页面手动输入数据(输入较多数据)并传向后台。
2. 解决方法
(1) html页面(文件名index.html)
<table class="table table-bordered" style="margin-top: 10px; 99%;" id="pressureDeviceTable"> <thead> <tr> <th>板号</th> <th>CH01</th> <th>CH02</th> <th>CH03</th> <th>CH04</th> <th>CH05</th> <th>CH06</th> <th>CH07</th> <th>CH08</th> <th>CH09</th> <th>CH10</th> <th>CH11</th> <th>CH12</th> <th>CH13</th> <th>CH14</th> <th>CH15</th> <th>CH16</th> </tr> </thead> <tbody> </tbody> </table> <button class="chose_cancle">取消</button> <button class="chose_enter" type="button" id="fun" onclick="fun();" >保存</button> <script type="text/javascript"> function fun(){ var PreList = []; for(var i=0;i<1;i++){ for(var k=0;k<16;k++){ var text = document.getElementsByName("pDB"+(i+1)+"CH"+(k+1)+"")[0].value; if(text!=false){ PreList = PreList.concat(text); } } } $.ajax({ url : "http://localhost:8080/tianjin-ssms-meach/Pre_devServlet?pDBCH="+PreList+"", type : "post", }); } </script>
静态页面的添加方法:在<button></button>中添加type属性为button,因其本身默认为submit属性;再添加onclick,后面为函数命名,再添加JS的function函数,实现想要实现的功能。再添加ajax,添加url地址,(本文件servlet层命名为Pre_devServlet.java)
注意:要想将前台获取到的数据传入servlet层,单纯的调用servlet文件是实现不了的,必须添加你获取到的值,我的数据组为PreList,因此表现出来为
url : "http://localhost:8080/xxx(工程文件名)/Pre_devServlet?pDBCH="+PreList+"",
3. servlet层接收数据
package com.bjut.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Pre_devServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //获取请求方法 this.doPost(request, response); } //doPost 客户端将数据传送至服务器 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String name=null; name = request.getParameter("pDBCH"); System.out.println(name); } }
通过dopost实现:里面主要用到函数getParameter("html页面<input>中的name属性");
在web.xml中加入servlet作为路径指引
<servlet>
<servlet-name>Pre_devServlet</servlet-name>
<servlet-class>com.bjut.servlet.Pre_devServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Pre_devServlet</servlet-name>
<url-pattern>/Pre_devServlet</url-pattern>
</servlet-mapping>
4. 结果展示
前台界面输入:
后台servlet层接收: