文章目录

  • 1.3 第三章 Spring Boot 和 web 组件
    • 1.3.1 SpringBoot 中拦截器
    • 1.3.2 Spring Boot 中使用 Servlet
    • 1.3.3 Spring Boot 中使用 Filter
    • 1.3.4 字符集过滤器的应用
    • 1.3.5 在 application.properties 文件中设置过滤器
  • 1.4 第四章 ORM 操作 MySQL
    • 1.4.1 创建 Spring Boot 项目
    • 1.4.2 @MapperScan
    • 1.4.3 mapper 文件和 java 代码分开管理
    • 1.4.4 事务支持
  • 1.5 第五章 接口架构风格—RESTful
    • 1.5.1 认识 REST
    • 1.5.2 RESTful 的注解
    • 1.5.3 RESTful 优点
    • 1.5.4 注解练习
      • 1.5.4.1 编写 Controller
      • 1.5.4.2 使用 Postman 模拟发送请求,进行测试
      • 1.5.4.3 请求路径冲突
      • 1.5.4.4 RESTful 总结
  • 1.6 第六章 Spring Boot 集成 Redis
    • 1.6.1 项目之前需要安装配置好 Redis。
    • 1.6.2 需求实现步骤
      • 1.6.2.1 pom.xml
      • 1.6.2.2 核心配置文件 application.properties
      • 1.6.2.3 创建 RedisController
      • 1.6.2.4 启动 Redis 服务
      • 1.6.2.5 执行 Spring Boot Application 启动类
      • 1.6.2.6 使用 Postman 发送请求
      • 1.6.2.7 启动浏览器访问 Controller
      • 1.6.2.8 Redis Desktop Manager 桌面工具查看
  • 1.7 第七章 Spring Boot 集成 Dubbo
    • 1.7.1 创建接口 module
    • 1.7.2 服务提供者 module
    • 1.7.3 创建消费者 module
    • 1.7.4 测试应用
    • 1.7.5 SLF4j 依赖
  • 1.8 第八章 Spring Boot 打包
    • 1.8.1 Spring Boot 打包为 war
      • 1.8.1.1 pom.xml
      • 1.8.1.2 指定 jsp 文件编译目录
      • 1.8.1.3 打包后的 war 文件名称
      • 1.8.1.4 完整的 build 标签内容
      • 1.8.1.5 创建 webapp 目录
      • 1.8.1.6 创建 jsp 文件
      • 1.8.1.7 创建 JspWarController
      • 1.8.1.8 设置视图解析器
      • 1.8.1.9 启动主类,在浏览器访问地址 index
      • 1.8.1.10 主启动类继承 SpringBootServletInitializer
      • 1.8.1.11 指定项目 package 是 war
      • 1.8.1.12 maven package 打包
      • 1.8.1.13 发布打包后的 war 到 tomcat
    • 1.8.2 Spring Boot 打包为 jar
      • 1.8.2.1 pom.xml
      • 1.8.2.2 创建 webpp 目录
      • 1.8.2.3 创建 jsp 文件
      • 1.8.2.4 创建 HelloController
      • 1.8.2.5 application.properties
      • 1.8.2.6 启动 Application,在浏览器访问应用
      • 1.8.2.7 修改 pom.xml 增加 resources 说明
      • 1.8.2.8 必须 maven 插件版本
      • 1.8.2.9 执行 maven package
      • 1.8.2.10 执行 jar,启动内置的 tomcat
    • 1.8.3 Spring Boot 部署和运行方式总结

1.3 第三章 Spring Boot 和 web 组件

1.3.1 SpringBoot 中拦截器

SpringMVC 使用拦截器
1)自定义拦截器类,实现 HandlerInterceptor 接口
2)注册拦截器类

Spring Boot 使用拦截器步骤:
1. 创建类实现 HandlerInterceptor 接口

package com.bjpowernode.web;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {System.out.println("执行了 LoginInterceptor,preHandle()");return true;}
}

2. 注册拦截器对象

