1. 程式人生 > >SpringBoot+Thymeleaf+JPA的基本使用

SpringBoot+Thymeleaf+JPA的基本使用

專案屬性配置

application.yml檔案

#cupSize: CD
#age: 18
#content: "cupSize: ${cupSize},age: ${age}"  #在當前配置裡面再使用配置
#
#girl:
#  cupSize: C
#  age: 20

  spring:
    profiles:
      active: dev   #使用dev這個配置,區分生產環境和開發環境

resources目錄下新建application-dev.yml檔案代表開發環境

server:
  port: 8081
  servlet:
    #context-path: "/url"
cupSize: CD age: 18 content: "cupSize: ${cupSize},age: ${age}" #在當前配置裡面再使用配置 girl: cupSize: C age: 20

resources目錄下新建application-prod.yml檔案代表生產環境,可以使用和開發環境不一樣的配置

server:
  port: 8081
  servlet:
    #context-path: "/url"

cupSize: CD
age: 18
content: "cupSize: ${cupSize},age: ${age}"  #在當前配置裡面再使用配置
girl: cupSize: C age: 20

GirlProperties類

@Component //如果使用@Autowired還需要使用@Component
@ConfigurationProperties(prefix = "girl")   //字首屬性是girl的對映到這個類
public class GirlProperties {
    private String cupSize;

    private Integer age;

    public String getCupSize() {
        return cupSize;
    }

    public
void setCupSize(String cupSize) { this.cupSize = cupSize; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }

注入屬性到類GirlProperties中

   @Value("${cupSize}")
    private String cupSize; //通過註解將配置檔案裡面的屬性注入到此

    @Value("${age}")
    private Integer age;

    @Value("${content}")
    private String content;

    @Autowired
    private GirlProperties girlProperties;
    
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String sayHi() {
        return girlProperties.getCupSize();
    }

@RestController

spring4之後新加的註解,原來返回json需要@ResponseBody配合@Controller

Controller和Thymeleaf模板的使用

1、第一步首先需要在pom.xml中配置Thymeleaf依賴

		<!--thymeleaf模板-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

2、在application.yml檔案中增加thymeleaf配置

#thymelea模板配置
    thymeleaf:
      prefix: classpath:/templates/
      suffix: .html
      mode: HTML5
      encoding: UTF-8
      servlet:
        content-type: text/html
      cache: false    #開發階段務必關閉快取

    resources:
      chain:
        strategy:
          content:
            enabled: true
            paths: /**

3、Controller的配置

/**
 * Created by wzh-zhua on 2018/9/30.
 */
//@RestController //spring4之後新加的註解,原來返回json需要@ResponseBody配合@Controller
 @Controller    //配合模板使用
public class HelloController {


    public String hello() {
        return "/index";
    }

      @RequestMapping(value = "hello",method = RequestMethod.GET)
      public ModelAndView index(ModelAndView mv) {
          mv.setViewName("/index");
          mv.addObject("title","歡迎使用Thymeleaf");
          return mv;
      }

}

4、在templates目錄下新建index.html檔案

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Spring</title>
</head>
<body>
<h1>hello wang</h1>
    <p th:text="'Hello, ' + ${title}" /><br/>

</body>
</html>

最後在瀏覽器中訪問http://localhost:8081/hello即可看到以下結果

在這裡插入圖片描述

Thymeleaf列表的使用

User.java

public class User {
    private int id;
    private String username;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

UserController.java

 @Controller
@RequestMapping("user")
public class UserController {

    //@RequestMapping(value = "/list", method = RequestMethod.GET)或者
    @GetMapping("list")
    public String listUser(Model model, @RequestParam(value = "id", required = false, defaultValue = "0") Integer id) {
        List<User> userList = new ArrayList<User>();

        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(i);
            user.setUsername("username" + i + i);
            userList.add(user);
        }

        model.addAttribute("users", userList);
        model.addAttribute("id", id);

        return "user/list";
    }

    //    @RequestMapping(value = "/list/{id}", method = RequestMethod.GET)
//    public String getUserID(@PathVariable("id") Integer id) {
//        return "id"+ id;
//    }


}

user/list.html檔案

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Spring</title>
</head>
<body>

<span th:text="'引數中的使用者id為'+${id}"></span>

<h2>使用者列表</h2>
<div>
    <ul>
        <li th:each="user:${users}">
            <p>ID:<span th:text="${user.id}"></span></p>
            <p>名字:<span th:text="${user.username}"></span></p>

        </li>
    </ul>
</div>


</body>
</html>

結果

在這裡插入圖片描述

JPA資料庫操作

JPA定義

1、pom.xml中配置JPA

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
</dependency>

2、

事務管理