springboot

[内容总览]

Spring Boot简介

第一个Spring Boot项目

Spring Boot项目结构

@ServletComponentScan

Spring Boot 整合JSP

Spring Boot 整合Thymeleaf

Spring Boot 整合MyBatis完成CRUD

Spring Boot 中异常处理

Spring Boot 整合Junit

Spring Boot 项目打包部署

[随堂笔记]

 

一、 Spring Boot简介

基于Spring Framework实现的。Spring Boot就是对Spring框架再次封装。

以前我们的烦恼:

繁琐的XML

繁琐的Spring整合其他技术。

较麻烦的部署。

Spring Boot可以给我们带来什么?

XML配置。使用Spring4中自动配置功能实现。如果希望配置使用的是propertiesyml进行配置,但是大部分都不需要进行配置,大部分都有默认值。

全生态的启动器。以后整合一个技术,基本上主流技术都有starter(启动器),只要依赖这个jar就可以使用这个技术。

SpringBoot绝大多数情况下就是一个jar,使用java -jar就可以运行这个项目。

Spring Boot内嵌Tomcat,打包后就会在jar中包含tomcat的内容。

二、 第一个Spring Boot项目

(spring boot 1.*版本spring4:兼容jdk1.8、2.*版本spring5:用jdk1.8版本写)

继承Spring Boot

继承过程和之前讲解Maven是同一个道理,让spring-boot-starter-parent作为父项目进行统一版本内容管理。

后面在引入时直接引入GroupId ArtifactId即可。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
</parent>

 

导入对应的启动器

Spring Boot 自己整合的内容都是以spring-boot-starter-xxx进行命名。而大部分第三方提供的启动器都是以xxx-spring-boot-starter进行命名。

spring-boot-starter:只包含了Spring Framework的启动器。

spring-boot-starter-web:包含了web,包含SpringMVC

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

 

新建启动类

启动类一定是在顶层包中。因为扫描当前类平级包及子包。

com.bjsxt包下新建任意名称的类。

@SpringBootApplication 表示当前类是SpringBoot的启动类。

/**
 * 自动扫描当前类同级包及子包中注解。
 */
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}

 

编写控制层代码

类应该在子包中。例如com.bjsxt.controller

@RestController
public class My {
@RequestMapping("/demo")
public String demo(){
return "demo";
}

}

 

启动启动类

运行MyApplication即可启动。

 

 

三、 SpringBoot整合Servlet

默认情况下,Spring Boot屏蔽了ServletFilterListener注解。如果希望开启在启动类中上添加@ServletComponentScan

在启动类上添加注解

@SpringBootApplication
@ServletComponentScan
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}

 

Servlet配置

@WebServlet

value是默认值,所以可以省略

urlPatterns配置多个映射路径。

@WebServlet("/servletdemo")
public class DemoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        writer.println("this is servlet");
        writer.flush();
        writer.close();
    }
}

 

Filter配置

@WebFilter /* 表示过滤所有

@WebFilter("/*")
public class DemoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        System.out.println(req.getRequestURI());
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

 

Listener

监听器负责监听整个web容器中对象的创建和销毁。当创建对象时调用contextInitialized,启动项目时执行该方法是因为application对象被创建。

@WebListener
public class DemoListen implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("执行了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

四、 MyBatis

导入依赖

数据库驱动没有放入到mybatis启动器中。因为驱动就是一个普通的jar不需要任何配置,导入即可,所以没有放入(不知道放那个数据库的驱动)

配置资源拷贝插件。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

编写配置文件

位置在src/main/resources下。名称应该叫做application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ego
spring.datasource.username=root
spring.datasource.password=root

 

10 在启动类中添加扫描包

@SpringBootApplication
@ServletComponentScan
@MapperScan("com.bjsxt.mapper")
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}

 

 

11 正常编码

正常编码,略

 

五、 SpringBoot项目的目录结构

SpringBoot项目中src/main/resources下有几个具有特定含义的隐藏文件夹,需要使用时自己手动创建。

static:放所有静态资源。所有当前文件夹中内容的访问路径为:/资源名称。每次新放静态资源时可以没有进行编译,无法访问,需要删除target

可以在static下放入favicon.ico作为整个项目图标的图片

public:放一些公共的资源。效果和static一样,只是含义上不同。

templates:不是SpringBoot自己的文件夹,而是Thymeleaf需要的目录。这个目录是受保护的,只能通过控制器转发才能访问。

 

六、 关于把Mapper.xml提到resources的步骤

为什么要提出来?

因为我们不希望配置资源拷贝插件,在SpringBootresources里面有很多具有特定含义的文件夹。

步骤

11.1 新建目录

src/main/resources下新建任意名称目录。例如叫做mybatis

 

文件夹中文件名称没有强制要求

11.2 配置配置文件

application.properties中添加下面内容。

mybatis.mapper-locations=classpath:mybatis/*Mapper.xml

 

如果mybatis中还有子文件夹可以使用**代表子文件夹。

mybatis.mapper-locations=classpath:mybatis/**/*Mapper.xml

 

七、 配置文件

Spring Boot可以使用application.properties还可以使用application.yml.

yml格式文件

类似于层次结构

 

yml文件中要注意的地方

每个属性独占一行

子属性要有缩进

取值不是等号而是冒号

每个冒号后面要有空格

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ego
    username: root
    password: root