//相当于 springmvc 配置文件
@Configuration
public class MyAppConfig implements WebMvcConfigurer {//注册拦截器对象的@Overridepublic void addInterceptors(InterceptorRegistry registry) {// InterceptorRegistry 登记系统中可以使用的拦截器// 指定拦截的地址String path [] = {"/user/**"};String excludePath [] = {"/user/login"};registry.addInterceptor( new LoginInterceptor()).addPathPatterns(path).excludePathPatterns(excludePath);}
}

3. 创建测试使用的 Controller

@Controller
public class BootController {@RequestMapping("/user/account")@ResponseBodypublic String queryAccount(){return "user/account";}@RequestMapping("/user/login")@ResponseBodypublic String login(){return "/user/login";}
}

4. 主启动类

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

5. 启动主类, 运行浏览器
访问 user/account , user/login 观察拦截的输出语句

1.3.2 Spring Boot 中使用 Servlet

ServletRegistrationBean 用来做在 servlet 3.0+容器中注册 servlet 的功能,但更具有SpringBean 友好性。
实现步骤:

  1. 创建 Servlet
public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html;charset=utf-8");PrintWriter out = resp.getWriter();out.println("使用 Servlet 对象");out.flush();out.close();}
}
  1. 注册 Servlet
@Configuration
public class SystemConfig {@Beanpublic ServletRegistrationBean servletRegistrationBean(){/* ServletRegistrationBean reg = new ServletRegistrationBean();reg.setServlet( new MyServlet());reg.addUrlMappings("/myservlet");return reg;*/ServletRegistrationBean reg = new ServletRegistrationBean( new MyServlet(),"/loginServlet");return reg;}
}
  1. 主启动类
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

4.启动主类,在浏览器中访问 loginServlet

1.3.3 Spring Boot 中使用 Filter

FilterRegistrationBean 用来注册 Filter 对象
实现步骤:
1.创建 Filter 对象

public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest,ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("使用了 Servlet 中的 Filter 对象");filterChain.doFilter(servletRequest,servletResponse);}
}

2.注册 Filter

@Configuration
public class SystemConfig {@Beanpublic FilterRegistrationBean filterRegistrationBean(){FilterRegistrationBean reg = new FilterRegistrationBean();//使用哪个过滤器reg.setFilter( new MyFilter());//过滤器的地址reg.addUrlPatterns("/user/*");return reg;}
}

3.创建 Controller

@Controller
public class FilterController {@RequestMapping("/user/account")@ResponseBodypublic String hello(){return "/user/account";}@RequestMapping("/query")@ResponseBodypublic String doSome(){return "/query";}
}

4.启动应用, 在浏览器访问 user/account, /query 查看浏览器运行结果

1.3.4 字符集过滤器的应用

创建项目:014-springboot-character-filter
实现步骤:
1.创建 Servlet,输出中文数据

public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html");PrintWriter out = resp.getWriter();out.println("学习 Hello SpringBoot 框架,自动配置");out.flush();out.close();}
}

2)注册 Servlet 和 Filter

package com.bjpowernode.config;
import com.bjpowernode.servlet.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
@Configuration
public class SystemAppliationConfig {@Beanpublic ServletRegistrationBean servletRegistrationBean(){ServletRegistrationBean reg = new ServletRegistrationBean(new MyServlet(),"/myservlet");return reg;}//注册 Filter//@Beanpublic FilterRegistrationBean filterRegistrationBean(){FilterRegistrationBean reg = new FilterRegistrationBean();//创建 CharacterEncodingFilterCharacterEncodingFilter filter = new CharacterEncodingFilter();//设置 request, response 使用编码的值filter.setEncoding("utf-8");//强制 request, response 使用 encoding 的值filter.setForceEncoding(true);reg.setFilter(filter);//请求先使用过滤器处理reg.addUrlPatterns("/*");return reg;}
}

3.在 application.properties , 禁用 Spring Boot 中默认启用的过滤器

#启用自己的 CharacterEncodingFitler 的设置
server.servlet.encoding.enabled=false

4.启动主类,运行浏览器

1.3.5 在 application.properties 文件中设置过滤器

Spring Boot 项目默认启用了 CharacterEncodingFilter, 设置他的属性就可以

#设置 spring boot 中 CharacterEncodingFitler 的属性值
server.servlet.encoding.enabled=true
server.servlet.encoding.charset=utf-8
#强制 request, response 使用 charset 他的值 utf-8
server.servlet.encoding.force=true

