Springboot的模块化使用

时间:2019-08-18
本文章向大家介绍Springboot的模块化使用,主要包括Springboot的模块化使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

摘要:层级依赖的体现、实现基础增删查改、改善编程习惯、配置文件的改变、thymeleaf替代jsp、拦截器和过滤器

1、建立springboot父工程

artfactid:springbootDemo2---->由于要作为父工程,我们不再需要parent标签,有的话就删掉,再找到下面的标签,

加入<packaging>pom</packaging>

1 <groupId>com.aaa.liu.springboot</groupId>
2     <artifactId>springbootDemo2</artifactId>
3     <!--添加pom-->
4     <packaging>pom</packaging>
5 
6     <version>1.0-SNAPSHOT</version>

 2、按照正常的流程开始在父工程的基础上新建module:springboot-mapper  springboot-model   springboot-service   springboot-web  springboot-common

再依次添加工程依赖,组成层次依赖的关系,,将所需要用到的jar包放入父工程的mxl中,并用dependencyManage管理:

 1 <dependencyManagement>
 2         <dependencies>
 3 
 4             <dependency>
 5                 <groupId>org.springframework.boot</groupId>
 6                 <artifactId>spring-boot-starter-parent</artifactId>
 7                 <version>1.5.22.RELEASE</version>
 8             </dependency>
 9 
10             <dependency>
11                 <groupId>org.springframework.boot</groupId>
12                 <artifactId>spring-boot-starter-web</artifactId>
13                 <version>1.5.22.RELEASE</version>
14             </dependency>
15 
16             <dependency>
17                 <groupId>org.springframework.boot</groupId>
18                 <artifactId>spring-boot-starter-thymeleaf</artifactId>
19                 <version>1.5.22.RELEASE</version>
20             </dependency>
21 
22             <dependency>
23                 <groupId>net.sourceforge.nekohtml</groupId>
24                 <artifactId>nekohtml</artifactId>
25                 <version>1.9.21</version>
26             </dependency>
27 
28             <dependency>
29                 <groupId>org.mybatis.spring.boot</groupId>
30                 <artifactId>mybatis-spring-boot-starter</artifactId>
31                 <version>1.3.0</version>
32             </dependency>
33 
34             <dependency>
35                 <groupId>mysql</groupId>
36                 <artifactId>mysql-connector-java</artifactId>
37                 <version>5.1.6</version>
38             </dependency>
39         </dependencies>
40     </dependencyManagement>

所有的子工程根据自身需要重写父工程中的依赖(不带版本号),有时可能会出现不带版本号的情况下不好使,那就带上,怎么好使怎么来!

注意1.每次新建项目之后看一下setting中的maven路径是否正确,不正确的话及时更改!

   2.在添加依赖的时候时刻注意idea右侧maven模块中的dependency是否出现错误,如果出现错误,及时更换jar包或重写依赖!

   3.如果jar包下载下来了,但由于网速等原因,jar包不完整以至于出现错误,先将正在运行的项目停掉(不然jar包正在使用,无法删除),注释掉依赖,去仓库中删除错误的jar包,

   再将依赖重写注释回来,让它重新下载!

3、在各个层分别写上基本的方法等,无论 是哪一个框架配置信息,全部都要写在web项目中,最终web项目是需要打包运行的,如果加载不到配置信息的情况下,则会报错!

4、配置springmvc的UTF-8编码集、配置springmvc的json格式化、配置springmvc的拦截器

 使用@SpringBootApplication注解,把创建出SpringMVCConfig标识成配置类

 1 package com.aaa.liu.springboot.config;
 2 
 3 import org.springframework.boot.autoconfigure.SpringBootApplication;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.http.converter.StringHttpMessageConverter;
 6 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
 7 
 8 import java.nio.charset.Charset;
 9 
10 /**
11  * @Author 刘其佳
12  * 2019/8/16 -- 21:36
13  * @Version 1.0
14  */
15 
16 //使用SpringBooApplication注解将此类标识成配置类
17 @SpringBootApplication
18 public class SpringmvcConfig {
19 
20     /**
21      * 配置springmvc的utf-8编码集处理
22      * @return
23      */
24     @Bean
25     public StringHttpMessageConverter stringHttpMessageConverter(){
26         StringHttpMessageConverter converter=new StringHttpMessageConverter(Charset.forName("UTF-8"));
27         return converter;
28     }
29 
30     /**
31      * 配置springmvc的json格式化
32      * @return
33      */
34     public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
35         MappingJackson2HttpMessageConverter converter=new MappingJackson2HttpMessageConverter();
36         converter.setPrettyPrint(true);
37         return converter;
38 }
39 }

