给定用户表和六张图书/教师/顾客/仓库....的表(随机给每人抽选),要求实现用户登录注册,异步更新,对物品增删改查,精确/模糊查询等。
tomcat 9
mysql 8
java 17
其实观察一下这六张表就会发现除了主键ID字段为int外,其他都可以为字符串,那么就可以写个通用框架,修改一下和数据库交互的表名和字段名还有一些前端显示文字即可,如下面代码所示,可以很巧妙的避免很多工作量,来实现六张表的切换。
package com.utils;
public class ExamTemp {
public static String id, b, c, d, e;
public static String tid, tb, tc, td, te;
public static String indexTitle,item;
public static String tableName = "course";
public static void switchSys(String tableName2){
if (tableName2.equals("course")) {
tableName = "course";
indexTitle = "课程管理系统";
System.out.println("切换为:"+indexTitle);
item = "课程";
//sql字段
id = "courseno";
b = "coursename";
c = "classhours";
d = "tname";
e = "precourse";
//表头
tid = "课程编号";
tb = "课程名称";
tc = "课时";
td = "任课教师";
te = "先修课程";
} else if (tableName2.equals("part")) {
indexTitle = "零件管理系统";
System.out.println("切换为:"+indexTitle);
tableName = "part";
item = "零件";
//sql字段
id = "PNO";
b = "PNAME";
c = "BRAND";
d = "MODEL";
e = "PRICE";
//表头
tid = "零件编号";
tb = "零件名称";
tc = "品牌";
td = "型号";
te = "价格";
}else if (tableName2.equals("warehouse")) {
indexTitle= "仓库管理系统";
System.out.println("切换为:"+indexTitle);
item = "仓库";
tableName = "warehouse";
//sql字段
id = "WNO";
b = "WNAME";
c = "LOCATION";
d = "SQUARE";
e = "MANAGER";
//表头
tid = "仓库编号";
tb = "仓库名称";
tc = "位置";
td = "面积";
te = "管理员";
}else if (tableName2.equals("book")){
indexTitle = "图书管理系统";
tableName = "book";
System.out.println("切换为:"+indexTitle);
item = "图书";
//sql字段
id = "BNO";
b = "BNAME";
c = "AUTHOR";
d = "PRICE";
e = "PUBLISHER";
//表头
tid = "图书编号";
tb = "图书名称";
tc = "作者";
td = "价格";
te = "出版社";
}else if(tableName2.equals("customer")){
indexTitle = "顾客管理系统";
tableName = "customer";
System.out.println("切换为:"+indexTitle);
item = "客户";
//sql字段
id = "CNO";
b = "CNAME";
c = "SEX";
d = "AGE";
e = "ADDRESS";
//表头
tid = "客户编号";
tb = "客户名称";
tc = "性别";
td = "年龄";
te = "地址";
}else if(tableName2.equals("teacher")){
indexTitle = "教师管理系统";
tableName = "teacher";
System.out.println("切换为:"+indexTitle);
item = "教师";
//sql字段
id = "TNO";
b = "TNAME";
c = "PHONE";
d = "DEPT";
e = "COURSE";
//表头
tid = "教师编号";
tb = "教师名称";
tc = "电话";
td = "部门";
te = "课程";
}
}
}
部分数据库相关代码
用户名输入框失去焦点后向后端发出异步请求来验证用户名是否已存在
var flag = false;
$("#ruser").blur(function(){
var uname = $("#ruser").val();
$.ajax({
url:"/register?action=getUserByUname",
type:"post",
data:{uname:uname},
success:function(msg){//请求成功的回调函数
if(msg == "err"){
flag = false;
$("#namecheck").html("此账号已被注册!!!!");
$("#namecheck").css("color","#e51111");
}else if(msg == "ok"){
flag = true;
$("#namecheck").html("您可以注册√");
$("#namecheck").css("color","#00ff2a");
}
},error:function(){//请求失败的回调函数
console.log("ajax请求失败!!!")
}
});
});
if ("getUserByUname".equals(action)) {
String uname = req.getParameter("uname");
boolean check = userService.getUserByUname(uname);
PrintWriter out = resp.getWriter();
if (check) {
out.write("err");
} else {
out.write("ok");
}
}
使用过滤器,判断Session中是否存在id(登录时会将id存进去),不存在就直接跳回登录页面
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
HttpSession session = httpRequest.getSession(false);
// 检查 session 中是否包含 id
if (session == null || session.getAttribute("uid") == null) {
httpResponse.sendRedirect("../logReg/logreg.html");
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
前端的表名下拉框对比当前项是否与ExamTemp类中的表明对应,相同即为当前系统,设置为默认选中状态
layui按钮事件,异步向后端发送切换请求,成功后重载界面
case 'switchSys':
var system = $("#system").val();
$.ajax({
url: '/SwitchSys',
dataType: 'text',
type: 'post',
data:{"system":system},
success: function (data) {
if (data == "ok") {
layer.msg('切换成功!');
location.reload();
} else {
layer.alert("切换失败!请稍后重试!", {icon: 2});
}
},
error: function () {
layer.alert("切换失败!请稍后重试!", {icon: 2});
}
});
break;
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String system = req.getParameter("system");
ExamTemp.switchSys(system);
tableConfig.init(ExamTemp.tableName,ExamTemp.id);
System.out.println("SwitchSys:" + system);
resp.getWriter().write("ok");
}
前端可参考layui官方文档
// 创建渲染实例
table.render({
elem: '#test',
url: '/GetAllTemp',
method: 'post',
request: {
pageName: "page", // 页码的参数名称,默认:page
limitName: "limit", // 每页数据量的参数名,默认:limit
},
toolbar: '#toolbarDemo',
defaultToolbar: ['filter', 'exports', 'print', {
title: '提示',
layEvent: 'LAYTABLE_TIPS',
icon: 'layui-icon-tips'
}],
height: 'full-35', // 最大高度减去其他容器已占有的高度差
css: [ // 重设当前表格样式
'.layui-table-tool-temp{padding-right: 145px;}'
].join(''),
cellMinWidth: 80,
totalRow: true, // 开启合计行
page: true,
cols: [[
{type: 'checkbox', fixed: 'left'},
{field:'id', fixed: 'left', width:100, title: '<%=ExamTemp.tid%>'},
{field:'b', width:300, title: '<%=ExamTemp.tb%>'},
{field:'c', width:250, title: '<%=ExamTemp.tc%>'},
{field:'d', title:'<%=ExamTemp.td%>', width: 300},
{field:'e', title:'<%=ExamTemp.te%>', width: 300},
{fixed: 'right', title:'操作', width: 134, minWidth: 125, toolbar: '#barDemo'}
]],
后端将从数据库中读取表单,并封装成Json发给前端
int uid = Integer.parseInt(req.getSession().getAttribute("uid").toString());
System.out.println("uid: "+uid);
List allTemplates = ats.getAllTemp();
JsonMassage JSM = new JsonMassage("0", "", allTemplates);
String json = JSM.toJSONString();
System.out.println(json);
resp.getWriter().write(json);
前端监听搜索框的回车事件,使用table,reload进行表格重载,并携带type和搜索文本和获取全部文档区分开,可参考我的另一篇博文。
function EnterKey(event){
event = event || window.event;
if (event.keyCode == 13) {
var value = $("#searchtext").val();
if(!value){
layer.msg('请输入搜索内容');
return elem.focus()
};
// 搜索跳转
layui.table.reload('test', {
where: {
type : '1',
Str : value
},
});
$("#searchtext").focus();
}
}
后端判断是否为纯数字来区分按照id查询还是name查询
String Str = req.getParameter("Str");
List allTemplates = null;
if (Tools.isNumer(Str)) {
allTemplates = ats.getTempsByid(Integer.parseInt(Str));
} else {
allTemplates = ats.getTempByStr(Str);
}
JsonMassage JSM = new JsonMassage("0", "", allTemplates);
String json = JSM.toJSONString();
System.out.println(json);
resp.getWriter().write(json);
layer.open的内容异步请求编辑界面文件‘’editTemp.jsp'返回html,并附带原表格数据。
// 触发单元格工具事件
table.on('tool(test)', function(obj){ // 双击 toolDouble
var data = obj.data; // 获得当前行数据
// console.log(obj)
if(obj.event === 'edit'){ // 编辑数据
layer.open({
type: 1,
area: ['500px', '400px'],
title: '编辑信息',
shade: 0.6,
shadeClose: true,
maxmin: true,
anim: 0,
success: function (layero, index) {
// 使用AJAX加载另一个页面的内容
$.ajax({
url: 'editTemp.jsp',
data:{
"id":data.id,
"b":data.b,
"c":data.c,
"d":data.d,
"e":data.e,
},
dataType: 'html',
success: function (data) {
// 将加载的另一个页面的内容插入到弹层中
layero.find('.layui-layer-content').html(data);
},
error: function () {
layer.msg('加载注册页面失败');
}
});
}
});
编辑界面获取异步请求传回的数据,并且显示在页面里
表单提交事件,将修改的数据交给后端处理
你可能感兴趣的:(项目练习,layui,前端,javascript,web,java)