1.4 第四章 ORM 操作 MySQL

讲解 MyBatis 框架,读写 MySQL 数据。通过 SpringBoot +MyBatis 实现对数据库学生表的查询操作。
数据库参考:springboot.sql 脚本文件
创建数据库:数据库 springboot,指定数据库字符编码为 utf-8

插入数据

1.4.1 创建 Spring Boot 项目

项目名称:015-springboot-mybatis
使用@Mapper 注解
➢ pom.xml

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--mybatis 起步依赖: mybatis 框架需要的依赖全部加入好--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency><!--mysql 驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

加入 resources 插件

<!--加入 resource 插件-->
<resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource>
</resources>

➢ 配置数据源:application.properties

server.port=9090
server.servlet.context-path=/myboot
#连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
#serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123

➢ 创建数实体 bean, dao 接口,mapper 文件

➢ 实体类

public class Student {private Integer id;private String name;private Integer age;// set | get
}

➢ 创建 Dao 接口

package com.bjpowernode.dao;
import com.bjpowernode.domain.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* @Mapper: 找到接口和他的 xml 文件
* 位置:在接口的上面
*/
@Mapper
public interface StudentMapper {Student selectStudentById(@Param("id") Integer id);
}

➢ mapper 文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bjpowernode.dao.StudentMapper"><select id="selectStudentById" resultType="com.bjpowernode.domain.Student">select * from student2 where id=#{id}</select>
</mapper>

➢ service 接口

public interface StudentService {Student queryStudent(Integer id);
}

➢ service 接口实现类

@Service
public class StudentServiceImpl implements StudentService {@Resourceprivate StudentMapper studentDao;@Overridepublic Student queryStudent(Integer id) {Student student = studentDao.selectStudentById(id);return student;}
}

➢ controller 类

@Controller
public class StudentController {@Resourceprivate StudentService studentService;@RequestMapping("/query")@ResponseBodypublic String queryStudent(Integer id){Student student = studentService.queryStudent(id);return "查询结果 id 是"+id+", 学生="+student.toString();}
}

启动 Application 类, 浏览器访问 http://localhost:9090/myboot/query

1.4.2 @MapperScan

在 Dao 接口上面加入@Mapper,需要在每个接口都加入注解。当 Dao 接口多的时候不方便。
可以使用如下的方式解决。

主类上添加注解包扫描:@MapperScan(“com.bjpowernode.dao”)

新建 Spring Boot 项目 : 016-springboot-mybatis2
项目的代码同上面的程序, 修改的位置:
1.去掉 StudentMapper 接口的上面的@Mapper 注解
2.在主类上面加入 @MapperScan()

/**
* @MapperScan: 扫描所有的 mybatis 的 dao 接口
* 位置:在主类的上面
* 属性:basePackages:指定 dao 接口的所在的包名。
* dao 接口和 mapper 文件依然在同一目录
*/
@SpringBootApplication
@MapperScan(basePackages = "com.bjpowernode.dao")
public class MyBatisApplication2 {public static void main(String[] args) {SpringApplication.run(MyBatisApplication2.class,args);}
}

1.4.3 mapper 文件和 java 代码分开管理

这种方式比较推荐,mapper 文件放在 resources 目录下, java 代码放在 src/main/java。
实现步骤:
➢ 在 resources 创建自定义目录,例如 mapper, 存放 xml 文件

➢ 把原来的 xml 文件剪切并拷贝到 resources/mapper 目录
➢ 在 application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映
射文件不在同一个包的情况下,才需要指定。

 #指定 mybatis 的配置, 相当于 mybatis 主配置文件的作用