mybatis:
  mapper-locations: classpath:mybatis/*Mapper.xml
  type-aliases-package: com.bjsxt.pojo

 

 

八、 Thymeleaf

thymeleaf是一个模板引擎技术。针对于html页面进行渲染。在html页面中通过属性进行动态控制。

Spring Boot官方推荐使用的视图技术为Thymeleaf

Thymeleaf更新速度较快。

社区较活跃。

完美支持HTML5.

Spring Boot中使用Thymeleaf是,所有Thymeleaf都放入到src/main/resources/templates中。

只需要在html页面中<html>添加命名空间

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

实现步骤:

11.3 添加thymeleaf启动器

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

11.4 创建目录

src/main/resources下新建templates文件夹。并在文件夹中新建页面。此页面必须通过控制器转发才能访问。

 

11.5 编写控制器

thymeleaf默认配置内容为

spring.thymeleaf.prefix=classpath:/templates/

spring.thymeleaf.suffix=.html

返回值demo最终结果为 prefix+demo+suffix= classpath:/templates/demo.html

@Controller
public class DemoController {
    @Autowired
    private PeopleService peopleService;
    @RequestMapping("/demo")
    public String demo(Model model,HttpServletRequest req) {
        model.addAttribute("list",peopleService.selectAll());//解耦方式
        //req.setAttribute("list",peopleService.selectAll());//紧耦方式
        return "demo";
    }
}

11.6 编写html页面

所有thymeleaf都是html标签属性。都是以th开头

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:each="peo : ${list}">
    <span th:text="${peo.id}"></span>
    <span th:text="${peo.name}"></span>
    <hr/>
</div>
</body>
</html>

 

九、 Thymeleaf常用属性

th:text

把内容填写进标签中

<!--没有${}表示固定字符串-->
<div th:text="abc"></div>
<!-- 取出作用域中值-->
<div th:text="${s}"></div>

 

12 session作用域取值

${# } #后面紧跟thymeleaf内置对象。

<!--从session作用域中取值  -->
<div th:text="${session.sess}"></div>
<div th:text="${#httpSession.getAttribute('sess')}"></div>

 

13 th:value

专门给表单对象设置value属性值。

<!--设置表单对象的value属性值-->
<input type="text" th:value="${session.sess}"/>

 

14 th:each

遍历时其中迭代变量s可以省略。其中p表示集合中每个元素对象。

s.count :1开始的序号

s.index:从0开始的序号

s.even:是否是偶数个,正常偶数行

s.odd:是否是奇数。

s.first:是否是第一个

s.last:是否是最后一个

<table border="1" width="500">
    <tr>
        <th>序号</th>
        <th>编号</th>
        <th>姓名</th>
    </tr>
    <tr th:each="p,s : ${list}">
        <td th:text="${s.count}"></td>
        <td th:text="${p.id}"></td>
        <td th:text="${p.name}"></td>
    </tr>
</table>

 

 

15 th:if

输出表格中奇数行

<table border="1" width="500">
    <tr>
        <th>序号</th>
        <th>编号</th>
        <th>姓名</th>
    </tr>
    <tr th:each="p,s : ${list}" th:if="${s.odd}">
        <td th:text="${s.count}"></td>
        <td th:text="${p.id}"></td>
        <td th:text="${p.name}"></td>
    </tr>
</table>

判断作用域中是否是指定内容

<div th:if="${s}=='字符串'">字符串</div>
<div th:if="${s}!='字符串'">不是字符串</div>

 

十、 异常处理

当出现异常时。SpringBoot显示的都是这个页面,注意状态码和异常信息

 

只需要在templates中新建error文件夹,在error中创建具体状态码或部分使用xx代替的文件。

如果状态码没有对应页面执行/templates/error.html

 

十一、 SpringBoot整合单元测试Junit

通过一个public void xxx()方法进行验证程序中任意一个方法或变量是否能正确执行。

 

 

添加启动器

 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

 

 

 

 

编写测试类

 

在src/main/test里面新建com.bjsxt.MyTest

 

注意:

 

1. 测试类不能叫做Test

 

2. 测试方法必须是public

 

3. 测试方法返回值必须是void

 

4. 测试方法必须没有参数

 

//告诉SpringBoot使用哪个单元测试工具
@RunWith(SpringJUnit4ClassRunner.class)
//当前类为测试类,classes指定哪个类为启动类
@SpringBootTest(classes = MyApplication.class)
public class MyTest {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Test
    public void test(){
        User user = userMapper.selectById(1L);
        System.out.println(user);
        System.out.println(userService.test());
    }

}

 

 

 

 

 

 

十二、 SpringBoot项目打包部署。

 

因为SpringBoot内嵌了Tomcat,只要把SpringBoot项目打包成jar后,在任意配置了JDK环境的系统上通过java -jar 文件名进行运行。

 

步骤

 

必须保证项目中包含SpringBoot打包插件。pom.xml中检查

 

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
</build>

 

 

 

 

打包

 

点击IDEA右侧Maven -- > Lifecycle --> install

 

 

 

打包后的内容出现在target根目录

 

 

 

部署到服务器

 

2.1 部署到windows

 

把此jar粘贴到任意目录,示例粘贴到D根目录下

 

启动windows命令行。依次输入:

 

# d:

 

# java-jar 文件名.jar

 

 

 

也可以新建一个批处理文件,例如:run.bat,在文件中添加

 

d:

java -jar 文件名.jar

 

2.2 部署到linux

 

windows步骤一样。把jar上传到linux后放入到任意目录中,进入到jar所在目录后执行java -jar 文件.jar 就可以运行。

 

也可以在jar所在文件夹中新建一个文件,执行运行文件。

 

# vim startup.sh

 

文件中输入java -jar 文件.jar

 

# chmod a+x startup.sh

 

# ./startup

 

注意:Idea中项目要关闭。

 

posted @ 2019-11-11 15:49  Wzhh  阅读(156)  评论(0)    收藏  举报