Spring Boot结和Spring Data(Ehcache缓存,Thymeleaf页面,自定义异常页面跳转,Swagger2)
项目结构
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bjsxt</groupId>
<artifactId>spring-bootdata-hotel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-bootdata-hotel</name>
<description>spring-bootdata-hotel</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot 缓存支持启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache 坐标 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
俩个配置文件
application.properties
#项目端口配置
server.port=8080
server.address=0.0.0.0
#Mysql数据源配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/sys?characterEncoding=UTF8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
#JPA相关配置
#项目启动生成数据库
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
#josn数据格式
spring.jackson.serialization.indent-output=true
#对于ehcache缓存进行相关配置
spring.cache.ehcache.config=classpath:ehcache.xml
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir"/> <!--defaultCache:echcache 的默认缓存策略 -->
<defaultCache maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache> <!-- 自定义缓存策略 -->
<cache name="room"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
三个页面,一个异常处理页面,一个添加页面,一个主页面(所有的查询操作,以及删除操作)
templates/error.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>页面崩溃了呢,主人~~~</h1>
<br/>
<h1>主人,页面异常是因为</h1>
<span th:text="${error}"></span>
</body>
</html>
templates/addhotel.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>添加房间</title>
</head>
<body>
<h1 align="center">添加房间</h1>
<hr/>
<form method="post" th:action="@{/addroom}" >
<p>
房型:<select name="type" >
<option value="1" selected="selected">标准间</option>
<option value="2">双人间</option>
<option value="3">豪华间</option>
<option value="4">总统间</option>
<option value="5">大床房</option>
</select>
</p>
<p>
价格:<input type="number" name="price"><font color="red" th:errors="${room.price}"></font>
</p>
<p>
所属酒店:
<select name="hotel" >
<option value="0">=请选择=</option>
<span th:each="h:${hotel}">
<option th:value="${h.hid}"><span th:text="${h.hname}"></span></option>
</span>
</select>
</p>
<p>描述:</p>
<textarea name="info" style="height: 60px"></textarea>
<p>
<input type="submit" value="发布">
</p>
</form>
</body>
</html>
templates/index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>主页面</title>
</head>
<body>
<h1 align="center">酒店管理系统</h1>
<hr/>
<form th:action="@{/findlike}" method="post">
按照酒店名称:<input type="text" name="hname">
<input type="submit" value="查询">
</form>
<hr/>
<a th:href="@{/hotel}">添加宾馆</a>
<h1>房型:</h1>
<h1>1:标准间 2:双人间 3:豪华间</h1>
<h1>4:总统间 5:大床房</h1>
<hr/>
<table border="1" align="center" width="50%">
<tr>
<th>ID</th>
<th>酒店名称</th>
<th>房型</th>
<th>价格</th>
<th>地址</th>
<th>电话</th>
<th>操作</th>
</tr>
<tr th:each="room:${room}">
<th th:text="${room.id}"></th>
<th th:text="${room.hotel.hname}">
<th th:text="${room.type}"></th>
<th th:text="${room.price}"></th>
<th th:text="${room.hotel.address}"></th>
<th th:text="${room.hotel.mobile}"></th>
<th><a th:href="@{/deleteById(id=${room.id})}">删除</a></th>
</tr>
</table>
</body>
</html>
业务代码
处理异常
package com.bjsxt.exception;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class GolableException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mav=new ModelAndView();
if (e instanceof Exception){
mav.setViewName("error");
}
mav.addObject("error",e.toString());
return mav;
}
}
Spring Boot正向工程
俩个实体类,表是一对多的关系
com.bjsxt.pojo.Hotel
package com.bjsxt.pojo;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "hotel")
@Data
public class Hotel implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "hid")
private int hid;
@Column(name = "hname")
private String hname;
@Column(name = "address")
private String address;
@Column(name = "mobile")
private String mobile;
@OneToMany(mappedBy = "hotel",cascade = CascadeType.PERSIST)
private Set<Room> room=new HashSet<>();
public Hotel() {
}
public Hotel(String hname, String address, String mobile, Set<Room> room) {
this.hname = hname;
this.address = address;
this.mobile = mobile;
this.room = room;
}
}
com.bjsxt.pojo.Room
package com.bjsxt.pojo;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity
@Table(name = "room")
@Data
public class Room implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "type")
private int type;
@Column(name = "price")
@NotNull
private double price;
@Column(name = "info")
private String info;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "hid")
private Hotel hotel;
public Room() {
}
public Room(int type, double price, String info, Hotel hotel) {
this.type = type;
this.price = price;
this.info = info;
this.hotel = hotel;
}
}
dao层
com.bjsxt.dao.HotelDao
package com.bjsxt.dao;
import com.bjsxt.pojo.Hotel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface HotelDao extends JpaRepository<Hotel,Integer> , JpaSpecificationExecutor<Hotel> {
}
com.bjsxt.dao.RoomDao
package com.bjsxt.dao;
import com.bjsxt.pojo.Room;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface RoomDao extends JpaRepository<Room,Integer>, JpaSpecificationExecutor<Room> {
@Query(value = "select h.*,r.* from hotel h,room r where h.hid=r.hid and h.hname like ?",nativeQuery = true)
List<Room> findLikeByhname(String hname);
}
service层(接口)
com.bjsxt.service.impl.HotelService
package com.bjsxt.service;
import com.bjsxt.pojo.Hotel;
import java.util.List;
public interface HotelService {
/**
* 查询所有的宾馆信息
* @return
*/
List<Hotel> findall();
}
com.bjsxt.service.RoomService
package com.bjsxt.service;
import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import org.springframework.data.domain.Page;
import java.util.List;
public interface RoomService {
/**
* 添加房间
* @param room
*/
void addRoom(Room room);
/**
* 查询所有房间
* @return
*/
public List<Room> findAll();
/**
* 模糊查询
* @param hname
* @return
*/
public List<Room> findLike(String hname);
/**
* 指定id删除
* @param id
*/
void deleteid(int id);
}
实现类
com.bjsxt.service.impl.HotelServiceImpl
package com.bjsxt.service.impl;
import com.bjsxt.dao.HotelDao;
import com.bjsxt.pojo.Hotel;
import com.bjsxt.service.HotelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class HotelServiceImpl implements HotelService {
@Autowired
private HotelDao hotelDao;
@Override
public List<Hotel> findall() {
List<Hotel> hotels = hotelDao.findAll();
return hotels;
}
}
com.bjsxt.service.impl.RoomServiceImpl
package com.bjsxt.service.impl;
import com.bjsxt.dao.HotelDao;
import com.bjsxt.dao.RoomDao;
import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import com.bjsxt.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
/**
* 处理放假的操作
*/
@Service
public class RoomServiceImpl implements RoomService {
@Autowired
private RoomDao roomDao;
/**
* 添加房间
* @param room
*/
@CacheEvict(value = "room",allEntries = true)//清空缓存
@Override
public void addRoom(Room room) {
roomDao.save(room);
}
/**
* 查询所有房间
* @return
*/
@Cacheable(value = "room")//配置缓存
@Override
public List<Room> findAll() {
List<Room> roomList = roomDao.findAll();
return roomList;
}
@Override
public List<Room> findLike(String hname) {
List<Room> roomList = roomDao.findLikeByhname(hname);
return roomList;
}
@Override
@CacheEvict(value = "room",allEntries = true)//清空缓存
public void deleteid(int id) {
roomDao.deleteById(id);
}
}
控制层
com.bjsxt.controller.HotelController
package com.bjsxt.controller;
import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import com.bjsxt.service.HotelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class HotelController {
/**
* 跳转页面
*/
@RequestMapping("/go")
private String goIndex(){
return "index";
}
@Autowired
private HotelService hs;
/**
* 查询所有的酒店
*/
@RequestMapping("/hotel")
private String findAll(Model model,Room room){
List<Hotel> hotel = hs.findall();
model.addAttribute("hotel",hotel);
return "addhotel";
}
}
com.bjsxt.controller.RoomController
package com.bjsxt.controller;
import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import com.bjsxt.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import java.util.List;
@Controller
public class RoomController {
@Autowired
private RoomService rs;
/**
* 新增
* @param room
* @return
*/
@RequestMapping("/addroom")
private String addRoom(@Valid Room room, BindingResult result){
if(result.hasErrors()){
return "addhotel";
}else {
rs.addRoom(room);
return "redirect:/findall";
}
}
/**
* 查询所有
* @param model
* @return
*/
@RequestMapping("/findall")
public String findAll(Model model){
List<Room> rooms = rs.findAll();
model.addAttribute("room",rooms);
return "index";
}
/**
* 模糊查询
* @param hname
* @param model
* @return
*/
@RequestMapping("/findlike")
public String findLike(String hname,Model model){
List<Room> rooms ;
if (hname==""){
rooms = rs.findAll();
}else {
hname="%"+hname+"%";
rooms = rs.findLike(hname);
}
model.addAttribute("room",rooms);
return "index";
}
@RequestMapping("/deleteById")
public String deleteById(int id){
rs.deleteid(id);
return "redirect:/findall";
}
}
启动类
com.bjsxt.SpringBootdataHotelApplication
package com.bjsxt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableCaching
@EnableSwagger2
public class SpringBootdataHotelApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootdataHotelApplication.class, args);
}
}
Spring Boot结和Spring Data(Ehcache缓存,Thymeleaf页面,自定义异常页面跳转,Swagger2)的更多相关文章
- Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面
Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面 在<Spring Boot(一):快速开始>中介绍了如何使用 Spring Boot 构建一个工程,并且提 ...
- Spring Boot 2.x基础教程:使用 Thymeleaf开发Web页面
通过本系列教程的前几章内容(API开发.数据访问).我们已经具备完成一个涵盖数据存储.提供HTTP接口的完整后端服务了.依托这些技能,我们已经可以配合前端开发人员,一起来完成一些前后端分离的Web项目 ...
- 【spring boot 系列】spring data jpa 全面解析(实践 + 源码分析)
前言 本文将从示例.原理.应用3个方面介绍spring data jpa. 以下分析基于spring boot 2.0 + spring 5.0.4版本源码 概述 JPA是什么? JPA (Java ...
- spring boot(五):spring data jpa的使用
在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...
- Spring Boot 中集成 Redis 作为数据缓存
只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...
- Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)
号外:为读者持续整理了几份最新教程,覆盖了 Spring Boot.Spring Cloud.微服务架构等PDF.获取方式:关注右侧公众号"泥瓦匠BYSocket",来领取吧! 摘 ...
- 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件 内容简介:本文介绍 Spring Boot 的配置文件和配置管理,以及介绍了三种读取配置文 ...
- 使用 Spring Boot 快速构建 Spring 框架应用--转
原文地址:https://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/ Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2 ...
- 使用 Spring Boot 快速构建 Spring 框架应用,PropertyPlaceholderConfigurer
Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2002 年发布以来,Spring 框架已经成为企业应用开发领域非常流行的基础框架.有大量的企业应用基于 Spring 框架来开发.S ...
随机推荐
- 201871010114-李岩松《面向对象程序设计(java)》第十一周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 使用ASP.NET Core 3.x 构建 RESTful API - 3.1 资源命名
之前讲了RESTful API的统一资源接口这个约束,里面提到了资源是通过URI来进行识别的,每个资源都有自己的URI.URI里还涉及到资源的名称,而针对资源的名称却没有一个标准来进行规范,但是业界还 ...
- OC语言自学基础知识总结
一.成员变量的作用域 二.点语法 三.构造方法 四.分类 五.类的本质 六.自动生成getter和setter方法 七.description方法 八.id类型 九.SEL 一.成员变量的作用域 @p ...
- 实现两个数字的交换(C语言)
int num1=10; int num2=20; //1.简单的数学方法实现数字交换 num1=num1+num2;//num1=30 num2=num1-num2;//num2=10 num1=n ...
- 易语言 史诗级Json处理 烁_Json模块!!!!
大家好,我是键盘上的魔手 * “************************”* “** 欢迎使用烁Json模块 **”* “** 作者:键盘上的魔手 **”* “** 微信号:codervip ...
- lqb 基础练习 杨辉三角形
基础练习 杨辉三角形 时间限制:1.0s 内存限制:256.0MB 问题描述 杨辉三角形又称Pascal三角形,它的第i+1行是(a+b)i的展开式的系数. 它的一个重要性质是:三角形中的 ...
- ProxySQL读写分离代理
实现ProxySQL反向代理Mysql读写分离 简介 ProxySQL相当于小型的数据库,在磁盘上有存放数据库的目录:ProxySQL用法和mysql相似 启动ProxySQL后会有两个监听端口: 6 ...
- 记录用户登陆信息,你用PHP是如何来实现的
对于初入门的PHP新手来说,或许有一定的难度.建议大家先看看PHP中session的基础含义,需要的朋友可以选择参考. 下面我们就通过具体的代码示例,为大家详细的介绍PHP中session实现记录用户 ...
- 究极秒杀Loadrunner乱码
Loadrunner乱码一击必杀 之前有介绍一些简单的针对Loadrunner脚本或者调试输出内容中乱码的一些设置,但是并没能完全解决一些小伙伴的问题,因为那些设置实在能力有限,还是有很多做不到的事情 ...
- Spring中常见的设计模式——单例模式
一.单例模式的应用场景 单例模式(singleton Pattern)是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点.J2EE中的ServletContext,ServletCon ...