mybatis:mapper-locations: classpath:mapper/*.xmlconfiguration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

➢ 运行主类, 浏览器测试访问

1.4.4 事务支持

Spring Boot 使用事务非常简单,底层依然采用的是 Spring 本身提供的事务管理
➢ 在入口类中使用注解 @EnableTransactionManagement 开启事务支持
➢ 在访问数据库的 Service 方法上添加注解 @Transactional 即可
通过 SpringBoot +MyBatis 实现对数据库学生表的更新操作,在 service 层的方法中构建异常,查看事务是否生效。
创建项目:018-springboot-transaction
项目可以在 MyBatis 项目中修改。
实现步骤:

  1. pom.xml
<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.4</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
  1. 修改 StudentService,在 addStudent()方法中抛出异常
@Service
public class StudentServiceImpl {@Resourceprivate StudentMapper studentDao;@Transactionalpublic int addStudent(Student student) {int rows = studentDao.addStudent(student);System.out.println("addStudent 添加学生数据!!!");//在此构造一个除数为 0 的异常,测试事务是否起作用int i = 10/0;return rows;}
}
  1. 在 Application 主类上,@EnableTransactionManagement 开启事务支持
@EnableTransactionManagement 可选,但是@Service 必须添加事务才生效
@SpringBootApplication
@EnableTransactionManagement
@MapperScan(value="com.bjpowernode.dao")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
  1. 测试应用, 数据没有添加成功
  2. 注释掉 StudentServiceImpl 上的@Transactional 测试。数据添加成功

1.5 第五章 接口架构风格—RESTful

1.5.1 认识 REST

REST(英文:Representational State Transfer,简称 REST)
一种互联网软件架构设计的风格,但它并不是标准,它只是提出了一组客户端和服务器交
互时的架构理念和设计原则,基于这种理念和原则设计的接口可以更简洁,更有层次

任何的技术都可以实现这种理念,如果一个架构符合 REST 原则,就称它为 RESTFul 架构

比如我们要访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1

采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1

1.5.2 RESTful 的注解

Spring Boot 开发 RESTful 主要是几个注解实现

  • (1) @PathVariable
    获取 url 中的数据
    该注解是实现 RESTFul 最主要的一个注解
  • (2) @PostMapping
    接收和处理 Post 方式的请求
  • (3) @DeleteMapping
    接收 delete 方式的请求,可以使用 GetMapping 代替
  • (4) @PutMapping
    接收 put 方式的请求,可以用 PostMapping 代替
  • (5) @GetMapping
    接收 get 方式的请求

1.5.3 RESTful 优点

➢ 轻量,直接基于 http,不再需要任何别的诸如消息协议
get/post/put/delete 为 CRUD 操作
➢ 面向资源,一目了然,具有自解释性。
➢ 数据描述简单,一般以 xml,json 做数据交换。
➢ 无状态,在调用一个接口(访问、操作资源)的时候,可以不用考虑上下文,不用考虑当前状态,
极大的降低了复杂度。
➢ 简单、低耦合

1.5.4 注解练习

1.5.4.1 编写 Controller

创建 MyRestController

package com.bjpowernode.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class MyRestController {//get 请求/*** rest 中, url 要使用占位符,表示传递的数据。* 占位符叫做路径变量, 在 url 中的数据** 格式: 在@RequestMapping 的 value 属性值中,使用 {自定义名称}* http://localhost:8080/myboot/student/1001/bj2009*** @PathVariable: 路径变量注解,作用是获取 url 中的路径变量的值* 属性: value : 路径变量名称* 位置: 在逐个接收参数中,在形参定义的前面** 注意:路径变量名和形参名一样, value 可以不写** /student/1001/bj2009*/@GetMapping(value = "/student/{studentId}/{classname}")public String queryStudent(@PathVariable(value = "studentId") Integer id,@PathVariable String classname){return "get 请求,查询学生 studentId:"+id+", 班级:"+classname;}///student/1001/bjpowernode@GetMapping(value = "/student/{studentId}/school/{schoolname}")public String queryStudentBySchool(@PathVariable(value = "studentId") Integer id, @PathVariable String schoolname){return "get 请求,查询学生 studentId:"+id+", 班级:"+schoolname;}@PostMapping("/student/{stuId}")public String createStudent(@PathVariable("stuId") Integer id,String name,Integer age){return "post 创建学生, id="+id+",name="+name+",age="+age;}@PutMapping("/student/{stuId}")public String modifyStudent(@PathVariable("stuId") Integer id,String name){System.out.println("===========put 请求方式 ========");return "put 修改学生, id="+id+",修改的名称是:"+name;}@DeleteMapping("/student/{stuId}")public String removeStudent(@PathVariable("stuId") Integer id){System.out.println("===========delete 请求方式 ========");return "delete 删除学生,id="+id;}
}