5、通过Mapper.xml的形式实现Mapper接口,需要在application.properties文件中进行配置mybatis

 1 # 配置Tomcat
 2 server.port=8081
 3 server.context-path=/
 4 # 配置数据源
 5 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 6 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
 7 spring.datasource.username=root
 8 spring.datasource.password=123456
 9 # 配置mybatis
10 # 给Mapper.xml需要返回的实体类取别名
11 mybatis.type-aliases-package=com.aaa.liu.springboot.model
12 # 配置mapper.xml的映射,支持通配符
13 mybatis.mapper-locations=classpath:mapper/*Mapper.xml

6、@MapperScan(“com.aaa.liu.springboot.mapper”):配置注解扫描(配置过后,mapper层就不用再添加Mapper注解)

 1 package com.aaa.liu.springboot;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 
 7 /**
 8  * @Author 刘其佳
 9  * 2019/8/16 -- 19:33
10  * @Version 1.0
11  */
12 
13 @SpringBootApplication
14 @MapperScan("com.aaa.liu.springboot.mapper")
15 public class ApplicationRun {
16     public static void main(String[] args) {
17         SpringApplication.run(ApplicationRun.class,args);
18     }
19 }

7、在spring boot官网中很明确的表明,如果使用springboot作为架构的话,默认不支持jsp,如果非要使用jsp,可以手动加载配置,

实现js,  springboot默认支持thymeleaf模板,这个模板也是Java写的,使用非常方便,相当于jsp;

  7.1.使用springboot支持thymeleaf模板的情况下,在开发阶段需要关闭thymeleaf的缓存,

    在application.properties中进行配置:spring.thymeleaf.cache=false

  7.2.添加thymeleaf的依赖:

    springboot已将完整的把thymeleaf集成进框架中了,可以直接添加使用不需要任何配置信息

1 <dependency>
2                 <groupId>org.springframework.boot</groupId>
3                 <artifactId>spring-boot-starter-thymeleaf</artifactId>
4                 <version>1.5.22.RELEASE</version>
5             </dependency>

  7..3.在springboot的官网描述如果使用thymeleaf作为HTML页面的情况下,默认springboot是在resources(classpath)下templates文件夹中进行加载创建templates文件夹

  7.4.如果使用thymeleaf需要更换HTML头部信息

 <html lang="en">
            替换
            <html xmlns="http://www.w3.org/1999/xhtml"
              xmlns:th="http://www.thymeleaf.org"
              xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

  7.5.thymeleaf是一个非常严谨的模板,和普通的HTML不一样,需要严格按照HTML标准来实现,如果不按照HTML的标准就会报错;

    且注意:<meta charset="utf-8">  是一个为闭合的标签。

    如果觉得标准过于严格,也可以不遵循HTML标准化实现thymeleaf。

      1、需要在application.properties文件中进行配置:

1 # 配置thymeleaf模板(不配置也可以,直接使用)
2 # 配置thymeleaf缓存:默认值true,需要手动修改为false
3 spring.thymeleaf.cache=false
4 # 配置不严谨的html
5 spring.thymeleaf.mode=LEGACYHTML5

      2、需要导入jar包

1 <dependency>
2                 <groupId>net.sourceforge.nekohtml</groupId>
3                 <artifactId>nekohtml</artifactId>
4                 <version>1.9.21</version>
5             </dependency>

7.6.thymeleaf的使用例子:

用户登录页面login.html——登录成功后查询数据并放入index.html页面——在页面上有增加、修改以及删除按钮:

login.html:

1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml"
 3       xmlns:th="http://www.thymeleaf.org"
 4       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
 5 <head>
 6     <meta charset="UTF-8">
 7     <title>Login</title>
 8 </head>
 9 <body>
10 <form action="login" method="post">
11     Username:<input type="text" name="username" /> <br />
12     Password:<input type="password" name="password" /> <br />
13     <input type="submit" value="Submit" />
14 </form>
15 </body>
16 </html>

index.html:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml"
 3       xmlns:th="http://www.thymeleaf.org"
 4       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
 5 <head>
 6     <meta charset="UTF-8">
 7     <title>Index</title>
 8 </head>
 9 <body>
