SpringBootMVC02——SpringDataJpa与ThymeLeaf
阅读原文时间:2023年07月10日阅读:2

大纲

- SpringDataJpa进阶使用
- SpringDataJpa自定义查询
- 整合Servlet、Filter、Listener
- 文件上传
- Thymeleaf常用标签

注解方式

启动类上添加注解

@SpringBootApplication
== @ServletComponentScan ==

public class Springboot011Application {

  public static void main(String[] args) {
    SpringApplication.run(Springboot011Application.class, args);
  }

}

@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);  
}

}

启动类中添加

  @Bean
public ServletRegistrationBean getServletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean<>(new MyServlet2(), "/s2");
bean.setLoadOnStartup();
return bean;
}

这种方式在Servlet中无需注解

需要implements Filter

实现接口 ServletContextListener

需要MyListener implements ServletContextListener

可以把静态文件放到以下工程目录下

- src/main/resources/static
- src/main/webapp

参数接收

@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;
}

@RequestMapping("/fileUploadController")  
public String fileUpload(MultipartFile filename) throws Exception{  
    System.out.println(filename.getOriginalFilename());  
    filename.transferTo(new File("e:/"+filename.getOriginalFilename()));  
    return "ok";  
}

官方文档:

https://docs.spring.io/spring-data/jpa/docs/2.1.8.RELEASE/reference/html/

public interface AccountRepository extends JpaRepository

application.properties 中配置``` spring.jpa.show-sql=true ```

关键字 意义
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 userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;
NotIn 等价于 SQL 中的 "not in",比如 findByUsernameNotIn(Collection userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;

public interface UserDao extends Repository {

@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 findByBalanceGreaterThan(Integer balance,Pageable pageable);
}

public interface UserDao extends Repository {

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);  

}

@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 {

@Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}

## Eclipse自动提示插件

官方文档

https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#base-objects

安装地址:

http://www.thymeleaf.org/eclipse-plugin-update-site/

Html中添加约束

```html

```

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

)``` ```

@ 以 "/" 开头定位到项**目根路径**,否则使用相对路径

th:href

```html
、@{userList(id=)} 、@{userList(id=,name=yoyo)} 、@{userList(id=,name=${userName})}

```

th:text 文本

空格属于特殊字符,必须使用单引号包含整个字符串

``` html

样式

中国

userName

temp


```

数字计算

``` html

+

+ +' Love '++

+ +' Love '+(+)


```

Boolean判断

``` html

布尔

true and true

已结婚

已成年

未成年


```

运算

``` html

值为

值为

值为


```

比较

```html

大于

大于

10大于等于8,且 不等于

!false

not(false)


```

三元运算符

```html

三元运算符

已婚


```

th:utext转义

```html
map .addAttribute("china", "Chian,USA,UK");

默认转义

不会转义


```

th:attr 设置属性

HTML5 所有的属性,都可以使用 th:* 的形式进行设置值
```html
百度
```
html属性设置
```html

前往百度
设置 href 属性
用户首页
设置 id 属性,data-target 属性 Html 本身是没有的,但允许用户自定义
归海一刀

th:abc=""

th:xxoo="yoyo"

```

Checked selected

Checked

```html
是否已婚1?
是否已婚2?

后台传值 : model.addAttribute("isMarry", true);

是否已婚?
是否已婚?
是否已婚?

```

select autofocus

``` html



```

日期格式化

<span th:text="${#dates.format(date, 'yyyy-MM-dd HH:mm')}"></span>  

循环

JSTL 有一个 **c:foreach**,同理 Thymeleaf 也有一个 th:each。

作用都是一样的,都是用于遍历数组、List、Set、Map 等数据。
在Select上循环

```html

```

状态变量 loopStatus

如果不指定 为变量 **Stat**

  • index: 当前迭代对象的index(从0开始计算)
  • count: 当前迭代对象的index(从1开始计算)
  • size: 被迭代对象的大小 current:当前迭代变量
  • even/odd: 布尔值,当前循环是否是偶数/奇数(从0开始计算)
  • first: 布尔值,当前循环是否是第一个

- last: 布尔值,当前循环是否是最后一个

```html

```

逻辑判断

If/else

```html

已婚1

未婚

```

Switch/case 多条件判断

``` html

管理员

操作员

未知用户

管理员

操作员

未知用户

已婚

已成年

未婚

美国

英国

中国

未知国籍

```

内联表达式

[[…]] 等价于 th:text(结果将被 HTML 转义),[(…)] 等价于 th:utext(结果不会执⾏HTML转义)
```html

\[\[${china}\]\]

\[(${china})\]

\[\[Lo1ve\]\]

\[\['I Love You Baby'\]\]

\[()\]


```
禁⽤内联th:inline ="none"

内联 JavaScript

```javascript


```

前后端分离开发

```javascript


```

Servlet作用域中的对象属性

URL/request

```html

${param.size()}=\[\[${param.size()}\]\]

${param.id}=\[\[${param.id}\]\]


```

Session

```html

${session.size()}=\[\[${session.size()}\]\]

${session.user.id}=\[\[${session.user.id}\]\]


```