application.properties 文件

server.servlet.context-path=/myboot
启用 HiddenHttpMethodFilter 这个过滤器, 支持 post 请求转为 put,delete
spring.mvc.hiddenmethod.filter.enabled=true

1.5.4.2 使用 Postman 模拟发送请求,进行测试

安装 Postman 测试软件,安装后执行 Postman.exe

使用方式,设置连接和参数,点击“发送”按钮

1.5.4.3 请求路径冲突

@GetMapping(value = "/student/{studentId}/{classname}")
@GetMapping(value = "/student/{studentId}/{schoolname}")

这样的路径访问会失败, 路径有冲突。
解决:设计路径,必须唯一, 路径 uri 和 请求方式必须唯一。

1.5.4.4 RESTful 总结

➢ 增 post 请求、删 delete 请求、改 put 请求、查 get 请求
➢ 请求路径不要出现动词
例如:查询订单接口
/boot/order/1021/1(推荐)
/boot/queryOrder/1021/1(不推荐)
➢ 分页、排序等操作,不需要使用斜杠传参数
例如:订单列表接口
/boot/orders?page=1&sort=desc
一般传的参数不是数据库表的字段,可以不采用斜杠

1.6 第六章 Spring Boot 集成 Redis

Redis 是一个 NoSQL 数据库, 常作用缓存 Cache 使用。 通过 Redis 客户端可以使用多种
语言在程序中,访问 Redis 数据。java 语言中使用的客户端库有 Jedis,lettuce, Redisson
等。

Spring Boot 中使用 RedisTemplate 模版类操作 Redis 数据。

需求:完善根据学生 id 查询学生的功能,先从 redis 缓存中查找,如果找不到,再从数
据库中查找,然后放到 redis 缓存中

1.6.1 项目之前需要安装配置好 Redis。

检查 Linux 中的 redis。 启动 redis,通过客户端访问数据

1.6.2 需求实现步骤

创建项目:020-springboot-redis

1.6.2.1 pom.xml

<!--redis 起步依赖spring boot 会在容器中创建两个对象 RedisTemplate ,StringRedisTemplate
-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

1.6.2.2 核心配置文件 application.properties

#指定 redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123456

1.6.2.3 创建 RedisController

package com.bjpowernode.controller;
import com.bjpowernode.vo.Student;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import
org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
www.bjpowernode.com 69 / 137 Copyright©动力节点
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class RedisController {//注入 RedisTemplate//泛型 key,value 都是 String ,或者 Object, 不写@Resourceprivate RedisTemplate redisTemplate;@GetMapping("/myname")public String getName(){redisTemplate.setKeySerializer( new StringRedisSerializer());// redisTemplate.setValueSerializer( new StringRedisSerializer());String name=(String) redisTemplate.opsForValue().get("name");return name;}@PostMapping("/name/{myname}")public String addName(@PathVariable("myname") String name){redisTemplate.opsForValue().set("name",name);return "添加了学生:"+name;}
}

1.6.2.4 启动 Redis 服务

1.6.2.5 执行 Spring Boot Application 启动类

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

1.6.2.6 使用 Postman 发送请求

1.6.2.7 启动浏览器访问 Controller

1.6.2.8 Redis Desktop Manager 桌面工具查看

1.7 第七章 Spring Boot 集成 Dubbo

1.7.1 创建接口 module

按照 Dubbo 官方开发建议,创建一个接口项目,该项目只定义接口和 model 类。
项目名称:021-interface-api
此项目就是一个普通的 maven 项目
gav:

<groupId>com.bjpowernode</groupId>
<artifactId>021-interface-api</artifactId>
<version>1.0.0</version>

model 类:

public class Student implements Serializable {private Integer id;private String name;private Integer age;//set|get 方法
}

服务接口

public interface StudentService {Student queryStudent(Integer studentId);
}

1.7.2 服务提供者 module

实现 api 项目中的接口
项目名称:022-service-prvoider
使用 Spring Boot Initializer 创建项目, 不用选择依赖

step1) pom.xml 依赖

<dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-spring-boot-starter</artifactId><version>2.7.8</version>
</dependency>
<dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-dependencies-zookeeper</artifactId><version>2.7.8</version><type>pom</type>
</dependency>

step2) application.properties

#服务名称
spring.application.name=service-provider
#zookeeper 注册中心
dubbo.registry.address=zookeeper://localhost:2181
#dubbo 注解所在的包名
dubbo.scan.base-packages=com.bjpowernode.service

step3)创建接口的实现类

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;
@Component
@DubboService(interfaceClass = StudentService.class,version = "1.0")
public class StudentServiceImpl implements StudentService {@Overridepublic Student queryStudent(Integer studentId) {Student student = new Student();student.setId(studentId);student.setName("张三");student.setAge(20);return student;}
}

step3) 应用主类 Application

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

1.7.3 创建消费者 module

项目名称:023-consumer
使用 Spring Boot Initializer 创建项目, 选择 web 依赖

step1) pom.xml dubbo 依赖

<dependency><groupId>com.bjpowernode</groupId><artifactId>021-interface-api</artifactId><version>1.0.0</version>
</dependency>
<dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-spring-boot-starter</artifactId><version>2.7.8</version>
</dependency>
<dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-dependencies-zookeeper</artifactId><version>2.7.8</version><type>pom</type>
</dependency>

step2) application.properties

#服务名称
spring.application.name=service-consumer
#dubbo 注解所在的包
dubbo.scan.base-packages=com.bjpowernode
#zookeeper
dubbo.registry.address=zookeeper://localhost:2181

step3) 创建 MyController

@RestController
public class MyController {@DubboReference(interfaceClass = StudentService.class,version = "1.0",check = false)private StudentService studentService;@GetMapping("/query")public String searchStudent(Integer id){Student student = studentService.queryStudent(id);return "查询学生:"+ student.toString();}
}

step4) 主启动类型 Application

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

1.7.4 测试应用

1)先启动 zookeeper
2)运行服务提供者 022-service-provider
3)运行消费者 023-consumer
4)在浏览器执行 http://localhost:8080/query?id=1

1.7.5 SLF4j 依赖

dubbo 提供者或者消费者项目启动是,有日志的提示

日志依赖 SLF4j 多次加入了。只需要依赖一次就可以。
解决方式:排除多余的 SLF4j 依赖, 提供者和消费者项目都需要这样做

<dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-dependencies-zookeeper</artifactId><version>2.7.8</version><type>pom</type><exclusions><exclusion><artifactId>slf4j-log4j12</artifactId><groupId>org.slf4j</groupId></exclusion></exclusions>
</dependency>

1.8 第八章 Spring Boot 打包

Spring Boot 可以打包为 war 或 jar 文件。 以两种方式发布应用

1.8.1 Spring Boot 打包为 war

创建 Spring Boot web 项目: 024-springboot-war

1.8.1.1 pom.xml

在 pom.xml 文件中配置内嵌 Tomcat 对 jsp 的解析包

<!--处理 jsp 的依赖-->
<dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--处理 web 的依赖-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

1.8.1.2 指定 jsp 文件编译目录

<resource><directory>src/main/webapp</directory><targetPath>META-INF/resources</targetPath><includes><include>**/*.*</include></includes>
</resource>

1.8.1.3 打包后的 war 文件名称

<!--指定打包后的 war 文件名称-->
<finalName>myweb</finalName>

1.8.1.4 完整的 build 标签内容

<build><!--指定打包后的 war 文件名称--><finalName>myweb</finalName><resources><!--mybatis 他的 xml 文件放置 src/main/java 目录--><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><!--指定 resources 下面的所有资源--><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes></resource><!--指定 jsp 文件编译后目录--><resource><directory>src/main/webapp</directory><targetPath>META-INF/resources</targetPath><includes><include>**/*.*</include></includes></resource></resources><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins>
</build>

1.8.1.5 创建 webapp 目录


指定 webapp 是 web 应用目录

1.8.1.6 创建 jsp 文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>jsp</title>
</head>
<body>显示 controller 中的数据 ${data}
</body>
</html>

1.8.1.7 创建 JspWarController