10     <table border="1px solid black">
11         <thead>
12             <tr>
13                 <th>图书编号</th>
14                 <th>图书名称</th>
15                 <th>图书价格</th>
16                 <th>操作</th>
17             </tr>
18         </thead>
19         <tbody>
20             <tr th:each="book:${bookList}">
21                 <td th:text="${book.id}"></td>
22                 <td th:text="${book.bookName}"></td>
23                 <td th:text="${book.bookPrice}"></td>
24                 <td><a th:href="@{update(id=${book.id})}">修改</a> &nbsp;&nbsp;|&nbsp;&nbsp;<a th:href="@{deleteBook(id=${book.id})}">删除</a></td>
25             </tr>
26         </tbody>
27     </table>
28 <a href="insert">添加</a>
29 </body>
30 </html>

insert.html:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml"
 3       xmlns:th="http://www.thymeleaf.org"
 4       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
 5 <head>
 6     <meta charset="UTF-8">
 7     <title>添加页面</title>
 8 </head>
 9 <body>
10 <form action="addBook" method="post">
11 <table>
12     <tr>
13         <td>书名</td>
14         <td><input type="text" name="bookName" placeholder="请输入书名"/></td>
15     </tr>
16     <tr>
17         <td>价格</td>
18         <td><input type="text" name="bookPrice" placeholder="请输入价格"/></td>
19     </tr>
20     <tr>
21         <td><input type="submit" value="Submit"/></td>
22     </tr>
23 </table>
24 </form>
25 </body>
26 </html>

update.html:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml"
 3       xmlns:th="http://www.thymeleaf.org"
 4       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
 5 <head>
 6     <meta charset="UTF-8">
 7     <title>修改页面</title>
 8 </head>
 9 <body>
10 <form action="updateBook" method="post">
11     <table>
12         <tr>
13             <td>编号</td>
14             <td><input type="text" name="id" th:value="${bookId}"/></td>
15         </tr>
16         <tr>
17             <td>书名</td>
18             <td><input type="text" name="bookName" th:placeholder="${bookName}"/></td>
19         </tr>
20         <tr>
21             <td>价格</td>
22             <td><input type="text" name="bookPrice" th:placeholder="${bookPrice}"/></td>
23         </tr>
24         <tr>
25             <td><input type="submit" value="Submit"/></td>
26         </tr>
27     </table>
28 </form>
29 </body>
30 </html>

404.html:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml"
 3       xmlns:th="http://www.thymeleaf.org"
 4       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
 5 <head>
 6     <meta charset="UTF-8">
 7     <title>404</title>
 8 </head>
 9 <body>
10     <h1>This is 404 Page!!!!</h1>
11 </body>
12 </html>

