Spring boot +tymeleaf 小案例总结
首先在spring 官网上 https://start.spring.io/ 上生成一个程序包,注意依赖选择
解压出程序,用idea 工具打开
这里我们对客户信息进行增删改查
在mysql中新建一个customer表
create table customer(
id varchar(40) primary key,
name varchar(20),
gender varchar(10),
birthday date,
cellphone varchar(20),
email varchar(40),
preference varchar(100),
type varchar(40),
description varchar(255)
);
插入三条测试数据
insert into customer values("a11","tom","男","2010-10-10","13888888888","tom@163.com","吃,喝,玩","vip","good man");
insert into customer values("a11","fox","男","2000-10-10","13888888888","tom@163.com","吃,喝,玩","vip","good man");
insert into customer values("a11","james","男","1990-10-10","13888888888","tom@163.com","吃,喝,玩","vip","good man");
idea 工具安装上lombox插件,
安装过程很简单
点开File-setting 菜单搜索插件lombox,点击安装即可
安装完成之后别忘了在pom文件下加入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
</dependency>
然后新建一个customer 类的java bean
@Getter
@Setter
@ToString
public class Customer {
private String id;
private String name;
private String gender;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date birthday;
private String cellphone;
private String email;
private String preference;
private String type;
private String description;
}
建立Controller层
@Controller
@RequestMapping("customer")
public class CustomerController {
@Autowired
public CustomerService customerService;
@RequestMapping("customerList")
public String getCustomerList(Model model){ //获取全部客户端列表
try {
model.addAttribute("customerlist",customerService.getCustomerList());
return "customer/customerlist";
} catch (Exception e) {
return "customer/error";
}
}
@RequestMapping("customerDetail")
public String getCustomerDatail(String id,Model model){
try {
model.addAttribute("customerdetail",customerService.getCustomerDetail(id));
return "customer/customerdetail";
} catch (Exception e) {
return "customer/error";
}
}
/**
* 调用接口类
* @param customer
* @return
*/
@RequestMapping("customerupdate1")
@ResponseBody
public CustomerUpdate customerUpdate1(@Valid @RequestBody Customer customer){
CustomerUpdate customerUpdate=new CustomerUpdate();
if(customer.getName()==null){
return customerUpdate;
}
try {
if(customerService.customerUpdate(customer)){
customerUpdate.retunCode="1";
customerUpdate.success="success";
}
return customerUpdate;
} catch (Exception e) {
return customerUpdate;
}
}
@RequestMapping("customerupdate2")
public void customerUpdate2(HttpServletRequest request,HttpServletResponse response){
try {
request.setCharacterEncoding("UTF-8");
Customer customer=new Customer();
DateConverter dateConverter=new DateConverter();
dateConverter.setPattern("yyyy-mm-dd");//调用日期转换器
ConvertUtils.register(dateConverter,java.util.Date.class);//将Date类的格式转换为yyyy-mm-dd的形式
BeanUtils.populate(customer,request.getParameterMap());//customer中的birthday是date类型,
if(customerService.customerUpdate(customer)){
response.sendRedirect(request.getContextPath()+"/customer/customerList");
}else{
response.sendRedirect(request.getContextPath()+"/customer/error");
}
} catch (Exception e) {
try {
response.getWriter().write("编辑客户信息出错");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("customerDelete")
public void customerDelete(HttpServletRequest request,HttpServletResponse response,String id){
try {
if(customerService.customerDelete(id)){
response.sendRedirect(request.getContextPath()+"/customer/customerList");
}else{
response.sendRedirect(request.getContextPath()+"/customer/error");
}
} catch (Exception e) {
try {
response.getWriter().write("删除客户信息出错");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
创建Service层
@Service
public class CustomerService {
@Autowired
public CustomerDao customerDao;
public List<Customer> getCustomerList() throws Exception {
return customerDao.getCoustomerList();
}
public Customer getCustomerDetail(String id) throws Exception {
return customerDao.getCoustomerDetail(id);
}
public boolean customerUpdate(Customer customer) throws Exception {
return customerDao.customerUpdate(customer);
}
public boolean customerDelete(String id) throws Exception {
return customerDao.customerDelete(id);
}
}
创建Dao层
@Repository
public class CustomerDao {
public List<Customer> getCoustomerList() throws Exception {
QueryRunner qr=new QueryRunner(DbUtilsHelp.getDateSource());
return qr.query(SQLConst.getCustomerList,new BeanListHandler<Customer>(Customer.class));
}
public Customer getCoustomerDetail(String id) throws Exception {
QueryRunner qr=new QueryRunner(DbUtilsHelp.getDateSource());
return qr.query(SQLConst.getCustomerDetail,new BeanHandler<Customer>(Customer.class),id);
}
public boolean customerUpdate(Customer customer) throws Exception {
QueryRunner qr=new QueryRunner(DbUtilsHelp.getDateSource());
return qr.update(SQLConst.customerUpdate,customer.getName(),customer.getGender()
,customer.getBirthday(),customer.getCellphone(),customer.getEmail(),
customer.getPreference(),customer.getType(),customer.getDescription(),customer.getId())>0;
}
public boolean customerDelete(String id) throws Exception {
QueryRunner qr=new QueryRunner(DbUtilsHelp.getDateSource());
return qr.update(SQLConst.customerDelete,id)>0;
}
}
创建SQl常量
public class SQLConst {
public static final String getCustomerList="select * from customer";
public static final String getCustomerDetail="select * from customer where id=?";
public static final String customerUpdate= "update customer set name=?,gender=?,birthday=?,cellphone=?,email=?,preference=?,type=?,description=? where id=?";
public static final String customerDelete="delete from customer where id=?";
}
由于我采用的DBUtils 操作的JDBC所以还需要在pom文件下添加如下依赖
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
新建工具类DbUtilsHelp 操作C3p0连接池
public class DbUtilsHelp {
private static ComboPooledDataSource dataSource=new ComboPooledDataSource();
public static ComboPooledDataSource getDateSource () throws Exception{
setDateSource();
return dataSource;
}
public static Connection getConnection () throws Exception{
setDateSource();
return dataSource.getConnection();
}
private static void setDateSource() throws PropertyVetoException {
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///luoming?characterEncoding=UTF-8");
dataSource.setUser("root");
dataSource.setPassword("123456");
}
}
创建一个输出的Dto,用来接口返回参数
public class CustomerUpdate {
public String retunCode="0";
public String success="error";
}
这里我的编辑方法写了两种
第一种是通过ajax 调用/customer/customerupdate1接口进行修改,然后转发到列表页面
第二种则是通过request 和response操作修改,然后转发到列表页面
获取列表页面customerlist.html代码如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div align="center">
<p th:if="${customerlist}==null">无客户信息
<p>
<table th:if="${customerlist}!=null" border="1" width="85%" align="center">
<tr>
<td><input type="checkbox"/></td>
<td>客戶編號</td>
<td>客戶姓名</td>
<td>客戶性別</td>
<td>客戶生日</td>
<td>客戶電話</td>
<td>客戶郵箱</td>
<td>客戶愛好</td>
<td>客戶類別</td>
<td>客戶描述</td>
<td>操作</td>
</tr>
<tr th:each="customer:${customerlist}">
<td><input type="checkbox"/></td>
<td th:text="${customer.id}"></td>
<td th:text="${customer.name}"></td>
<td th:text="${customer.gender}"></td>
<td th:text="${customer.birthday}"></td>
<td th:text="${customer.cellphone}"></td>
<td th:text="${customer.email}"></td>
<td th:text="${customer.preference}"></td>
<td th:text="${customer.type}"></td>
<td th:text="${customer.description}"></td>
<td>
<a th:text="编辑" th:href="@{/customer/customerDetail(id=${customer.id})}"></a>
<a th:text="删除" th:href="@{/customer/customerDelete(id=${customer.id})}"></a>
</td>
</tr>
</table>
</div>
</body>
</html>
客户详情页面如下customerdetail
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>客户详情信息</title>
</head>
<body>
<form method="post" id="form">
<input type="hidden" name="id" th:value="${customerdetail.id}"/>
客户姓名:<input type="text" name="name" th:value="${customerdetail.name}"/></br>
客户姓别:<input type="text" name="gender" th:value="${customerdetail.gender}"/></br>
客户生日:<input type="text" name="birthday" th:value="${customerdetail.birthday}"/></br>
客户电话:<input type="text" name="cellphone" th:value="${customerdetail.cellphone}"/></br>
客户邮箱:<input type="text" name="email" th:value="${customerdetail.email}"/></br>
客户爱好:<input type="text" name="preference" th:value="${customerdetail.preference}"/></br>
客户类别:<input type="text" name="type" th:value="${customerdetail.type}"/></br>
客户描述:<input type="text" name="description" th:value="${customerdetail.description}"/></br>
<input type="button" id="update" value="修改" />
</form>
</body>
<script type="text/javascript" th:src="@{/JS/jquery-3.3.1.min.js}"></script>
<script type="text/javascript">
$(function () {
$("#update").click(function () {
var para={id:$("input[name='id']").val(),
name:$("input[name='name']").val(),
gender:$("input[name='gender']").val(),
birthday:new Date($("input[name='birthday']").val()),//getDate(),
cellphone:$("input[name='cellphone']").val(),
email:$("input[name='email']").val(),
preference:$("input[name='preference']").val(),
type:$("input[name='type']").val(),
description:$("input[name='description']").val()
};
$.ajax( {
type:"POST",
contentType:"application/json",
url:"/customer/customerupdate1",
dataType: "json",
data: JSON.stringify(para),
success :function (data) {
if(data.retunCode="1" && data.success=="success"){
location.href="/customer/customerList"
}
}
})
})
})
</script>
</html>
这个页面表单最终会调用/customer/customerupdate1这个借口返回数据 并转发列表页面
浏览器输入http://localhost:8080/customer/customerList
可以看到如上结果
点击编辑
列表得到修改
但是这种方法采用的是ajax转发的请求,性能并不好
如果采用第二种方法,性能则会好很多
修改客户详情页customerdetail.html
代码如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>客户详情信息</title>
</head>
<body>
<form method="post" th:action="@{/customer/customerupdate2}">
<input type="hidden" name="id" th:value="${customerdetail.id}"/>
客户姓名:<input type="text" name="name" th:value="${customerdetail.name}"/></br>
客户姓别:<input type="text" name="gender" th:value="${customerdetail.gender}"/></br>
客户生日:<input type="text" name="birthday" th:value="${customerdetail.birthday}"/></br>
客户电话:<input type="text" name="cellphone" th:value="${customerdetail.cellphone}"/></br>
客户邮箱:<input type="text" name="email" th:value="${customerdetail.email}"/></br>
客户爱好:<input type="text" name="preference" th:value="${customerdetail.preference}"/></br>
客户类别:<input type="text" name="type" th:value="${customerdetail.type}"/></br>
客户描述:<input type="text" name="description" th:value="${customerdetail.description}"/></br>
<input type="submit" value="修改"/>
</form>
</body>
<script type="text/javascript" th:src="@{/JS/jquery-3.3.1.min.js}"></script>
</html>
采用表单自动提交处理方式
这时候请求会发往controller层中如下代码处理
@RequestMapping("customerupdate2")
public void customerUpdate2(HttpServletRequest request,HttpServletResponse response){
try {
request.setCharacterEncoding("UTF-8");
Customer customer=new Customer();
DateConverter dateConverter=new DateConverter();
dateConverter.setPattern("yyyy-mm-dd");//调用日期转换器
ConvertUtils.register(dateConverter,java.util.Date.class);//将Date类的格式转换为yyyy-mm-dd的形式
BeanUtils.populate(customer,request.getParameterMap());//customer中的birthday是date类型,
if(customerService.customerUpdate(customer)){
response.sendRedirect(request.getContextPath()+"/customer/customerList");
}else{
response.sendRedirect(request.getContextPath()+"/customer/error");
}
} catch (Exception e) {
try {
response.getWriter().write("编辑客户信息出错");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
这里的日期格式转化器一定要使用,否则会出现日期转化失败问题
新增批量删除和按条件查询和新增客户功能,修改customerList页面如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title th:text="查询客户信息"></title>
</head>
<body>
<div align="center">
<div align="center">
<form method="post" th:action="@{/customer/getcustomerByCon}">
<select name="field">
<option th:text="请选择条件查询"></option>
<option value="name" th:text="按姓名查询"></option>
<option value="gender" th:text="按性别查询"></option>
<option value="type" th:text="按类别查询"></option>
</select>
<input type="text" name="msg"/>
<input type="submit" value="查询">
</form>
</div>
<p th:if="${customerlist}==null" th:text="无客户信息">
<p>
<table th:if="${customerlist}!=null" border="1" width="85%" align="center">
<tr>
<td><input type="checkbox" id="ck"/></td>
<td th:text="客戶編號"></td>
<td th:text="客戶姓名"></td>
<td th:text="客戶性別"></td>
<td th:text="客戶生日"></td>
<td th:text="客戶電話"></td>
<td>客戶郵箱</td>
<td>客戶愛好</td>
<td>客戶類別</td>
<td>客戶描述</td>
<td>操作</td>
</tr>
<tr th:each="customer:${customerlist}">
<td><input type="checkbox" th:value="${customer.id}" name="cks"/></td>
<td th:text="${customer.id}" ></td>
<td th:text="${customer.name}"></td>
<td th:text="${customer.gender}"></td>
<td th:text="${customer.birthday}"></td>
<td th:text="${customer.cellphone}"></td>
<td th:text="${customer.email}"></td>
<td th:text="${customer.preference}"></td>
<td th:text="${customer.type}"></td>
<td th:text="${customer.description}"></td>
<td>
<a th:text="编辑" th:href="@{/customer/customerDetail(id=${customer.id})}"></a>
<a th:text="删除" th:href="@{/customer/customerDelete(id=${customer.id})}"></a>
</td>
</tr>
<tr>
<td colspan="10"><a class="del" href="javascript:void(0)" th:text="删除全选"></a></td>
<td><a th:text="添加" th:href="@{/customer/getcustomerAdd}"></a></td>
</tr>
</table>
</div>
</body>
<script type="text/javascript" th:src="@{/JS/jquery-3.3.1.min.js}"></script>
<script type="text/javascript">
$(function () {
$("#ck").click(function () {
var flag = $(this).get(0).checked;
$("input[name='cks']").each(function () {
$(this).get(0).checked = flag;
});
})
$(".del").click(function () {
var ids=new Array();
$("input[name='cks']").each(function () {
var flag=$(this).get(0).checked;
if(flag){
var id=$(this).val();
ids.push(id);
}
});
$.ajax({
type:"POST",
url:"/customer/customerDeleteBatch",
contentType:"application/json",
data:JSON.stringify(ids),
dataType:"json",
success:function (data) {
if(data.success=="success" && data.retunCode=="1"){
location.href="/customer/customerList";
}
}
})
})
})
</script>
</html>
创建一个添加客户页面customerAdd.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>客户信息添加</title>
</head>
<body>
<form method="post" th:action="@{/customer/customerAdd}">
客户姓名:<input type="text" name="name" /></br>
客户姓别:<input type="text" name="gender" /></br>
客户生日: <input type="text" name="birthday" class="Wdate" "WdatePicker()" readonly="readonly"><br>
客户电话:<input type="text" name="cellphone" /></br>
客户邮箱:<input type="text" name="email" /></br>
客户爱好:<input type="text" name="preference" /></br>
客户类别:<input type="text" name="type" /></br>
客户描述:<input type="text" name="description" /></br>
<input type="submit" value="添加"/>
</form>
</body>
<script language="javascript" type="text/javascript" th:src="@{/My97DatePicker/WdatePicker.js}"></script>
</html>
这里用了一个时间选择器的插件WdatePicker.js
customercontroller中添加如下代码
@RequestMapping("getcustomerAdd")
public String getcustomerAdd(Model model){
try {
return "customer/customerAdd";
} catch (Exception e) {
return "customer/error";
}
}
@RequestMapping("customerAdd")
public void customerAdd(HttpServletRequest request,HttpServletResponse response){
try {
request.setCharacterEncoding("UTF-8");
Customer customer=new Customer();
DateConverter dateConverter=new DateConverter();
dateConverter.setPattern("yyyy-mm-dd");//调用日期转换器
ConvertUtils.register(dateConverter,java.util.Date.class);//将Date类的格式转换为yyyy-mm-dd的形式
BeanUtils.populate(customer,request.getParameterMap());//customer中的birthday是date类型,
if(customerService.customerAdd(customer)){
response.sendRedirect(request.getContextPath()+"/customer/customerList");
}else{
response.sendRedirect(request.getContextPath()+"/customer/error");
}
} catch (Exception e) {
try {
response.setCharacterEncoding("UTF-8");
response.getWriter().write("添加客户信息出错");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//批量删除
@RequestMapping("customerDeleteBatch")
@ResponseBody
public CustomerUpdate customerDeleteBatch(@Valid @RequestBody String[] id){
CustomerUpdate customerUpdate=new CustomerUpdate();
if(id==null){
return customerUpdate;
}
try {
if(customerService.customerDeleteBatch(id)){
customerUpdate.retunCode="1";
customerUpdate.success="success";
}
return customerUpdate;
} catch (Exception e) {
return customerUpdate;
}
}
/**
* 按条件查询
* @param model
* @return
*/
@RequestMapping("getcustomerByCon")
public String getCustomerListByCon(HttpServletRequest request,Model model){
try {
String filed=request.getParameter("field");
String msg=request.getParameter("msg");
if(!StringHelp.IsNullOrEmpty(filed) && !StringHelp.IsNullOrEmpty(msg)){
model.addAttribute("customerlist",customerService.getCustomerListByCon(filed,msg));
}else{
model.addAttribute("customerlist",customerService.getCustomerList());
}
return "customer/customerlist";
} catch (Exception e) {
return "customer/error";
}
}
customerservice添加如下代码
public boolean customerAdd(Customer customer) throws Exception {
return customerDao.customerAdd(customer);
}
public boolean customerDeleteBatch(String[] id) throws Exception {
return customerDao.customerDeleteBatch(id);
}
public List<Customer> getCustomerListByCon(String filed,String msg) throws Exception {
return customerDao.getCustomerListByCon(filed,msg);
}
dao层添加如下代码
public boolean customerAdd(Customer customer) throws Exception {
QueryRunner qr=new QueryRunner(DbUtilsHelp.getDateSource());
return qr.update(SQLConst.customerAdd, UUiDHelp.getUUID(),customer.getName(),customer.getGender()
,customer.getBirthday(),customer.getCellphone(),customer.getEmail(),
customer.getPreference(),customer.getType(),customer.getDescription())>0;
}
public boolean customerDeleteBatch(String[] id) throws Exception {
QueryRunner qr=new QueryRunner(DbUtilsHelp.getDateSource());
Object[][] para=new Object[id.length][1];
for (int i=0;i<id.length;i++){
para[i][0]=id[i];
}
int count=0;
int[] res=qr.batch(SQLConst.customerDelete,para);
for (int i=0;i<res.length;i++){
count++;
}
return count==res.length;
}
public List<Customer> getCustomerListByCon(String filed,String msg) throws Exception {
QueryRunner qr=new QueryRunner(DbUtilsHelp.getDateSource());
return qr.query(SQLConst.getCustomerListByCon.replace("ss",filed),new BeanListHandler<Customer>(Customer.class),"%"+msg+"%");
}
SqlConst添加如下sql语句
public static final String customerAdd="insert into customer value(?,?,?,?,?,?,?,?,?)";
public static final String getCustomerListByCon="select * from customer where ss like ?";
浏览器输入地址最终结果如下
到此这个小案例暂时完成,目前可以进行一些增删改查的操作,后续将会在添加一些新功能,尽情期待