@Controller
public class JspWarController {@RequestMapping("/index")public ModelAndView index(){ModelAndView mv = new ModelAndView();mv.addObject("data","SpringBoot web 应用打包为 war");mv.setViewName("index");return mv;}
}

1.8.1.8 设置视图解析器

application.properties

server.port=9090
server.servlet.context-path=/myboot
# webapp
spring.mvc.view.prefix=/
# .jsp
spring.mvc.view.suffix=.jsp

1.8.1.9 启动主类,在浏览器访问地址 index

访问浏览器,地址 index

1.8.1.10 主启动类继承 SpringBootServletInitializer

继承 SpringBootServletInitializer 可以使用外部 tomcat。
SpringBootServletInitializer 就是原有的 web.xml 文件的替代。使用了嵌入式 Servlet,默
认是不支持 jsp。

@SpringBootApplication
public class JspApplication extends SpringBootServletInitializer {public static void main(String[] args) {SpringApplication.run(JspApplication.class, args);}@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {return builder.sources(JspApplication.class);}
}

1.8.1.11 指定项目 package 是 war

<!--指定 packing 为 war-->
<packaging>war</packaging>

1.8.1.12 maven package 打包

1.8.1.13 发布打包后的 war 到 tomcat

target 目录下的 war 文件拷贝到 tomcat 服务器 webapps 目录中,启动 tomcat。

在浏览器访问 web 应用

1.8.2 Spring Boot 打包为 jar

创建项目 025-springboot-jar

1.8.2.1 pom.xml

<!--处理 jsp 的依赖-->
<dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--指定 jsp 文件编译后目录-->
<resource><directory>src/main/webapp</directory><targetPath>META-INF/resources</targetPath><includes><include>**/*.*</include></includes>
</resource>

1.8.2.2 创建 webpp 目录

并指定他是 web 应用根目录

1.8.2.3 创建 jsp 文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>hello</title>
</head>
<body>hello.jsp ,显示数据 ${data}
</body>
</html>

1.8.2.4 创建 HelloController

@Controller
public class HelloController {//ModelAndView//Model 存储数据 相当于 HttpServletRequest 的 setAttribute()@RequestMapping("/hello")public String doHello(Model model){model.addAttribute("data","SpringBoot 打包为 jar");return "hello";}
}

1.8.2.5 application.properties

server.port=9001
server.servlet.context-path=/myboot
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

1.8.2.6 启动 Application,在浏览器访问应用

启动浏览器,访问 hello

1.8.2.7 修改 pom.xml 增加 resources 说明

以后为了保险起见,大家在打包的时候,建议把下面的配置都加上

<build><finalName>mybootjar</finalName><resources><!--mybatis 他的 xml 文件放置 src/main/java 目录--><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><!--指定 resources 下面的所有资源--><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes></resource><!--指定 jsp 文件编译后目录--><resource><directory>src/main/webapp</directory><targetPath>META-INF/resources</targetPath><includes><include>**/*.*</include></includes></resource></resources><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><!--带有 jsp 的程序,打包为 jar--><version>1.4.2.RELEASE</version></plugin></plugins>
</build>

1.8.2.8 必须 maven 插件版本

<plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><!--带有 jsp 的程序,打包为 jar--><version>1.4.2.RELEASE</version></plugin>
</plugins>

1.8.2.9 执行 maven package

target 目录有 jar 文件:mybootjar.jar

1.8.2.10 执行 jar,启动内置的 tomcat

java –jar mybootjar.jar
浏览器访问 web 应用

1.8.3 Spring Boot 部署和运行方式总结

➢ 在 IDEA 中直接运行 Spring Boot 程序的 main 方法(开发阶段)
➢ 用 maven 将 Spring Boot 安装为一个 jar 包,使用 Java 命令运行 java -jar springboot-xxx.jar
可以将该命令封装到一个 Linux 的一个 shell 脚本中(上线部署)
◼ 写一个 shell 脚本:
#!/bin/sh
java -jar xxx.jar
◼ 赋权限 chmod 777 run.sh
◼ 启动 shell 脚本: ./run.sh

➢ 使用 Spring Boot 的 maven 插件将 Springboot 程序打成 war 包,单独部署在 tomcat 中运行(上线部署 常用)

