自己写的一个简单项目 注释写的很详细,主要是表格的CURD操作,文章结尾放了项目源码,有兴趣的朋友可以下载
功能介绍:
登录功能:启动服务器跳转到登录界面,用户输入正确的账号密码登录到主页面,为避免未登录的用户通过直接访问html文件进入主页面,设置了拦截器进行拦截,提高了项目的安全性。
主页功能:一些常用的操作,如关闭当前页面,退出登录,修改密码等。
表格功能:表格页面是主页面的子页面,主要是对表格的增删查改操作。
1. Html页面
index.jsp
<jsp:forward page="page/login-1.html"></jsp:forward>
登录界面
<script>
layui.use(['form'], function () {
var form = layui.form,
layer = layui.layer;
$(document).ready(function(){
$('.layui-container').particleground({
dotColor:'#7ec7fd',
lineColor:'#7ec7fd'
});
});
$("#btn").click(function () {
if ($("#captcha").val()!="xszg")
{
alert("验证码错误")
return ;
}
$.ajax(
{
url: "http://localhost:8888/login",
type: "GET",
dataType: "json",
data:$("#form").serialize(),
success: function (data) {
if (data.codes=="1")
{
window.location.href="page/MainInterface.html"
}
else
{
alert("账户或密码错误")
}
}
})
return false;
})
})
</script>
主页面
<script>
layui.use(['jquery', 'layer', 'miniAdmin','miniTongji'], function () {
var $ = layui.jquery,
layer = layui.layer,
miniAdmin = layui.miniAdmin,
miniTongji = layui.miniTongji;
var options = {
iniUrl: "../api/init.json",
clearUrl: "../api/clear.json",
urlHashLocation: true,
bgColorDefault: false,
multiModule: true,
menuChildOpen: false,
loadingTime: 0,
pageAnim: true,
maxTabNum: 20,
};
miniAdmin.render(options);
miniTongji.render({
specific: true,
domains: [
'99php.cn',
'layuimini.99php.cn',
'layuimini-onepage.99php.cn',
],
});
$('.login-out').on("click", function () {
layer.msg('退出登录成功', function () {
$.ajax(
{
url: "http://localhost:8888/exitLogin",
type: "GET",
dataType: "text",
success:function (data) {
if (data=="OK")
{
window.location.href="login-1.html";
}
}
}
)
});
});
});
</script>
表格界面
<script>
$(function () {
$.ajax(
{
url: "http://localhost:8888/searchList",
type: "GET",
dataType: "json",
success: function (data) {
var d=data;
layui.use(['form', 'table'], function () {
var $ = layui.jquery,
form = layui.form,
table = layui.table;
table.render({
elem: '#currentTableId',
data:d,
toolbar: '#toolbarDemo',
defaultToolbar: ['filter', 'exports', 'print', {
title: '提示',
layEvent: 'LAYTABLE_TIPS',
icon: 'layui-icon-tips'
}],
cols: [[
{type: "checkbox", width: 50},
{field: 'id', width: 80, title: 'ID', sort: true},
{field: 'name', width: 80, title: '用户名'},
{field: 'sex', width: 80, title: '性别', sort: true},
{field: 'city', width: 80, title: '城市'},
{field: 'job', width: 80, title: '职业'},
{title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"},
]],
limits: [10, 15, 20, 25, 50, 100],
limit: 15,
page: true,
skin: 'line',
parseData:function (d) {
return {
"code": 0,
"msg": "",
"count": 100,
"data": d
}
}
});
form.on('submit(data-search-btn)', function (data) {
var result = JSON.stringify(data.field);
if ($("#name").val()==""&&
$("#sex").val()==""&&
$("#job").val()==""&&
$("#city").val()=="")
{
table.reload('currentTableId', {
url: "http://localhost:8888/searchList",
page: {
curr: 1
}
, where: {
}
}, 'data');
return false;
}
else
{
table.reload('currentTableId', {
url: "http://localhost:8888/searchKey",
page: {
curr: 1
}
, where: {
Key: result
}
}, 'data');
return false;
}
});
table.on('checkbox(currentTableFilter)', function (obj) {
});
table.on('toolbar(currentTableFilter)', function (obj) {
if (obj.event === 'add') {
var index = layer.open({
title: '添加用户',
type: 2,
shade: 0.2,
maxmin:true,
shadeClose: true,
area: ['100%', '100%'],
content: '../page/table/add.html',
success:function (layero, index) {
}
});
$(window).on("resize", function () {
layer.full(index);
});
} else if (obj.event === 'delete') {
var checkStatus = table.checkStatus('currentTableId');
var result= JSON.stringify(checkStatus.data)
layer.close(index);
table.reload('currentTableId', {
url: "http://localhost:8888/deleteCustomer",
page: {
curr: 1
}
, where: {
trData: result
}
}, 'data');
return false;
}
else if (obj.event === 'save')
{
$(".layui-table").find('td').data('edit', false);
var checkStatus = table.checkStatus('currentTableId');
var result= JSON.stringify(checkStatus.data)
table.reload('currentTableId', {
url: "http://localhost:8888/updateCustomer",
page: {
curr: 1
}
, where: {
Key: result
}
}, 'data');
return false;
}
});
table.on('tool(currentTableFilter)', function (obj) {
var data = obj.data;
if (obj.event === 'edit') {
$(".layui-table").find('td').data('edit', true);
} else if (obj.event === 'delete') {
layer.confirm('确定删除该用户吗', function (index) {
var checkStatus = table.checkStatus('currentTableId');
var result= JSON.stringify(checkStatus.data)
layer.close(index);
table.reload('currentTableId', {
url: "http://localhost:8888/deleteCustomer",
page: {
curr: 1
}
, where: {
trData: result
}
}, 'data');
return false;
});
}
});
})
}}
)
})
</script>
修改密码页面
<script>
layui.use(['form','miniTab'], function () {
var form = layui.form,
layer = layui.layer,
miniTab = layui.miniTab;
$ = layui.$;
form.on('submit(saveBtn)', function (data) {
var result=JSON.stringify(data.field);
var object=JSON.parse(result);
if (object.new_password!=object.again_password)
{
alert("两次输入的密码不一致,请仔细核对");
return false;
}
var index = layer.confirm("确定修改密码吗?", {
title: '提示'
}, function () {
layer.close(index);
$.ajax(
{
url:"http://localhost:8888/updateUserPassword",
type:"get",
dataType:"text",
data:{formKey:result},
success:function (data) {
if (data=="OK")
{
alert("修改成功")
miniTab.deleteCurrentByIframe();
}
else if (data=="ERROR")
{
alert("修改失败");
location.reload();
}
}
}
)
return false;
});
return false;
});
});
</script>
添加页面
<script>
layui.use(['form'], function () {
var form = layui.form,
layer = layui.layer,
$ = layui.$;
form.on('submit(saveBtn)', function (data) {
var result=JSON.stringify(data.field)
var index = layer.confirm("确定添加该用户吗?", {
title: '提示'
}, function () {
layer.close(index);
var iframeIndex = parent.layer.getFrameIndex(window.name);
parent.layer.close(iframeIndex);
$.ajax(
{
url:"http://localhost:8888/addCustomer",
type:"get",
dataType:"text",
data:{formKey:result},
success:function (data) {
if (data=="OK")
{
parent.location.reload();
}
else
{
alert("添加失败")
}
}
}
)
return false;
});
return false;
});
});
</script>
404页面
<script>
function randomNum() {
return Math.floor(Math.random() * 9) + 1;
}
var loop1, loop2, loop3, time = 30, i = 0, number;
loop3 = setInterval(function () {
if (i > 40) {
clearInterval(loop3);
document.querySelector('.thirdDigit').textContent = 4;
} else {
document.querySelector('.thirdDigit').textContent = randomNum();
i++;
}
}, time);
loop2 = setInterval(function () {
if (i > 80) {
clearInterval(loop2);
document.querySelector('.secondDigit').textContent = 0;
} else {
document.querySelector('.secondDigit').textContent = randomNum();
i++;
}
}, time);
loop1 = setInterval(function () {
if (i > 100) {
clearInterval(loop1);
document.querySelector('.firstDigit').textContent = 4;
} else {
document.querySelector('.firstDigit').textContent = randomNum();
i++;
}
}, time);
</script>
2.Control层
package Control;
import Service.CustomerService;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.xerces.internal.xs.XSAttributeUse;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import po.Customer;
import po.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Key;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class CustomerControl {
@Autowired
private CustomerService customerService;
Gson gson=new Gson();
@GetMapping(value = "/login")
public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
String username=request.getParameter("username");
String password=request.getParameter("password");
Map <String,String> map=new HashMap<String, String>();
User user=customerService.findUser(username,password);
map.put("codes","0");
if (user!=null)
{
request.getSession().setAttribute("user_information",user);
map.put("codes","1");
response.getWriter().write(gson.toJson(map));
return;
}
response.getWriter().write(gson.toJson(map));
}
@RequestMapping("/searchList")
public void searchList(HttpServletResponse response) throws IOException {
List<Customer> list=customerService.findCustomerAll();
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(gson.toJson(list));
}
@RequestMapping("/searchKey")
public void searchKey(HttpServletResponse response,HttpServletRequest request) throws IOException {
String key=request.getParameter("Key");
JsonObject object=gson.fromJson(key,JsonObject.class);
for (String keys:object.keySet()
) {
if (!(object.get(keys).getAsString().equals("")))
{
key=object.get(keys).getAsString();
}
}
List<Customer> list=customerService.findCustomerByKey(key);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(gson.toJson(list));
}
@RequestMapping(value = "/deleteCustomer")
public void delete(HttpServletResponse response, HttpServletRequest request) throws IOException {
String Key=request.getParameter("trData");
int i=0;
JsonArray array=gson.fromJson(Key,JsonArray.class);
for (int index=0;index<array.size();index++)
{
Key=array.get(index).getAsJsonObject().get("id").getAsString();
i= customerService.deleteCustomer(Key);
}
List<Customer> list=customerService.findCustomerAll();
if (i>=1)
response.getWriter().write(gson.toJson(list));
}
@RequestMapping(value = "/addCustomer")
public void add(HttpServletRequest request,HttpServletResponse response) throws IOException {
String formValue=request.getParameter("formKey");
Customer customer=gson.fromJson(formValue,Customer.class);
int i=customerService.insertCustomer(customer);
if (i>=1)
response.getWriter().write("OK");
else
response.getWriter().write("Error");
}
@RequestMapping(value = "/updateCustomer")
public void updateCustomer(HttpServletRequest request,HttpServletResponse response) throws IOException {
int i=0;
String jsonStr;
String json=request.getParameter("Key");
Customer customer;
JsonArray array=gson.fromJson(json,JsonArray.class);
for (int index=0;index<array.size();index++)
{
jsonStr=array.get(index).getAsJsonObject().toString();
customer=gson.fromJson(jsonStr,Customer.class);
i=customerService.updateCustomer(customer);
}
List<Customer> list=customerService.findCustomerAll();
if (i>=1)
response.getWriter().write(gson.toJson(list));
}
@RequestMapping(value ="/updateUserPassword" )
public void updateUserPassword(HttpServletRequest request,HttpServletResponse response) throws IOException {
String json=request.getParameter("formKey");
int i=0;
User user= (User) request.getSession().getAttribute("user_information");
JsonObject object=gson.fromJson(json,JsonObject.class);
i= customerService.updateUserPassword(user.getUserid(),object.get("old_password").getAsString(),object.get("new_password").getAsString());
if (i>=1)
response.getWriter().write("OK");
else
response.getWriter().write("ERROR");
}
@RequestMapping(value = "/exitLogin")
public void exit(HttpServletRequest request,HttpServletResponse response) throws IOException {
request.getSession().invalidate();
response.getWriter().write("OK");
}
}
3.登录拦截器
package interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String url=httpServletRequest.getRequestURI();
if (url.indexOf("MainInterface.html")>=0)
{
if (httpServletRequest.getSession().getAttribute("user_information")==null)
{
return false;
}
}
return true;
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
4.源码下载链接 https://pan.baidu.com/s/1wMQLtDpGjSaPRZyflww1uA 提取码:xszg
|