前言
thymeleaf和freemarker比较,个人更倾向于freemarker这种模板引擎,两者的设计思路本就不同。
springboot整合freemarker
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
配置application.yml
spring:
freemarker:
suffix: .ftl
template-loader-path: classpath:/templates
datasource:
url: jdbc:mysql://88.88.88.194:3306/master1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
server:
port: 8080
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.orm.mybatis.freemarker.entity
configuration:
map-underscore-to-camel-case: true
Spring boot2.0访问静态资源就会被同步拦截。
需要创建一个类名为AWebMvcConfigurer 继承WebMvcConfigurer
我们使用的Springboot本身把静态资源目录设置为"/",所以我们访问静态资源时是不需要加上/static的,因此在放行拦截的使用不能使用/static/**.因此我在/下创建目录res放入我全部的静态资源,并以此目录放行。
//配置拦截事件
@Configuration
public class AWebMvcConfigurer implements WebMvcConfigurer {
// 静态资源映射,保证资源的正确访问
// 重写上述方法可以达到拦截器的效果,但是在使用FreeMarker时有时会导致不能加载css、js文件。
// 在上述创建类中重写
// 这时我们需要重写映射文件类即public void addResourceHandlers(ResourceHandlerRegistry registry) 类
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/res/**")
.addResourceLocations("classpath:/res/");
registry.addResourceHandler("/templates/**")
.addResourceLocations("classpath:/templates/");
}
}
三个页面
index.ftl 页面
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../res/bootstrap-4.5.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../res/font-awesome-4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Home Page</h2>
</div>
<a href="showUsers">Show User (Retrieve employee data from database)</a>
<p></p>
<a href="table">Show User CRUD</a>
</div>
</div>
</body>
</html>
showUsers.ftl
<!DOCTYPE html>
<html>
<head>
<title>Employee List</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../res/jquery-3.5.1.min.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>User List</h2>
</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Num</th>
<th>Name</th>
<th>Address</th>
<th>Abc</th>
</tr>
</thead>
<tbody>
<#list userList as user>
<tr>
<td>${user.id}</td>
<td>${user.num}</td>
<td>${user.name}</td>
<td>${user.address!"null"}</td>
<td>${user.ABC!"null"}</td>
</tr>
</#list>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
table.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数据表格</title>
<link rel="stylesheet" href="../res/bootstrap-4.5.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../res/font-awesome-4.7.0/css/font-awesome.min.css">
<script src="../res/jquery-3.5.1.min.js"></script>
<script src="../res/popper.min.js"></script>
<script src="../res/bootstrap-4.5.0-dist/js/bootstrap.min.js"></script>
<script src="../res/layer/layer.js"></script>
<style>
.form-text {
width: 100px;
text-align: center;
}
</style>
</head>
<body>
<button type="button" class="btn btn-primary" id="btn_add"><i class="fa fa-plus-square" aria-hidden="true"></i> 添加
</button>
<button type="button" class="btn btn-primary" id="btn_del"><i class="fa fa-trash" aria-hidden="true"></i> 删除
</button>
<button type="button" class="btn btn-primary" id="btn_edit"><i class="fa fa-pencil-square" aria-hidden="true"></i> 修改
</button>
<button type="button" class="btn btn-primary" id="btn_info"><i class="fa fa-info-circle" aria-hidden="true"></i> 查看
</button>
<table class="table table-hover table-bordered">
<thead class="thead-light">
<tr align="center">
<th><input type="checkbox" id="isAll"></th>
<#-- <th>Id</th>-->
<th>Num</th>
<th>Name</th>
<th>Address</th>
<th>Abc</th>
</tr>
</thead>
<tbody>
<#list userList as user>
<tr align="center">
<td><input type="checkbox" name="id" class="form-check" value="${user.id}"></td>
<td>${user.num!"null"}</td>
<td>${user.name!"null"}</td>
<td>${user.address!"null"}</td>
<td>${user.ABC!"null"}</td>
</tr>
</#list>
<div class="form-group" style="margin-top: 10px;margin-left: 20px">
<label for="num">id</label>
<input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_id" type="text" placeholder=""
name="num"
value=""
autocomplete="off">
<label for="num">num</label>
<input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_num" type="text" placeholder=""
name="num"
value=""
autocomplete="off">
<label for="name">Name</label>
<input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_name" type="text" placeholder=""
name="name"
value="" autocomplete="off">
<label for="address">address</label>
<input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_address" type="text" placeholder=""
name="address"
value="" autocomplete="off">
<label for="aBC">abc</label>
<input style="display: initial;width: 15%" class="form-control form-edit" id="andrew_aBC" type="text" placeholder=""
name="aBC"
value="" autocomplete="off">
<button class="btn btn-primary" id="btn_andrew" style="margin-bottom: 5px">确认修改</button>
</div>
</tbody>
</table>
<!-- 新增员工模态框 -->
<div id="addModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-title">
<h1 class="text-center">用户信息</h1>
</div>
<div class="modal-body">
<form class="form-group" action="">
<div class="form-group">
<label for="num">num</label>
<input class="form-control form-add" id="num" type="text" placeholder="" name="num"
value=""
autocomplete="off">
</div>
<div class="form-group">
<label for="name">name</label>
<input class="form-control form-add" id="name" type="text" placeholder="" name="name"
value="" autocomplete="off">
</div>
<div class="form-group">
<label for="address">address</label>
<input class="form-control form-add" id="address" type="text" placeholder="" name="address"
value="" autocomplete="off">
</div>
<div class="form-group">
<label for="aBC">abc</label>
<input class="form-control form-add" id="aBC" type="text" placeholder="" name="aBC"
value="" autocomplete="off">
</div>
<div class="text-right">
<button class="btn btn-primary" id="add_submit" type="submit">提交</button>
<button class="btn btn-danger" data-dismiss="modal">取消</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- 员工信息模态框 -->
<div id="infoModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-title">
<h1 class="text-center">用户信息</h1>
</div>
<div class="modal-body">
<form class="form-group" action="">
<div class="form-group">
<label for="num">num</label>
<input class="form-control form-edit" id="info_num" readonly type="text" placeholder=""
name="num"
value=""
autocomplete="off">
</div>
<div class="form-group">
<label for="num">Name</label>
<input class="form-control form-edit" id="info_name" readonly type="text" placeholder=""
name="name"
value="" autocomplete="off">
</div>
<div class="form-group">
<label for="address">address</label>
<input class="form-control form-edit" id="info_address" readonly type="text" placeholder=""
name="address"
value="" autocomplete="off">
</div>
<div class="form-group">
<label for="aBC">abc</label>
<input class="form-control form-edit" id="info_aBC" readonly type="text" placeholder=""
name="aBC"
value="" autocomplete="off">
</div>
<div class="text-right">
<button class="btn btn-danger" data-dismiss="modal">关闭</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
$(function (e) {
$('#addModal').on('show.bs.modal', function (e) {
var $this = $(this);
var $modal_dialog = $this.find('.modal-dialog');
$this.css('display', 'block');
$modal_dialog.css({'margin-top': Math.max(0, ($(window).height() - $modal_dialog.height()) / 2 - 30)});
});
var addOrSave = true;
$('#btn_add').on('click', function (e) {
e.preventDefault();
addOrSave = true;
$("#addModal").modal({backdrop: true, keyboard: true});
});
$('#add_submit').on('click', function (e) {
e.preventDefault();
let data = {};
let forms = $('.form-add');
$.each(forms, function(index, input){
data[input.name] = input.value;
});
// data.test = ["3","5",{"a":"asd"}];
if(!addOrSave){
let list = sessionStorage.getItem('ids');
data['ids'] = JSON.parse(list);
}
window.console.log(data);
let methodName = addOrSave ? 'add' : 'edit';
$.ajax({
method: "post",
url: '/user/' + methodName,
async: false,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (respose) {
switch (respose.code) {
case "200": {
window.location.replace("/user/table");
break;
}
}
}
});
});
$('#btn_andrew').on('click', function (e) {
e.preventDefault();
let data = {};
let list = [];
// data[input.name] = input.value;
// data.test = ["3","5",{"a":"asd"}];
if ($('#andrew_id')[0].value){
console.log("1")
addOrSave = false;
}else {
console.log("2")
addOrSave = true;
}
list.push($('#andrew_id')[0].value)
data.ids = [...list];
data.num = $('#andrew_num')[0].value;
data.name = $('#andrew_name')[0].value;
data.address = $('#andrew_address')[0].value;
data.aBC = $('#andrew_aBC')[0].value;
window.console.log(data);
let methodName = addOrSave ? 'add' : 'edit';
$.ajax({
method: "post",
url: '/user/' + methodName,
async: false,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (respose) {
switch (respose.code) {
case "200": {
window.location.replace("/user/table");
break;
}
}
}
});
});
$('#isAll').change(function (e) {
if ($('#isAll').is(':checked')) {
$('.form-check').each(function (index, element) {
if (!element.checked) {
element.checked = true;
}
});
} else {
$('.form-check').each(function (index, element) {
if (element.checked) {
element.checked = false;
}
});
}
});
$('.form-check').click(function (e) {
e.preventDefault();
});
$('tr').slice(1).click(function (e) {
// let checkbox = $("input[type='checkbox']",this)[0];
let checkbox = $("input:checkbox", this)[0];
if (checkbox.checked) {
checkbox.checked = false;
} else {
checkbox.checked = true;
}
check($('.form-check'));
})
function check(items) {
let flag = true;
$(items).each(function (index, element) {
if (!element.checked) {
flag = false;
}
});
let isAll = window.document.querySelector(`#isAll`)
isAll.checked = flag;
}
$('#btn_del').click(function (e) {
e.preventDefault();
let list = new Array();
$('.form-check').each(function (index, element) {
if (element.checked) {
list.push(element.value);
}
});
if (list.length > 0) {
$.ajax({
method: "post",
url: '/user/delete',
async: false,
data: JSON.stringify({"ids": JSON.parse(JSON.stringify(list))}),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (respose) {
switch (respose.code) {
case "200": {
window.location.replace("/user/table");
break;
}
}
}
});
} else {
layer.msg('请选择要删除的员工', {icon: 2});
}
});
$('#btn_info').click(function (e) {
e.preventDefault();
let list = new Array();
$('.form-check').each(function (index, element) {
if (element.checked) {
list.push(element.value);
}
});
if (list.length > 0) {
$.ajax({
method: "post",
url: '/user/getUserById',
async: false,
data: JSON.stringify({"ids":[...list]}),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (respose) {
console.log(respose.code);
switch (respose.code) {
case "200": {
$("#infoModal").modal({backdrop: true, keyboard: true});
$('#info_num').val(respose.data.num);
$('#info_address').val(respose.data.address);
$('#info_aBC').val(respose.data.aBC);
$('#info_name').val(respose.data.name);
break;
}
}
}
});
} else {
layer.msg('请选择要查看的员工', {icon: 2});
}
});
$('#btn_edit').click(function(e){
e.preventDefault();
addOrSave = false;
let list = new Array();
$('.form-check').each(function (index, element) {
if (element.checked) {
list.push(element.value);
}
});
sessionStorage.setItem('ids',JSON.stringify(list));
if (list.length > 0) {
$.ajax({
method: "post",
url: '/user/getUserById',
async: false,
data: JSON.stringify({'ids':JSON.parse(JSON.stringify(list))}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (respose) {
console.log(respose.code);
switch (respose.code) {
case "200": {
$("#addModal").modal({backdrop: true, keyboard: true});
$('#num').val(respose.data.num);
$('#address').val(respose.data.address);
$('#aBC').val(respose.data.aBC);
$('#name').val(respose.data.name);
break;
}
}
}
});
} else {
layer.msg('请选择要查看的员工', {icon: 2});
}
});
});
</script>
控制层
/**
* (User)表控制层
*
* @author makejava
* @since 2022-03-11 09:53:09
*/
@Controller
@RequestMapping("user")
public class UserController {
/**
* 服务对象
*/
@Resource
private UserServiceImpl userService;
@GetMapping("/")
public String index(Model model) {
return "index";
}
@GetMapping("/test")
public String test(Model model) {
return "index";
}
@GetMapping("/showUsers")
public ModelAndView showCities() {
List<User> userList = userService.queryAll();
Map<String, Object> params = new HashMap<>();
System.out.println(userList.toString());
params.put("userList", userList);
return new ModelAndView("showUsers", params);
}
@GetMapping("/table")
public ModelAndView showUser() {
List<User> userList = userService.queryAll();
Map<String, Object> params = new HashMap<>();
System.out.println(userList.toString());
params.put("userList", userList);
return new ModelAndView("table", params);
}
@ResponseBody
@PostMapping(value = "/getUserById",produces = {"application/json;charset=UTF-8"} )
public Object getUserById(@RequestBody String json) {
System.out.println(json);
JSONObject jsonObject = JSONObject.parseObject(json);
String temp = jsonObject.getString("ids");
List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
Integer id = Integer.valueOf(ids.get(0));
User user1 = userService.queryById(id);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("data",user1);
jsonObject1.put("code","200");
return jsonObject1;
}
@ResponseBody
@PostMapping(value = "/edit",produces = {"application/json;charset=UTF-8"} )
public Object editUserById(@RequestBody String json) {
System.out.println(json);
JSONObject jsonObject = JSONObject.parseObject(json);
String temp = jsonObject.getString("ids");
List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
// String[] ids = temp.split(",");
// List<String> list = Arrays.asList(ids);
// Integer id = Integer.valueOf(list.get(0));
System.out.println(ids);
System.out.println(ids.get(0));
User user1 = User.builder().id(ids.get(0))
.num(Integer.valueOf((String)jsonObject.get("num")))
.address((String) jsonObject.get("address"))
.name((String) jsonObject.get("name"))
.aBC(jsonObject.getString("aBC"))
.build();
userService.update(user1);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("code","200");
return jsonObject1;
}
@ResponseBody
@PostMapping(value = "/add",produces = {"application/json;charset=UTF-8"} )
public Object addUserById(@RequestBody String json) {
System.out.println(json);
JSONObject jsonObject = JSONObject.parseObject(json);
String temp = jsonObject.getString("ids");
List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
// String[] ids = temp.split(",");
// List<String> list = Arrays.asList(ids);
// Integer id = Integer.valueOf(list.get(0));
// System.out.println(ids);
// System.out.println(ids.get(0));
User user1 = User.builder()
.num(Integer.valueOf((String)jsonObject.get("num")))
.address((String) jsonObject.get("address"))
.name((String) jsonObject.get("name"))
.aBC(jsonObject.getString("aBC"))
.build();
userService.insert(user1);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("code","200");
return jsonObject1;
}
@ResponseBody
@PostMapping(value = "/delete",produces = {"application/json;charset=UTF-8"} )
public Object deleteUserById(@RequestBody String json) {
System.out.println(json);
JSONObject jsonObject = JSONObject.parseObject(json);
String temp = jsonObject.getString("ids");
List<Integer> ids = JSONArray.parseArray(temp,Integer.class);
ids.forEach(
(v)-> userService.deleteById(v)
);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("code","200");
return jsonObject1;
}
}
测试
结果能实现跳转和增删改查
项目地址
https://gitee.com/liuweiqiang12/springboot