SpringBootMVC02——SpringDataJpa与ThymeLeaf
大纲
- SpringDataJpa进阶使用
- SpringDataJpa自定义查询
- 整合Servlet、Filter、Listener
- 文件上传
- Thymeleaf常用标签
1.整合Servlet
注解方式
启动类上添加注解
@SpringBootApplication
== @ServletComponentScan == public class Springboot011Application { public static void main(String[] args) {
SpringApplication.run(Springboot011Application.class, args);
} }
Servlet类
@WebServlet(name = "myServlet",urlPatterns = "/srv",loadOnStartup = )
public class MyServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("");
super.doGet(req, resp);
} }
2.编码方式
启动类中添加
@Bean
public ServletRegistrationBean<MyServlet2> getServletRegistrationBean(){
ServletRegistrationBean<MyServlet2> bean = new ServletRegistrationBean<>(new MyServlet2(), "/s2");
bean.setLoadOnStartup();
return bean;
}
这种方式在Servlet中无需注解
3.整合Filter
需要implements Filter
监听器
实现接口 ServletContextListener
需要MyListener implements ServletContextListener
可以把静态文件放到以下工程目录下
- src/main/resources/static
- src/main/webapp
4.常用表单数据接收方式
参数接收
@GetMapping(value = "/hello/{id}")
public String hello(@PathVariable("id") Integer id){
return "ID:" + id;
}
实体对象接受
JSON数据
@PostMapping(value = "/user")
public User saveUser2(@RequestBody User user) {
return user;
}
普通实体对象
@PostMapping(value = "/user")
public User saveUser2(User user) {
return user;
}
参数名取值
@PostMapping(value = "/post")
public String post(@RequestParam(name = "name") String name,
@RequestParam(name = "age") Integer age) {
String content = String.format("name = %s,age = %d", name, age);
return content;
}
5.上传与下载
@RequestMapping("/fileUploadController")
public String fileUpload(MultipartFile filename) throws Exception{
System.out.println(filename.getOriginalFilename());
filename.transferTo(new File("e:/"+filename.getOriginalFilename()));
return "ok";
}
6.JPA的进阶使用
官方文档: https://docs.spring.io/spring-data/jpa/docs/2.1.8.RELEASE/reference/html/
public interface AccountRepository extends JpaRepository<Account, Integer>
7.控制台显示SQL
application.properties 中配置``` spring.jpa.show-sql=true ```
8.自定义查询
| 关键字 | 意义 |
| :---------- | ------------------------------------------------------------ |
| And | 等价于 SQL 中的 and 关键字,比如 findByUsernameAndPassword(String user, Striang pwd); |
| Or | 等价于 SQL 中的 or 关键字,比如 findByUsernameOrAddress(String user, String addr); |
| Between | 等价于 SQL 中的 between 关键字,比如 findBySalaryBetween(int max, int min); |
| LessThan | 等价于 SQL 中的 "<",比如 findBySalaryLessThan(int max); |
| GreaterThan | 等价于 SQL 中的">",比如 findBySalaryGreaterThan(int min); |
| IsNull | 等价于 SQL 中的 "is null",比如 findByUsernameIsNull(); |
| IsNotNull | 等价于 SQL 中的 "is not null",比如 findByUsernameIsNotNull(); |
| NotNull | 与 IsNotNull 等价; |
| Like | 等价于 SQL 中的 "like",比如 findByUsernameLike(String user); |
| NotLike | 等价于 SQL 中的 "not like",比如 findByUsernameNotLike(String user); |
| OrderBy | 等价于 SQL 中的 "order by",比如 findByUsernameOrderBySalaryAsc(String user); |
| Not | 等价于 SQL 中的 "! =",比如 findByUsernameNot(String user); |
| In | 等价于 SQL 中的 "in",比如 findByUsernameIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数; |
| NotIn | 等价于 SQL 中的 "not in",比如 findByUsernameNotIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数; |
9.自定义SQL @Query注解
public interface UserDao extends Repository<AccountInfo, Long> { @Query("select a from AccountInfo a where a.accountId = ?1")
public AccountInfo findByAccountId(Long accountId); @Query("select a from AccountInfo a where a.balance > ?1")
public Page<AccountInfo> findByBalanceGreaterThan(Integer balance,Pageable pageable);
}
public interface UserDao extends Repository<AccountInfo, Long> { public AccountInfo save(AccountInfo accountInfo); @Query("from AccountInfo a where a.accountId = :id")
public AccountInfo findByAccountId(@Param("id")Long accountId); @Query("from AccountInfo a where a.balance > :balance")
public Page<AccountInfo> findByBalanceGreaterThan(@Param("balance")Integer balance,Pageable pageable);
}
10.更新操作
@Modifying
@Query("update AccountInfo a set a.salary = ?1 where a.salary < ?2")
public int increaseSalary(int after, int before);
直接使用Native SQL 设置属性 nativeQuery = true public interface UserRepository extends JpaRepository<User, Long> { @Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}
11.Thymeleaf
## Eclipse自动提示插件 ## 官方文档
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#base-objects ### 安装地址: http://www.thymeleaf.org/eclipse-plugin-update-site/ ### Html中添加约束 ```html
<html xmlns:th="http://www.thymeleaf.org">
``` ## URL地址处理 ### @{...} )@{userList} 相对当前路径结果为:http://localhost/thymeleaf/user/userList )@{./userList} 相对当前路径结果为:http://localhost/thymeleaf/user/userList )@{../tiger/home} 相对当前路径结果为:http://localhost/thymeleaf/tiger/home )@{/tiger/home} 相对应用根目录结果为:http://localhost/thymeleaf/tiger/home )@{https://www.baidu.com/} 绝对路径结果为:https://www.baidu.com )``` <link type="text/css" rel="stylesheet" th:href="@{/css/home.css}">``` @ 以 "/" 开头定位到项**目根路径**,否则使用相对路径 ### th:href ```html
<body>
<a th:href="@{userList(id=1)}">、@{userList(id=)}</a>
<a th:href="@{userList(id=1,name=华安)}">、@{userList(id=,name=yoyo)}</a>
<a th:href="@{userList(id=1,name=${userName})}">、@{userList(id=,name=${userName})}</a>
</body> ``` ### th:text 文本 空格属于特殊字符,必须使用单引号包含整个字符串 ``` html
<p class="css1 css2" th:class="'css1 css2'">样式</p>
<p th:text="'Big China'">中国</p>
<p th:text="${userName}">userName</p>
<p th:text="'small smile'+',very good.' + ${userName}">temp</p>
``` #### 数字计算
``` html
<p th:text=""></p>
<p th:text="8+8"> + </p>
<p th:text="8+8+' Love '+9+9"> + +' Love '++</p>
<p th:text="8+8+' Love '+(9+9)"> + +' Love '+(+)</p>
<p th:text="100-${age}"></p>
``` #### Boolean判断
``` html
<p th:text="true">布尔</p>
<p th:text="true and false">true and true</p>
<p th:if="${isMarry}">已结婚</p>
<p th:if="${age}>18">已成年</p>
<p th:if="${age}<18">未成年</p>
``` #### 运算
``` html
<p th:text="15 * 4">值为 </p>
<p th:text="15 * 4-100/10">值为 </p>
<p th:text="100 % 8">值为 </p>
``` #### 比较
```html
<p th:if="5>3"> 大于 </p>
<p th:if="5 >4"> 大于 </p>
<p th:if="10>=8 and 7 !=8">10大于等于8,且 不等于 </p>
<p th:if="!${isMarry}">!false</p>
<p th:if="not(${isMarry})">not(false)</p>
``` ### 三元运算符
```html
<p th:text="7>5?'7大':'5大'">三元运算符</p>
<p th:text="${age}!=null?${age}:'age等于 null'"></p>
<p th:text="${age}!=null?(${age}>=18?'成年':'未成年'):'age等于 null'"></p>
<p th:text="${age2}!=null?${age2}:'age2等于 null'"></p>
<p th:class="${isMarry}?'css2':'css3'">已婚</p>
``` ### th:utext转义
```html
map .addAttribute("china", "<b>Chian</b>,USA,UK");
<p th:text="${china}">默认转义</p>
<p th:utext="${china}">不会转义</p>
``` ### th:attr 设置属性
HTML5 所有的属性,都可以使用 th:* 的形式进行设置值
```html
<a href="http://baidu.com" th:attr="title='百度'">百度</a>
```
html属性设置
```html <a href="" th:attr="title='前往百度',href='http://baidu.com'">前往百度</a>
设置 href 属性
<a href="userList.html" th:attr="href=@{/user/userHome}">用户首页</a>
设置 id 属性,data-target 属性 Html 本身是没有的,但允许用户自定义
<a href="#" th:attr="id='9527',data-target='user'">归海一刀</a> <p th:abc="">th:abc=""</p> <p th:xxoo="yoyo">th:xxoo="yoyo"</p> ``` #### Checked selected ##### Checked
```html
<input type="checkbox" name="option1" checked/><span>是否已婚1?</span>
<input type="checkbox" name="option2" checked="checked"/><span>是否已婚2?</span> 后台传值 : model.addAttribute("isMarry", true); <input type="checkbox" name="option3" th:checked="${isMarry}"/><span>是否已婚?</span>
<input type="radio" name="option4" th:checked="${isMarry}"/><span>是否已婚?</span>
<input type="radio" name="option5" th:checked="!${isMarry}"/><span>是否已婚?</span> ``` <!--option3、option4 会选中;option5 不会选中-->
##### select autofocus
``` html
<select>
<option>a</option>
<option th:selected="${isMarry}">已婚</option>
<option th:selected="${!isMarry}">未婚</option> </select>
<input type="text" th:autofocus="false">
<input type="text" th:autofocus="true">
<input type="text" th:autofocus="false"> ``` ### 日期格式化 <span th:text="${#dates.format(date, 'yyyy-MM-dd HH:mm')}"></span>
## 循环 JSTL 有一个 **c:foreach**,同理 Thymeleaf 也有一个 th:each。 作用都是一样的,都是用于遍历数组、List、Set、Map 等数据。
在Select上循环 ```html
<option th:each="city : ${list}" th:text="${city.name}" th:selected="${cityName} eq ${city.name}">Peking</option>
``` #### 状态变量 loopStatus 如果不指定 为变量 **Stat** - index: 当前迭代对象的index(从0开始计算)
- count: 当前迭代对象的index(从1开始计算)
- size: 被迭代对象的大小 current:当前迭代变量
- even/odd: 布尔值,当前循环是否是偶数/奇数(从0开始计算)
- first: 布尔值,当前循环是否是第一个
- last: 布尔值,当前循环是否是最后一个
- ```html
<tr th:each="city,status : ${list}" th:style="${status.odd}?'background-color:#c2c2c2'">
<!-- EL JSTL-->
<td th:text = "${status.count}"></td>
<td th:text = "${city.id}"></td>
<td th:text = "${city.name}"></td>
</tr>
``` ## 逻辑判断
### If/else ```html
<p th:if="${isMarry}">已婚1</p>
<p th:unless="${isMarry}">未婚</p> ``` ### Switch/case 多条件判断
``` html
<div th:switch="">
<p th:case="">管理员</p>
<p th:case="">操作员</p>
<p th:case="*">未知用户</p>
</div> <div th:switch="-1">
<p th:case="">管理员</p>
<p th:case="*">操作员</p>
<p th:case="*">未知用户</p>
</div> <div th:switch="${isMarry}">
<p th:case="true">已婚</p>
<p th:case="true">已成年</p>
<p th:case="false">未婚</p>
</div> <div th:switch="'For China'">
<p th:case="'For USA'">美国</p>
<p th:case="'For UK'">英国</p>
<p th:case="'For China'">中国</p>
<p th:case="*">未知国籍</p>
</div> ```
## 内联表达式
[[...]] 等价于 th:text(结果将被 HTML 转义),[(...)] 等价于 th:utext(结果不会执⾏HTML转义)
```html
<p>[[${china}]]</p>
<p>[(${china})]</p>
<p>[[Lo1ve]]</p>
<p>[['I Love You Baby']]</p>
<p>[()]</p>
```
禁⽤内联th:inline ="none" ### 内联 JavaScript
```javascript
<script type="text/javascript" th:inline="javascript">
var info = [[${info}]];
var age = [[${age}]];
var id = [[${id}]];
var name = [[${name}]];
console.log(id, name, age, info);
</script>
```
### 前后端分离开发
```javascript
<script type="text/javascript" th:inline="javascript">
/**
* Thymeleaf 将自动忽略掉注释之后 和 分号之前的所有内容,如下为 "前端测试"
*/
var info = /*[[${info}]]*/ "前端测试";
console.log(info);
</script>
```
## Servlet作用域中的对象属性
### URL/request
```html
<p>${param.size()}=[[${param.size()}]]</p>
<p>${param.id}=[[${param.id}]]</p>
``` ### Session
```html
<p>${session.size()}=[[${session.size()}]]</p>
<p>${session.user.id}=[[${session.user.id}]]</p>
```
SpringBootMVC02——SpringDataJpa与ThymeLeaf的更多相关文章
- Thymeleaf+SpringBoot+SpringDataJPA实现的中小医院信息管理系统
项目简介 项目来源于:https://gitee.com/sensay/hisystem 作者介绍 本系统是基于Thymeleaf+SpringBoot+SpringDataJPA实现的的中小医院信息 ...
- 基于springboot+thymeleaf+springDataJpa自带的分页插件实现完整的动态分页
实现百度搜索使用的前五后四原则,效果如下. 下面贴出代码,复制到前端即可,只需要域中放置page对象就可以.(springdatajpa自带的page 注意:第一页是按0开始算的) <div c ...
- Spring-Data-JPA尝鲜:快速搭建CRUD+分页后台实例
前言:由于之前没有接触过Hibernate框架,但是最近看一些博客深深被它的"效率"所吸引,所以这就来跟大家一起就着一个简单的例子来尝尝Spring全家桶里自带的JPA的鲜 Spr ...
- SpringBoot系列——Spring-Data-JPA(究极进化版) 自动生成单表基础增、删、改、查接口
前言 我们在之前的实现了springboot与data-jpa的增.删.改.查简单使用(请戳:SpringBoot系列——Spring-Data-JPA),并实现了升级版(请戳:SpringBoot系 ...
- SpringBoot系列——Spring-Data-JPA
前言 jpa是ORM映射框架,更多详情,请戳:apring-data-jpa官网:http://spring.io/projects/spring-data-jpa,以及一篇优秀的博客:https:/ ...
- SpringBoot关于SpringDataJpa中findOne()方法报错问题
问题描述: 首先用的SpringDataJPA的1.11版本,可以使用findOne()方法根据id查询 然后我使用了2.0.5版本,发现findOne()方法报错了,不能用来当作根据id查询了. 当 ...
- spring boot: thymeleaf模板引擎使用
spring boot: thymeleaf模板引擎使用 在pom.xml加入thymeleaf模板依赖 <!-- 添加thymeleaf的依赖 --> <dependency> ...
- Spring Boot中使用Spring-data-jpa让数据访问更简单、更优雅
在上一篇Spring中使用JdbcTemplate访问数据库中介绍了一种基本的数据访问方式,结合构建RESTful API和使用Thymeleaf模板引擎渲染Web视图的内容就已经可以完成App服务端 ...
- Spring 4 mvc+shiro+thymeleaf+JPA(Hibernate)+MySql eclipse项目模板
本模板基本配制为:spring 4.3.8+thymeleaf 3.0.3 +hibernate 5.5.5 + mysql 5.7 IDE:eclipse 运行环境为:Tomcat 8.0.28 项 ...
随机推荐
- Ubuntu 16.04下安装sublime Text的插件
Sublime Text是什么: 它是一款具有代码高亮.语法提示.自动完成且反应快速的编辑器软件,不仅具有华丽的界面,还支持插件扩展机制,用她来写代码,绝对是一种享受.相比于难于上手的Vim,浮肿沉重 ...
- flutter routes跳转
flutter可以通过push pop跳转到上一级或者下一级 基本push跳转方法 此时仍然有返回按钮 Navigator.push( context, MaterialPageRoute( buil ...
- CompletableFuture引入
一.Future介绍 Future以前我们如果有个方法action执行,比如去数据库中查询数据.上传一个文件等,这个方法执行10分钟,调用者就需要等10分钟.基于此,调用者可以先执行action,返回 ...
- malloc分配内存进行对齐的操作
昨天面试高通Linux Kernel,面试官考了一个malloc内存对齐的问题,我晚上的时候细细的想了一下,实在是学习的不到位. 有的时候真的应该感谢,像是Qt.Ubuntu Gcc的编译器,他们做的 ...
- Go(05)map介绍
原文地址: http://www.limerence2017.com/2019/06/11/golang06/ 基本用法 map同样也是引用类型,map在使用前需要通过make进行初始化,否则会报pa ...
- 盒模型 box-sizing 属性
css3增添了盒模型box-sizing属性,box-sizing属性值可以有下面三个值: content-box:默认值,让元素维持W3C的标准盒模型.元素的宽度/高度(width/height)( ...
- mycat是什么?你是怎么理解的?你们公司分库分表的分片规则是什么?搭建mycat环境常用的配置文件有哪些?
1.mycat是什么? 国内最活跃的.性能最好的开源数据库分库分表中间件 一个彻底开源的,面向企业应用开发的大数据库集群 支持事务.ACID.可以替代MySQL的加强版数据库 一个可以视为MySQL集 ...
- mnist数据集下载——mnist数据集提供百度网盘下载地址
mnist数据集是由深度学习大神 LeCun等人制作完成的数据集,mnist数据集也常认为是深度学习的“ Hello World!”. 官网:http://yann.lecun.com/exdb/mn ...
- 20191224 Spring官方文档(启动)
再学Spring 之前看过Spring教学视频,看过<Spring5高级编程>,但是对于Spring始终还是感觉差了一点,应该是底层没有学好,这次再学Spring,就是要将Spring底层 ...
- 创建可执行bin安装文件
[应用场景] 简化操作,对于有些安装操作而言,需要包含安装脚本和脚本需要的文件两部分,封装成可执行bin文件之后就只有一个安装包了. 代码保护,在很多情况下,我们并不希望用户可以直接接触到代码部分,这 ...