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 ...
随机推荐
- K8S入门系列之集群yum安装(一)
kubernetes master 节点包含的组件: 1.kube-apiserver :集群核心,集群API接口.集群各个组件通信的中枢:集群安全控制: 2.kube-scheduler: 集群调度 ...
- Servlet中response的相关案例(重定型,验证码,ServletContext文件下载)
重定向 首先设置状态码,设置响应头 //访问Demo1自动跳转至Demo2 //设置状态码 response.setStatus(302); //设置响应头 response.setHeader(&q ...
- 张孝祥java高新技术 --- jkd1.5 新特性
1. 静态导入 import static java.lang.Math.max; 2. 可变参数 3. 自动装箱,拆箱 4. 枚举
- yum 配置文件 以及 语法
yum的配置文件 #vi /etc/yum.conf [main] cachedir=/var/cache/yum/$basearch/$releasever keepcache= debugleve ...
- 从最近面试聊聊我所感受的.net天花板
#0 前言 入职新公司没多久,闲来无事在博客园闲逛,看到园友分享的面试经历,正好自己这段时间面试找工作,也挺多感想的,干脆趁这个机会总结整理一下.博主13年开始实习,14年毕业.到现在也工作五六年了. ...
- 串烧 JavaCAS相关知识
JMM与问题引入 为啥先说JMM,因为CAS的实现类中维护的变量都被volatile修饰, 这个volatile 是遵循JMM规范(不是百分百遵循,下文会说)实现的保证多线程并发访问某个变量实现线程安 ...
- 新闻实时分析系统 Spark Streaming实时数据分析
1.Spark Streaming功能介绍1)定义Spark Streaming is an extension of the core Spark API that enables scalable ...
- 【集训Day2 哈希表】【NHOI2015】【Luogu P2421】差
LuoguP2421 原题来自NHOI2015 [解题思路] 本题的解题方法有三种,一种为枚举减数,二分查找被减数.第二种为利用数据单调性用尺取法进行查找,第三种为运用哈希表以快速查找数据. [解题反 ...
- 用CodePush在React Native App中做热更新
最近在学React Native,学到了CodePush热更新. 老师讲了两种实现的方法,现将其记录一下. 相比较原生开发,使用React Native开发App不仅能节约开发成本,还能做原生开发不能 ...
- SpringSecurity代码实现JWT接口权限授予与校验
通过笔者前两篇文章的说明,相信大家已经知道JWT是什么,怎么用,该如何结合Spring Security使用.那么本节就用代码来具体的实现一下JWT登录认证及鉴权的流程. 一.环境准备工作 建立Spr ...