pringBoot Thymeleaf模板 && 任務調度

SpringBoot 靜態資源訪問

什麼是靜態資源?

  • 靜態資源類型:html、css、js、image等
  • 動態資源類型:Servlet、JSP、Spring/Mybatis/Boot

SpringBoot對靜態資源管理

在SpringBoot工程中,有幾個默認約定的文件夾用於存放靜態資源信息。(src/main/resources/)

  • public 優先級最低
  • static
  • resources
  • META-INF/resources 優先級最高

可以自定義靜態資源目錄,方法如下:

@Configuration
public class ResourcesConfiguration extends WebMvcConfigurerAdapter{

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/mystatic/**")
            .addResourceLocations("classpath:/myresources/");
    }

}

Thymeleaf模板技術

模板簡介

velocity、freemark、thymeleaf技術都屬於模板技術。

SpringBoot默認支持thymeleaf技術。

模板技術優點:

  • 執行效率高於JSP
  • 模板技術單一,易學、易用

 

SpringBoot Thymeleaf應用

thymeleaf模板技術,模板文件擴展名爲.html,頁面中需要使用th:xx表達式。編寫時HTML模板頁面,語法要求追加xmlns:th定義然後在使用th表達式。

<html xmlns:th="http://www.thymeleaf.org"> xxx xxx

模板中的html標記比較嚴格,有開始和結束匹配。

SpringBoot有一個templates文件,是默認存放html模板文件位置。

案例1:Hello World

  1. 在pom.xml中追加thymeleaf定義

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. 在src/main/resources目錄下添加templates文件夾並追加hello.html模板文件

    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>thymeleaf示例</title>
        </head>
        <body>
            <h1 th:text="${msg}"></h1>
        </body>
    </html>
    
  3. 定義HelloController,將消息放入Model中

    @Controller
    public class HelloController {
    
        @RequestMapping("/hello1.do")
        public ModelAndView hello1(){
            ModelAndView mav = new ModelAndView();
            mav.setViewName("hello");
            mav.getModel().put("msg", "Hello Thymeleaf!");
            return mav;
        }
    
        @RequestMapping("/hello2.do")
        public ModelAndView hello2(){
            ModelAndView mav = new ModelAndView();
            mav.setViewName("hello");
            mav.getModel().put("msg", "你好模板技術!");
            return mav;
        }
    
    }
    

案例2:列表顯示

  1. ListController

    @Controller
    public class ListController {
    
        @RequestMapping("/list.do")
        public ModelAndView list(){
            ModelAndView mav = new ModelAndView();
            mav.setViewName("list");//templates/list.html
    
            List<City> list = new ArrayList<City>();
            list.add(new City(1,"北京"));
            list.add(new City(2,"上海"));
            list.add(new City(3,"廣州"));
            list.add(new City(4,"深圳"));
    
            mav.getModel().put("cities", list);
            return mav;
        }
    
    }
    
  2. list.html模板文件

    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>thymeleaf示例</title>
    </head>
    <body>
        <h1>列表顯示</h1>
        <table>
            <tr>
                <td>編號</td>
                <td>名稱</td>
            </tr>
            <tr th:each="c:${cities}">
                <td th:text="${c.id}"></td>
                <td th:text="${c.name}"></td>
            </tr>
        </table>
        <select>
            <option th:each="c:${cities}" th:value="${c.id}" th:text="${c.name}"></option>
        </select>
    </body>
    

案例3:重構列表分頁案例

  1. 在pom.xml追加mybatis、jdbc等定義

     <!-- jdbc -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    
    <!-- mybatis-spring -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.2.2</version>
    </dependency>
    
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.2.3</version>
    </dependency>
    
    <!-- ojdbc6 -->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.3</version>
    </dependency>
    
  2. 在application.properties追加數據庫參數定義

    spring.datasource.username=SCOTT
    spring.datasource.password=TIGER
    spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
    spring.datasource.driverClassName=oracle.jdbc.OracleDriver
    
  3. 定義實體類Book.java

  4. 定義Mapper接口BookDao.java

    public interface BookDao {
    
        @Select("select * from xdl_book")
        public List<Book> findAll();
    
        @Select("select * from xdl_book where id=#{id}")
        public Book findById(int id);
    
        @Delete("delete from xdl_book where id=#{id}")
        public int deleteById(int id);
    
        @Update("update xdl_book set author=#{author,jdbcType=VARCHAR},publishing=#{publishing,jdbcType=VARCHAR},publish_time=#{publish_time,jdbcType=DATE},isbn=#{isbn,jdbcType=VARCHAR},total_page=#{total_page,jdbcType=NUMERIC},book_summary=#{book_summary,jdbcType=VARCHAR} where id=#{id}")
        public int update(Book book);
    
        @Insert("insert into xdl_book (id,author,publishing,publish_time,total_page,book_summary) values (xdl_book_id_seq.nextval,#{author},#{publishing},#{publish_time},#{total_page},#{book_summary})")
        public int save(Book book);
    
    }
    
  5. 在主啓動類前追加@MapperScanner標記

    @SpringBootApplication
    @MapperScan(basePackages={"cn.xdl.dao"})
    public class BootApplication {
    
        public static void main(String[] args){
            SpringApplication.run(BootApplication.class, args);
        }
    }
    
  6. 定義BookController

    @Controller
    public class BookController {
    
        @Autowired
        private BookDao bookDao;
    
        @RequestMapping("/book/page/{p}")
        public ModelAndView list(@PathVariable("p")int p){
            ModelAndView mav = new ModelAndView();
            mav.setViewName("book");
    
            Page page = PageHelper.startPage(p,3);
            List<Book> list = bookDao.findAll();
            int totalPage = page.getPages();
            mav.getModel().put("books", list);
            mav.getModel().put("totalPage", totalPage);
            mav.getModel().put("currentPage", p);
            return mav;
        }
    
        @RequestMapping("/book/{id}/delete")
        public ModelAndView delete(@PathVariable("id")int id){
            bookDao.deleteById(id);
            ModelAndView mav = new ModelAndView();
            RedirectView view = new RedirectView("/book/page/1");
            mav.setView(view);
            return mav;
        }
    
    
    }
    
  7. 在templates/下定義book.html模板文件

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <base href="/"/>
        <meta charset="UTF-8"/>
        <title>Insert title here</title>
        <!-- 新 Bootstrap 核心 CSS 文件 -->
        <link  rel="stylesheet" href="js/bootstrap.min.css"/>
    
        <!-- jQuery文件。務必在bootstrap.min.js 之前引入 -->
        <script type="text/javascript" src="js/jquery.min.js"></script>
    
        <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
        <script type="text/javascript" src="js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <h1>圖書列表</h1>
    
        <button class="btn btn-info">新增</button>
        <table id="tb_book" class="table table-striped table-hover">
            <tr class="danger">
                <td>序號</td>
                <td>作者</td>
                <td>出版社</td>
                <td>出版時間</td>
                <td>總頁數</td>
                <td>操作</td>
            </tr>
            <tr th:each="book,stat:${books}">
                <td th:text="${stat.count}"></td>
                <td th:text="${book.author}"></td>
                <td th:text="${book.publishing}"></td>
                <td th:text="${book.publish_time}"></td>
                <td th:text="${book.total_page}"></td>
                <td>
                    <a class="btn btn-danger" href="#">刪除</a>
                </td>
            </tr>
    
        </table>
        <div id="pages">
    
        <a th:each="p:${#numbers.sequence(1,totalPage)}" 
            th:text="${p}" class="btn btn-warning" 
            th:href="@{'book/page/'+${p}}"></a>
    
        </div>
    </div>
    </body>
    </html>
    
  8. 將jquery.js、css等文件放入static或public等靜態資源目錄下

  9. 禁用thymeleaf中HTML模板校驗

    • 在pom.xml中追加nekohtml定義

      <dependency>
        <groupId>net.sourceforge.nekohtml</groupId>
        <artifactId>nekohtml</artifactId>
      </dependency>
      
    • 在application.properties追加參數

      spring.thymeleaf.mode=LEGACYHTML5
      

SpringBoot AOP

  1. 在pom.xml中追加spring-boot-starter-aop定義

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. 編寫切面組件追加@Aspect、@Around定義

    @Component
    @Aspect
    public class WatchBean {
    
        @Around("within(cn.xdl.controller.*)")
        public Object execute(ProceedingJoinPoint pjp) throws Throwable{
            //追加前面邏輯
            StopWatch watch = new StopWatch();
            watch.start();
            Object obj = pjp.proceed();//執行目標方法,獲取返回結果
            watch.stop();
            long time = watch.getTotalTimeMillis();//執行時間
            String method = pjp.getSignature().getName();//目標方法名
            //追加後面邏輯
            System.out.println(method+"方法執行了"+time+"ms");
            return obj;
        }
    
    }
    

SpringBoot任務調度

啓動服務器立刻調用任務

SpringBoot提供了CommandLineRunner和ApplicationRunner接口,程序猿可以實現接口及其方法,將啓動任務寫到方法中。

  1. 使用CommandLineRunner

    @Component
    @Order(1)
    public class Task1Bean implements CommandLineRunner{
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("啓動服務器自動執行任務1");
        }
    
    }
    
  2. 使用ApplicationRunner

    @Component
    @Order(2)
    public class Task2Bean implements ApplicationRunner{
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println("啓動服務器自動執行任務2");
        }
    
    }
    

    可以通過@Order標記定義任務執行順序。

週期性定時調用任務

可以在服務器啓動後,指定時間或週期調用執行任務處理。
  1. 定義任務類,類和方法定義沒有限制

    @Component//掃描 @EnableScheduling//啓用任務計劃調度 public class Task3Bean {

    @Scheduled(cron="0/5 * * * * ?")
    public void execute(){
        System.out.println("週期調用Task3任務:"+new Date());
    }
    

    }

  2. 根據需求指定@EnableScheduling和@Scheduled

  3. 編寫cron表達式,參考下面資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章