controller:

  1 package com.aaa.liu.springboot.controller;
  2 
  3 import com.aaa.liu.springboot.model.Book;
  4 import com.aaa.liu.springboot.model.User;
  5 import com.aaa.liu.springboot.service.BookService;
  6 import com.aaa.liu.springboot.service.UserService;
  7 import com.aaa.liu.springboot.service.UserServiceImpl;
  8 import org.springframework.beans.factory.annotation.Autowired;
  9 import org.springframework.stereotype.Controller;
 10 import org.springframework.ui.Model;
 11 import org.springframework.ui.ModelMap;
 12 import org.springframework.web.bind.annotation.PathVariable;
 13 import org.springframework.web.bind.annotation.RequestMapping;
 14 
 15 import javax.servlet.http.HttpServletRequest;
 16 import java.util.List;
 17 import java.util.Map;
 18 
 19 /**
 20  * @Author 刘其佳
 21  * 2019/8/16 -- 23:43
 22  * @Version 1.0
 23  */
 24 @Controller
 25 public class LoginController {
 26     @Autowired
 27     private UserService userService;
 28     @Autowired
 29     private BookService bookService;
 30 
 31     /**
 32      * 跳转登录页面
 33      * @return
 34      */
 35     @RequestMapping("/")
 36     public String turnLoginPage(){
 37         return "login";
 38     }
 39 
 40     /**
 41      * 登陆方法:登录成功后重定向
 42      * @param user
 43      * @param request
 44      * @param model
 45      * @return
 46      */
 47     @RequestMapping("/login")
 48     public String login(User user, HttpServletRequest request, Model model){
 49         Map<String,Object> resultMap=userService.login(user,request);
 50         if(200==(Integer)resultMap.get("code")){
 51             User user1= (User) resultMap.get("result");
 52             model.addAttribute("user",user1);
 53             return "redirect:/turnIndexPage";
 54         }else {
 55             return "404";
 56         }
 57     }
 58 
 59     /**
 60      * 跳转至查询方法
 61      * @param modelMap
 62      * @return
 63      */
 64     @RequestMapping("/turnIndexPage")
 65     public String turnIndexPage(ModelMap modelMap){
 66         //需求是查询所有的图书信息
 67     Map<String,Object> resultMap=bookService.selectAll();
 68     List<Book> bookList= (List<Book>) resultMap.get("result");
 69     if(200==(Integer) resultMap.get("code")){
 70         modelMap.addAttribute("bookList",bookList);
 71         return "index";
 72     }
 73    return "404";
 74     }
 75 
 76     /**
 77      * 添加按钮跳转至添加页面
 78      * @return
 79      */
 80     @RequestMapping("/insert")
 81     public String insert(){
 82         return "insert";
 83     }
 84     /**
 85      * 进行添加图书
 86      * @param bookName
 87      * @param bookPrice
 88      * @return
 89      */
 90     @RequestMapping("/addBook")
 91     public String addBook(String bookName, Double bookPrice){
 92          Map<String,Object> resultMap=bookService.addBook(bookName,bookPrice);
 93          if(200==(Integer) resultMap.get("code")){
 94              return "redirect:/turnIndexPage";
 95             }
 96             return "404";
 97     }
 98 
 99     /**
100      * 执行修改操作,并返回查询页面
101      * @param id
102      * @param model
103      * @return
104      */
105     @RequestMapping("/update")
106     public String update( Integer id,Model model){
107         //根据id进行查询,并将数据放入修改页面table中
108         Map<String, Object> resultMap = bookService.selectById(id);
109         List<Book> bookList= (List<Book>) resultMap.get("result");
110         if(200==(Integer) resultMap.get("code")){
111             Book book = bookList.get(0);
112             int bookId=book.getId();
113             String bookName = book.getBookName();
114             Double bookPrice = book.getBookPrice();
115             model.addAttribute("bookId",bookId);
116             model.addAttribute("bookName",bookName);
117             model.addAttribute("bookPrice",bookPrice);
118             return "update";
119         }
120         return "404";
121     }
122 
123     /**
124      * 删除
125      * @param id
126      * @param bookName
127      * @param bookPrice
128      * @return
129      */
130     @RequestMapping("/updateBook")
131     public String updateBook(Integer id,String bookName,Double bookPrice){
132         Book book=new Book(id,bookName,bookPrice);
133         System.out.println(book);
134         Map<String, Object> resultMap = bookService.updateBook(book);
135         if(200==(Integer) resultMap.get("code")){
136             return "redirect:/turnIndexPage";
137         }else {
138             return "404";
139         }
140     }
141 
142     /**
143      * 执行删除,并返回删除页面
144      * @param id
145      * @return
146      */
147     @RequestMapping("/deleteBook")
148     public String deleteBook(Integer id){
149         Map<String, Object> resultMap = bookService.deleteBook(id);
150         if(200==(Integer)resultMap.get("code")){
151             return "redirect:/turnIndexPage";
152         }else {
153             return "404";
154         }
155     }
156 }

拦截器的配置:在web工程下创建一个interceptor包:

 1 package com.aaa.liu.springboot.interceptor;
 2 
 3 import org.springframework.boot.autoconfigure.SpringBootApplication;
 4 import org.springframework.web.servlet.HandlerInterceptor;
 5 import org.springframework.web.servlet.ModelAndView;
 6 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 8 
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 /**
13  * @Author 刘其佳
14  * 2019/8/16 -- 22:06
15  * @Version 1.0
16  */
17 
18 @SpringBootApplication
19 public class LoginInterceptor extends WebMvcConfigurerAdapter {
20     @Override
21     public void addInterceptors(InterceptorRegistry registry) {
22         //添加自定义的拦截器,并添加路径
23         registry.addInterceptor(loginInterceptor()).addPathPatterns("/**");
24     }
25 
26     //在类的内部自定义拦截器
27     private HandlerInterceptor loginInterceptor(){
28         //实例化接口
29         HandlerInterceptor handlerInterceptor=new HandlerInterceptor() {
30             public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
31                 System.out.println("我是拦截器,我被访问了!!!");
32                 return true;
33             }
34 
35             public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
36 
37             }
38 
39             public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
40 
41             }
42         };
43         return handlerInterceptor;//将拦截器扔出
44     }
45 }

原文地址:https://www.cnblogs.com/liuqijia/p/11369422.html