Spring boot(web 组件,ORM 操作 MySQL,接口架构风格—RESTful,集成 Redis,集成 Dubbo,打包)相关推荐

  1. spring boot ---- jpa连接和操作mysql数据库

    环境: centos6.8,jdk1.8.0_172,maven3.5.4,vim,spring boot 1.5.13,mysql-5.7.23 1.引入jpa起步依赖和mysql驱动jar包 1 ...

  2. Spring boot web(2):web综合开发

    1 web开发 Spring boot web 开发非常简单,其中包括常用的 json输出.filters.property.log等 1.1 json接口开发 在以前的Spring 开发我么提供js ...

  3. okta-spring_通过Okta的单点登录保护Spring Boot Web App的安全

    okta-spring "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多 ...

  4. 通过Okta的单点登录保护Spring Boot Web App的安全

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 您可以使 ...

  5. Spring Boot之jdbc数据操作06

    Spring Boot之jdbc数据操作06 JDBC 通过快速创建spring boot项目选择 mysql 和jdbc 创建一个基于web的spring boot项目 依赖为 <depend ...

  6. PART 5: INTEGRATING SPRING SECURITY WITH SPRING BOOT WEB

    转自:http://justinrodenbostel.com/2014/05/30/part-5-integrating-spring-security-with-spring-boot-web/ ...

  7. spring boot编写并运行HelloWorld服务接口

    spring boot编写并运行HelloWorld服务接口 在主程序上要加包扫描注解@ComponentScan("com.example.demo1") package com ...

  8. spring boot web 开发示例

    一.创建Maven工程 创建maven工程,packaging 类型选择jar. 二.配置相关maven依赖. 1,首先你需要在pom中最上方添加spring boot的父级依赖,这样当前的项目就是S ...

  9. Spring Boot Web应用程序中注册 Servlet 的方法实例

    Spring Boot Web应用程序中注册 Servlet 的方法实例 本文实例工程源代码:https://github.com/KotlinSpringBoot/demo1_add_servlet ...

最新文章

  1. IBM发布IBM Watson创新功能,旨在帮助企业扩展AI使用
  2. MySql 5.7.19 源代码安装 for ubuntu 16.04
  3. XAML中格式化日期
  4. 调试内核Ubuntu 搭建嵌入式开发环境-续
  5. 并发编程学习之阻塞队列BlockingQueue和LinkedBlockingQueue
  6. bzoj2821 作诗(Poetize)
  7. C语言 拓补排序 有向无环图
  8. 自学计算机基础知识需要什么书,学习计算机基础知识,我强烈推荐这三本书!...
  9. 机器学习:PCA(使用梯度上升法求解数据主成分 Ⅰ )
  10. 恒指赵鑫:来说说止损
  11. 命主属性是水什么意思_​五行中,你属什么就是什么样的人!太准了~
  12. HTML5和CSS3的一些小总结
  13. 软件配置 | pip下载第三方库文件及配置pip源的不完全总结
  14. NSDP协议PORTAL服务器源码
  15. 【python】hasattr()、getattr()、setattr() 函数使用详解
  16. led的c语言程序,单片机C语言LED灯点亮程序完全版
  17. 若依框架免密登录(仅做参考)
  18. 使用99编程 —— EDA拼接屏大规模图像处理
  19. 基于Netty的联机版坦克大战
  20. 【文献篇】国家法律法规数据库提供免费的文献下载功能

热门文章

  1. javaScript 生成随机字母 随机数字的5种方法
  2. matlab 正负数,matlab判断函数值正负程序
  3. 怎么控制latex插图的位置_[转载](转)LaTeX 控制图片的位置
  4. word2016开机后首次打开非常慢_终于找到了电脑开机时间长的原因了,一看就会,一招到位...
  5. php jsp显示数据排序,JSP_SQL数据库开发中的一些精典代码,1.按姓氏笔画排序: select * From T - phpStudy...
  6. 需账号密码登陆的网页爬虫
  7. HTML 动态背景
  8. Qt Charts示例
  9. 前端小白系列之——导言
  10. 手机 download .cu .log_手机清理内存,这些英文文件哪些是可以删除的?看完就知道...