非必要不会把框架的每层代码放出来(没什么意义)
准备工作
配置layui参考(转)
https://blog.csdn.net/weixin_43977327/article/details/103016179
查询
后台新建一波文件
先导入可以生成layui可识别json的工具包
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
/***
*
* @author Administrator
*
*/
public class ObjtoLayJson {
public static String toJson(Object object,String[] colums) throws Exception {
String[] dataRow = new String[colums.length];
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
String fistfont = fieldName.substring(0,1).toUpperCase();
String methodname = "get"+fistfont+fieldName.substring(1);
Method method = object.getClass().getMethod(methodname);
if (method.invoke(object) == null) {
dataRow[i] = "null";
}else {
dataRow[i] = method.invoke(object).toString();
}
}
//System.out.println(Arrays.toString(dataRow));
String jsonStr = "[{\"status\":0}, {\"message\": \"success\" }, {\"count\": 1000},{\"rows\":{\"item\":[";
for(int i = 0; i < dataRow.length; i++) {
String arr = "{";
if (dataRow[i] == null || "NULL".equals(dataRow[i]) ) {
arr += "\"\"";
}else {
arr += "\"" + colums[i] + "\""+":" ;
arr += "\"" + dataRow[i]+"\"";
}
arr += "}";
if( i < dataRow.length - 1 ) {
arr += ",";
}
jsonStr += arr;
}
jsonStr += "]}}]";
return jsonStr;
}
public static <T> String ListtoJson(List<T> objects,String[] colums) throws Exception {
String[][] dataRow = new String[objects.size()][colums.length];
int count = 0;
for (Object object : objects) {
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
String fistfont = fieldName.substring(0,1).toUpperCase();
String methodname = "get"+fistfont+fieldName.substring(1);
Method method = object.getClass().getMethod(methodname);
if (method.invoke(object) == null) {
dataRow[count][i] = "null";
}else {
dataRow[count][i] = method.invoke(object).toString();
}
}
count += 1;
}
String jsonStr = "[{\"status\":0}, {\"message\": \"success\" }, {\"count\": 1000},{\"rows\":{\"item\":[";
for(int i = 0; i < dataRow.length; i++) {
String arr = "{";
for( int j = 0; j < dataRow[i].length; j++) {
//System.out.println("j======"+j);
if(dataRow[i][j] == null || "NULL".equals(dataRow[i][j])) {
arr += "\"\"";
}else {
arr += "\"" + colums[j] + "\""+":" ;
arr += "\"" +dataRow[i][j] + "\"";
}
if( j < dataRow[i].length - 1 ) {
arr += ",";
}
}
arr += "}";
if( i < dataRow.length - 1) {
arr += ",";
}
jsonStr += arr;
}
jsonStr += "]}}]";
return jsonStr;
}
public static void main(String[] args) throws Exception {
// User user = new User();
// user.setAge(18);
// user.setId(1);
// user.setPassword("123456789");
// String[] colums = {"id","userName","Password","age"};
String jsonString = toJson(user,colums);
System.out.println(jsonString);
// List
// users.add(user);
// users.add(user);
// String helloString = ListtoJson(users,colums);
// System.out.println(helloString);
}
}
一层一层来
先把实体类写好
@Data代表get set方法(不用自己生成了)
import lombok.Data;
@Data
public class Test {
private int id;
private String acc;
private String pwd;
}
controller
对应好字段名(acc , pwd)
import com.qcby.entity.Test;
import com.qcby.service.TestService;
import com.qcby.util.ObjtoLayJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("test")
public class TestController {
@Autowired
private TestService testService;
@ResponseBody
@RequestMapping(value = "selectAll", method = RequestMethod.GET, produces = "text/json;charset=utf-8")
public String selectAll(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("utf-8");
List<Test> list = testService.selectAll();
String[] column = {"id", "acc", "pwd"};
String data = ObjtoLayJson.ListtoJson(list, column);
return data;
}
}
service接口
import com.qcby.entity.Test;
import java.util.List;
public interface TestService {
List<Test> selectAll();
}
serviceImpl
import com.qcby.dao.TestMapper;
import com.qcby.entity.Test;
import com.qcby.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("TestService")
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public List<Test> selectAll() {
return this.testMapper.selectAll();
}
}
dao层(mapper层)
import com.qcby.entity.Test;
import java.util.List;
public interface TestMapper {
List<Test> selectAll();
}
mapping
<mapper namespace="com.qcby.dao.TestMapper">
<resultMap id="BaseResultMap" type="com.qcby.entity.Test">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="acc" jdbcType="VARCHAR" property="acc"/>
<result column="pwd" jdbcType="VARCHAR" property="pwd"/>
resultMap>
<sql id="Base_Column_List">
id, acc, pwd
sql>
<select id="selectAll" resultMap="BaseResultMap" parameterType="java.lang.Integer">
select
<include refid="Base_Column_List"/>
from t_test
select>
mapper>
后台配置好了就可以开始配置前台了
在前台页面文件中加入下面代码
<head>
<meta charset="utf-8">
<title>title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="../sources/layui/css/layui.css" media="all">
<script src="../sources/layui/layui.js">script>
<script type="text/javascript" src="../sources/js/jquery.js">script>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">script>
head>
<body>
<table class="layui-hide" id="test" lay-filter="test">table>
<script src="../sources/layui/layui.js" charset="utf-8">script>
<script>
layui.use('table', function () {
var table = layui.table
, form = layui.form;
table.render({
elem: '#test'
, url: 'test/selectAll'
, method: "get"
, toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
, defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
, layEvent: 'LAYTABLE_TIPS'
, icon: 'layui-icon-tips'
}]
, title: 'test'
, cols: [
[
{type: 'checkbox', fixed: 'left'}
, {field: 'id', title: 'ID', width: 70, fixed: 'left', unresize: true, sort: true, align: 'center'}
, {field: 'acc', title: '用户名', width: 150, edit: 'text', align: 'center', unresize: true}
, {field: 'pwd', title: '密码', width: 150, edit: 'text', align: 'center', unresize: true}
]
]
, response: {
statusName: 'status'
, dataName: 'rows'
}
, parseData: function (res) {
// console.log(res);
return {
"status": res[0].status,
"message": res[1].message,
"count": 1000,
"rows": res[3].rows.item
};
}
});
});
script>
body>
html>
jsp要在一开始加入
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
url对应selectAll方法
(建议不要[[这样连着写 , 会被什么识别成一个有意义的符号 , 什么来着???忘了…)
我这是id, acc, pwd字段,所以就是三行
测试一下
后台已经查出数据了
前台也自动加载数据了
简单的查询结束
删除&更新
删除是增删改查中最简单的,更新是第二简单的
而且借助layui, 可以直接传一个对象到后台, 非常方便
以下是页面代码
<html>
<head>
<meta charset="utf-8">
<title>title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="../sources/layui/css/layui.css" media="all">
<script src="../sources/layui/layui.js">script>
<script type="text/javascript" src="../sources/js/jquery.js">script>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">script>
head>
<body>
<table class="layui-hide" id="test" lay-filter="test">table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">更新</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
<script src="../sources/layui/layui.js" charset="utf-8">script>
<script>
layui.use('table', function () {
var table = layui.table;
table.render({
elem: '#test'
, url: 'test/selectAll' //改成我们使用的servlet
, method: "get"
, cols: [
[
{type: 'checkbox', fixed: 'left'}
, {field: 'id', title: 'ID', width: 70, fixed: 'left', unresize: true, sort: true, align: 'center'}
, {field: 'acc', title: '用户名', width: 150, edit: 'text', align: 'center', unresize: true, sort: true}
, {field: 'pwd', title: '密码', width: 150, edit: 'text', align: 'center', unresize: true, sort: true}
, {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 120, align: 'center'}
]
]
, response: {
statusName: 'status'
, dataName: 'rows'
}
, parseData: function (res) {
// console.log(res);
return {
"status": res[0].status,
"message": res[1].message,
"count": 1000,
"rows": res[3].rows.item
};
}
});
//让添加框弹出来
table.on('tool(test)', function (obj) {
if (obj.event === 'del') {
layer.confirm('真的删除行么', function (index) {
$.ajax({
type: "get",
url: "test/deleteById",
data: obj.data,
cache: false,
async: true,
success: function () {
layer.msg("删除成功", { icon: 1, offset: "auto", time:2000 });
},
error: function () {
layer.msg("删除失败", { icon: 2, offset: "auto", time:2000 });
}
});
obj.del();
layer.close(index);
});
} else if (obj.event === 'edit') {
$.ajax({
type: "get",
url: "test/update",
data: obj.data,
cache: false,
async: true,
success: function () {
layer.msg("更新成功", { icon: 1, offset: "auto", time:2000 });
},
error: function () {
layer.msg("更新失败", { icon: 2, offset: "auto", time:2000 });
}
});
}
});
});
script>
body>
html>
以下是后台每层部分代码
controller
@ResponseBody
@RequestMapping(value = "deleteById", method = RequestMethod.GET, produces = "text/json;charset=utf-8")
public String deleteById(Test test) {
testService.deleteById(test);
return null;
}
@ResponseBody
@RequestMapping(value = "update", method = RequestMethod.GET, produces = "text/json;charset=utf-8")
public String update(Test test) {
testService.update(test);
return null;
}
service
public interface TestService {
List<Test> selectAll();
int deleteById(Test test);
int update(Test test);
}
Impl
@Service("TestService")
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public List<Test> selectAll() {
return this.testMapper.selectAll();
}
@Override
public int deleteById(Test test) {
return this.testMapper.deleteById(test);
}
@Override
public int update(Test test) {
return this.testMapper.update(test);
}
}
dao层
public interface TestMapper {
List<Test> selectAll();
int deleteById(Test test);
int update(Test test);
}
<delete id="deleteById" parameterType="java.lang.Integer">
delete from t_test
where id = #{id,jdbcType=INTEGER};
delete>
<update id="update" parameterType="com.qcby.entity.Test">
update t_test
set acc = #{acc,jdbcType=VARCHAR},
pwd = #{pwd,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
update>
可以看出删除和更新都是从前台获取一个test对象, 然后从controller一直走到dao层
最后在mapping层执行各自的sql语句
就是layui可以把一行数据打包成后台可识别的对象, 删除和更改才这么简单的
添加
首先加入头部工具栏
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button type="button" class="layui-btn layui-btn-sm" id="add" lay-event="add">添加</button>
</div>
script>
然后是form表单 用来获取输入的值
<form class="layui-form" action="" id="addForm" style="display:none">
<div class="layui-form-item" style="margin-top: 5%">
<label class="layui-form-label">用户名label>
<div class="layui-input-inline">
<input type="text" id="acc" required lay-verify="required" placeholder="请输入用户名" autocomplete="off"
class="layui-input">
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">密码label>
<div class="layui-input-inline">
<input type="text" id="pwd" required lay-verify="required" placeholder="请输入密码" autocomplete="off"
class="layui-input">
div>
div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formDemo" onclick="adds()">提交button>
<button type="reset" class="layui-btn layui-btn-primary">重置button>
div>
div>
form>
然后点击头部工具栏的按钮会执行的方法
(官网还有很多有趣的头部工具)
//头部工具栏
table.on('toolbar(test)', function (obj) {
switch (obj.event) {
case 'add':
layer_index = layer.open({
type: 1, //可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
title: "添加房间", //数组第二项可以写任意css样式;如果你不想显示标题栏,你可以title: false
area: ['400px', '250px'], //所打开页面大小
content: $("#addForm"), //内容
cancel: function () {
layer.close(layer_index);
$("#addForm")[0].reset();
}
});
break;
}
});
最后是打开添加框输入完数据后的添加方法
只是比删除和更改多了获取值一步
function adds() {
var data = {
"acc": $("#acc").val(),
"pwd": $("#pwd").val()
};
$.ajax({
type: "get",
url: "test/insert",
data: data,
cache: false,
async: true,
success: function () {
layer.msg("添加成功", {icon: 1, offset: "auto", time: 2000});
},
error: function () {
layer.msg("添加失败", {icon: 2, offset: "auto", time: 2000});
}
});
}
而后台controller层到dao层和删除更改是基本相同的写法
只是到了mapping层执行insert的sql语句
<insert id="insert" parameterType="com.qcby.entity.Test">
insert into t_test (id, acc, pwd)
values (#{id,jdbcType=INTEGER}, #{acc,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR})
insert>
到这基础的增删改查就完成了
然后看下全部的代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="utf-8">
<title>title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="../sources/layui/css/layui.css" media="all">
<script src="../sources/layui/layui.js">script>
<script type="text/javascript" src="../sources/js/jquery.js">script>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">script>
head>
<body>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button type="button" class="layui-btn layui-btn-sm" id="add" lay-event="add">添加</button>
</div>
script>
<form class="layui-form" action="" id="addForm" style="display:none">
<div class="layui-form-item" style="margin-top: 5%">
<label class="layui-form-label">用户名label>
<div class="layui-input-inline">
<input type="text" id="acc" required lay-verify="required" placeholder="请输入用户名" autocomplete="off"
class="layui-input">
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">密码label>
<div class="layui-input-inline">
<input type="text" id="pwd" required lay-verify="required" placeholder="请输入密码" autocomplete="off"
class="layui-input">
div>
div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formDemo" onclick="adds()">提交button>
<button type="reset" class="layui-btn layui-btn-primary">重置button>
div>
div>
form>
<table class="layui-hide" id="test" lay-filter="test">table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">更新</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
script>
<script src="../sources/layui/layui.js" charset="utf-8">script>
<script>
layui.use('table', function () {
var table = layui.table;
table.render({
elem: '#test'
, url: 'test/selectAll' //改成我们使用的servlet
, method: "get"
, toolbar: '#toolbarDemo'
, cols: [
[
{type: 'checkbox', fixed: 'left'}
, {field: 'id', title: 'ID', width: 70, fixed: 'left', unresize: true, sort: true, align: 'center'}
, {
field: 'acc',
title: '用户名',
width: 150,
edit: 'text',
align: 'center',
unresize: true,
sort: true
}
, {field: 'pwd', title: '密码', width: 150, edit: 'text', align: 'center', unresize: true, sort: true}
, {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 120, align: 'center'}
]
]
, response: {
statusName: 'status'
, dataName: 'rows'
}
, parseData: function (res) {
// console.log(res);
return {
"status": res[0].status,
"message": res[1].message,
"count": 1000,
"rows": res[3].rows.item
};
}
});
//操作栏
table.on('tool(test)', function (obj) {
if (obj.event === 'del') {
//让添加框弹出来
layer.confirm('真的删除行么', function (index) {
$.ajax({
type: "get",
url: "test/deleteById",
data: obj.data,
cache: false,
async: true,
success: function () {
layer.msg("删除成功", {icon: 1, offset: "t", time: 2000});
},
error: function () {
layer.msg("删除失败", {icon: 2, offset: "t", time: 2000});
}
});
obj.del();
layer.close(index);
});
} else if (obj.event === 'edit') {
$.ajax({
type: "get",
url: "test/update",
data: obj.data,
cache: false,
async: true,
success: function () {
layer.msg("更新成功", {icon: 1, offset: "t", time: 2000});
},
error: function () {
layer.msg("更新失败", {icon: 2, offset: "t", time: 2000});
}
});
}
});
//头部工具栏
table.on('toolbar(test)', function (obj) {
switch (obj.event) {
case 'add':
layer_index = layer.open({
type: 1, //可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
title: "添加房间", //数组第二项可以写任意css样式;如果你不想显示标题栏,你可以title: false
area: ['400px', '250px'], //所打开页面大小
content: $("#addForm"), //内容
cancel: function () {
layer.close(layer_index);
$("#addForm")[0].reset();
}
});
break;
}
});
});
function adds() {
var data = {
"acc": $("#acc").val(),
"pwd": $("#pwd").val()
};
$.ajax({
type: "get",
url: "test/insert",
data: data,
cache: false,
async: true,
success: function () {
layer.msg("添加成功", {icon: 1, offset: "auto", time: 2000});
},
error: function () {
layer.msg("添加失败", {icon: 2, offset: "auto", time: 2000});
}
});
}
script>
body>
html>
controller
package com.qcby.controller;
import com.qcby.entity.Test;
import com.qcby.service.TestService;
import com.qcby.util.ObjtoLayJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("test")
public class TestController {
@Autowired
private TestService testService;
@ResponseBody
@RequestMapping(value = "selectAll", method = RequestMethod.GET, produces = "text/json;charset=utf-8")
public String selectAll(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("utf-8");
List<Test> list = testService.selectAll();
String[] column = {"id", "acc", "pwd"};
String data = ObjtoLayJson.ListtoJson(list, column);
return data;
}
@ResponseBody
@RequestMapping(value = "deleteById", method = RequestMethod.GET, produces = "text/json;charset=utf-8")
public String deleteById(Test test) {
testService.deleteById(test);
return null;
}
@ResponseBody
@RequestMapping(value = "update", method = RequestMethod.GET, produces = "text/json;charset=utf-8")
public String update(Test test) {
testService.update(test);
return null;
}
@ResponseBody
@RequestMapping(value="insert",method = RequestMethod.GET,produces = "text/json;charset=utf-8")
public String insert(Test test) {
testService.insert(test);
return null;
}
}
service
package com.qcby.service;
import com.qcby.entity.Test;
import java.util.List;
public interface TestService {
List<Test> selectAll();
int deleteById(Test test);
int update(Test test);
int insert(Test test);
}
serviceImpl
package com.qcby.service.Impl;
import com.qcby.dao.TestMapper;
import com.qcby.entity.Test;
import com.qcby.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("TestService")
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public List<Test> selectAll() {
return this.testMapper.selectAll();
}
@Override
public int deleteById(Test test) {
return this.testMapper.deleteById(test);
}
@Override
public int update(Test test) {
return this.testMapper.update(test);
}
@Override
public int insert(Test test) {
return this.testMapper.insert(test);
}
}
dao层
package com.qcby.dao;
import com.qcby.entity.Test;
import java.util.List;
public interface TestMapper {
List<Test> selectAll();
int deleteById(Test test);
int update(Test test);
int insert(Test test);
}
mapping层
<mapper namespace="com.qcby.dao.TestMapper">
<resultMap id="BaseResultMap" type="com.qcby.entity.Test">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="acc" jdbcType="VARCHAR" property="acc"/>
<result column="pwd" jdbcType="VARCHAR" property="pwd"/>
resultMap>
<sql id="Base_Column_List">
id, acc, pwd
sql>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_test
select>
<delete id="deleteById" parameterType="java.lang.Integer">
delete from t_test
where id = #{id,jdbcType=INTEGER};
delete>
<update id="update" parameterType="com.qcby.entity.Test">
update t_test
set acc = #{acc,jdbcType=VARCHAR},
pwd = #{pwd,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
update>
<insert id="insert" parameterType="com.qcby.entity.Test">
insert into t_test (id, acc, pwd)
values (#{id,jdbcType=INTEGER}, #{acc,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR})
insert>
mapper>
以上为学习期间的学习笔记