最终效果,如图所示:
如果想要进行修改操作,可点击某栏修改选项,会在本表格下方弹出修改的具体操作界面(点击前隐藏),并且目前的信息可复现在修改框内。
本篇文章通过该项目将后端和前端结合起来,实现了对数据库的调用,和对数据库的查找,添加,删除,修改。
首先我们应该准备一个简单的前端界面,其中通过$.ajax({})部分完成和后端的交互。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>库存商品管理系统</title>
<script src="js/jquery.js"></script>
<script>$(function(){$.ajax({url:"goodsServlet",type:"get", //请求方式 get postsuccess:function(value){$("tbody").empty()console.log(value)console.log(value.data)var arr=value.datafor(var i=0;i<arr.length;i++){$("tbody").append("<tr>"+"<td>"+arr[i].g_name+"</td>"+"<td>"+arr[i].g_num+"</td>"+"<td>"+arr[i].g_price+"</td>"+"<td><input type='button' value='修改' class='update' id='body' index='"+arr[i].g_name+"'><input type='button' value='删除' class='delete' id='body' index='"+arr[i].g_name+"'></td>"+"</tr>")}},error:function(){alert("出错啦")},})$("tbody").on("click",".delete",function(){var g_name =$(this).attr("index")$.ajax({ url: 'deleteServlet', // 替换为你的后端处理URL type: 'post', // 请求类型post 做修改常用 data: { g_name }, success: function(value) { // 请求成功时执行的代码 alert(value)//页面刷新location.reload()}, error: function() { // 请求失败时执行的代码 alert("出错啦") }, })})$("#btn").on("click",function(){$(".add_model").css("display","block")})$("#close").on("click",function(){$(".add_model").css("display","none")})$("#u_close").on("click",function(){$(".update_model").css("display","none")})//添加$("#add").on("click",function(){//获取框里的值var name=$(".name").val()var number=$(".num").val()var price=$(".price").val()$.ajax({ url: 'addServlet', // 替换为你的后端处理URL type: 'post', // 请求类型post 做修改常用 data: { name,number,price}, success: function(value) { // 请求成功时执行的代码 alert(value)//页面刷新location.reload()}, error: function() { // 请求失败时执行的代码 alert("出错啦") }, })})$("tbody").on("click",".update",function(){$(".add_model").css("display","none")$(".update_model").css("display","block")var u_name=$(this).attr("index")$.ajax({ url: 'searchidServlet', // 替换为你的后端处理URL type: 'get', // 请求类型post 做修改常用 data: { u_name}, success: function(value) { // 请求成功时执行的代码 var obj=value.data[0]console.log(obj)$(".u_name").val(obj.g_name);$(".u_num").val(obj.g_num);$(".u_price").val(obj.g_price);$("#update").attr("index",obj.g_name)//页面刷新}, error: function() { // 请求失败时执行的代码 alert("出错啦") }, })})$("#update").on("click",function(){var u_name=$(".u_name").val()var u_number=$(".u_num").val()var u_price=$(".u_price").val()var id=$(this).attr("index")alert(id)$.ajax({ url: 'updateServlet', // 替换为你的后端处理URL type: 'post', // 请求类型post 做修改常用 data: { u_name,u_number,u_price,id}, success: function(value) { // 请求成功时执行的代码 alert(value)//页面刷新location.reload()}, error: function() { // 请求失败时执行的代码 alert("出错啦") }, })})})</script>
<style>*{padding: 0;margin: 0;}.container{width: 10%;min-width: 350px;margin: 150px auto;}table{border-collapse: collapse;margin: 5px auto;width: 80%;}thead{background: rgb(57, 151, 180);border: 2px rgb(14, 77, 160) solid;}table tbody tr:nth-child(odd){background: rgb(192, 230, 244);border: 2px rgb(14, 77, 160) solid;}table tbody tr:nth-child(even){background: rgb(197, 209, 225);border: 2px rgb(14, 77, 160) solid;}table tbody #body{margin:3px;}table tbody #body:nth-child(1){background: rgb(230, 233, 167);}table tbody #body:nth-child(2){background: rgb(227, 182, 223);}.add_model{border: 2px rgb(14, 77, 160) solid;padding:15px;font-weight: 500;margin: 50px ;display:none}.update_model{border: 2px rgb(14, 87, 160) solid;padding:15px;font-weight: 500;margin: 50px ;display:none}</style>
</head>
<body>
<div class="container"><span>商品名称:<input type="text" id="userInput"><input type="button" value="查找" class="title" id="search"><input type="button" value="添加" class="title" id="btn"></span><table border="1"><thead><tr><th>商品名称</th><th>数量</th><th>价格</th><th>操作</th></tr></thead><tbody></tbody></table><h4 class="add_model"><span class="bottom">添加商品</span><br><span>商品名称:<input type="text" class="name"></span><br><span>商品数量:<input type="text" class="num"></span><br><span>商品价格:<input type="text" class="price"></span><input type="button" value="添加商品" class="title" id="add"><input type="button" value="取消" class="title" id="close"></h4><h4 class="update_model"><span class="bottom">修改</span><br><span>商品名称:<input type="text" class="u_name"></span><br><span>商品数量:<input type="text" class="u_num"></span><br><span>商品价格:<input type="text" class="u_price"></span><input type="button" value="修改" class="title" id="update"><input type="button" value="取消" class="title" id="u_close"></h4></div></body>
</html>
1.goodsServlet.java
构建servlet文件,在doGet方法做如下操作。该文件用来调用数据库中初始表格。其中 MysqlUtil.getJsonBySql方法为自建包MysqlUtil中的方法将所调出来的数据转化为Json格式
package com.qcby.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import datab.MysqlUtil;@WebServlet("/goodsServlet")
public class goodsServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public goodsServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//解决中文乱码request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//设置后端给前端返回的数据为json格式(大量数据)response.setContentType("text/json;charset=utf-8");//接收参数//查找String sql="SELECT * from goods";String[] colums= {"g_name","g_num","g_price"};String res=MysqlUtil.getJsonBySql(sql, colums);//后端给前端返回数据response.getWriter().write(res);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
2.deleteServlet.java
该文件用来实现删除功能。同样的 MysqlUtil.del方法为自建包MysqlUtil中的方法,用于执行删除语句(当然也可以自己写),这个方法会返回一个int型 即修改的行数,这个数可以判断删除操作是否成功执行。
package com.qcby.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import datab.MysqlUtil;/*** Servlet implementation class deleteServlet*/
@WebServlet("/deleteServlet")
public class deleteServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public deleteServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");System.out.println("post");String g_name=request.getParameter("g_name");String sql="DELETE FROM goods WHERE g_name='"+g_name+"'";int num=MysqlUtil.del(sql);String res="删除失败";if(num>0) {res="删除成功";}response.getWriter().write(res); }}
3.searchidServlet.java & updateServlet.java
要实现在修改时弹框的复现功能,就需要接受data域所传参数,并进行展示,在此插入searchidServlet.java,如下所示,本文件配合前端jQuery方法用于获取在 update操作中所需要复现的内容
package com.qcby.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import datab.MysqlUtil;/*** Servlet implementation class searchidServlet*/
@WebServlet("/searchidServlet")
public class searchidServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public searchidServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//解决中文乱码request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//设置后端给前端返回的数据为json格式(大量数据)response.setContentType("text/json;charset=utf-8");String u_name=request.getParameter("u_name");String sql="SELECT * FROM goods WHERE g_name=\""+u_name+"\"";String[] colums= {"g_name","g_num","g_price"};String res=MysqlUtil.getJsonBySql(sql, colums);response.getWriter().write(res);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
package com.qcby.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import datab.MysqlUtil;/*** Servlet implementation class updateServlet*/
@WebServlet("/updateServlet")
public class updateServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public updateServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//解决中文乱码request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//接收参数String name=request.getParameter("u_name");String number=request.getParameter("u_number");String price=request.getParameter("u_price");String id=request.getParameter("id");//修改String sql="UPDATE goods SET g_name=\""+name+"\",g_num="+number+",g_price="+price+" WHERE g_name=\""+id+"\"";int num=MysqlUtil.update(sql);String res="修改失败";if(num>0) {res="修改成功";}response.getWriter().write(res); }}