• Spring boot(2)


    目录

    一、springboot集成jsp

    1、创建webapp

    2、将webapp文件夹设置为web的资源

    3、导入依赖,并指定资源到resources下

     4.访问jsp即可

    二、SpringMVC的自动配置

    1.拦截器

    1.1创建拦截器实现HandlerInterceptor

    1.2 在mvc配置类中设置interceptor 

    2.异常处理

    2.1 Springboot有默认的错误处理

     2.2 springmvc的全局处理--只能识别服务器错误

    2.3 异步的异常处理

    三、任务管理

    1、异步任务

    1.1开启异步任务

    1.2 将方法设置为异步任务

     

    1.3 测试

     ​编辑

     2. 定时任务

     2.1 开启定时任务

     2.2 在方法中声明条件

    2.3 测试

     四、健康监控

     1、基本使用

    导入依赖

     配置文件

    访问

     2. springboot-admin

    2.1 先创建客户端

    2.2 创建服务端端来接受客户端 

     五、swapper 文档框架

    1、导入依赖

     2、在app中加入swapper2的注解

    3、设置config,注解配置类 

    4、访问

     5、标注接口


    一、springboot集成jsp

    1、创建webapp

    在main下创建webapp的文件夹 

    在webapp下创建WEB-INF文件夹

    2、将webapp文件夹设置为web的资源

     

     

     设置完毕后,webapp出现小蓝点说明正确

     

    3、导入依赖,并指定资源到resources下

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.bootgroupId>
    4. <artifactId>spring-boot-starter-webartifactId>
    5. dependency>
    6. <dependency>
    7. <groupId>org.apache.tomcat.embedgroupId>
    8. <artifactId>tomcat-embed-jasperartifactId>
    9. dependency>
    10. <dependency>
    11. <groupId>org.springframework.bootgroupId>
    12. <artifactId>spring-boot-starter-testartifactId>
    13. dependency>
    14. <dependency>
    15. <groupId>org.springframework.bootgroupId>
    16. <artifactId>spring-boot-devtoolsartifactId>
    17. dependency>
    18. <dependency>
    19. <groupId>org.projectlombokgroupId>
    20. <artifactId>lombokartifactId>
    21. dependency>
    22. <dependency>
    23. <groupId>jstlgroupId>
    24. <artifactId>jstlartifactId>
    25. <version>1.2version>
    26. dependency>
    27. dependencies>
    28. <build>
    29. <resources>
    30. <resource>
    31. <directory>src/main/webappdirectory>
    32. <targetPath>META-INF/resourcestargetPath>
    33. <includes>
    34. <include>
    35. **/*.*
    36. include>
    37. includes>
    38. resource>
    39. resources>
    40. build>

     4.访问jsp即可

    1. package com.sofwin;
    2. import com.sofwin.service.impl.schedulingServiceImpl;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.boot.SpringApplication;
    5. import org.springframework.boot.autoconfigure.SpringBootApplication;
    6. import org.springframework.scheduling.annotation.EnableAsync;
    7. import org.springframework.scheduling.annotation.EnableScheduling;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.web.bind.annotation.GetMapping;
    10. import java.util.Map;
    11. /**
    12. * @author : wentao
    13. * @version : 1.0
    14. */
    15. @SpringBootApplication
    16. @Controller
    17. public class App {
    18. public static void main(String[]args){
    19. SpringApplication.run(App.class,args);
    20. }
    21. @GetMapping("/test")
    22. public String test(){
    23. return "index.jsp";
    24. }
    25. }

     也可以设置前后缀在yml中   --视图解析器

    1. spring:
    2. mvc:
    3. view:
    4. prefix: /WEB-INF/ #前缀
    5. suffix: .jsp #后缀

    二、SpringMVC的自动配置

    1.拦截器

    1.1创建拦截器实现HandlerInterceptor

    1. package com.sofwin.interceptor;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.stereotype.Component;
    4. import org.springframework.web.servlet.HandlerInterceptor;
    5. import org.springframework.web.servlet.ModelAndView;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. /**
    9. * @author : wentao
    10. * @version : 1.0
    11. */
    12. @Component
    13. @Slf4j
    14. public class LoginInterceptor implements HandlerInterceptor {
    15. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    16. log.info("preHandle");
    17. return true;
    18. }
    19. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    20. log.info("postHandle");
    21. }
    22. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    23. log.info("afterCompletion");
    24. }
    25. }

    1.2 在mvc配置类中设置interceptor 

    1. package com.sofwin.config;
    2. import com.sofwin.interceptor.LoginInterceptor;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    7. /**
    8. * @author : wentao
    9. * @version : 1.0
    10. */
    11. @Configuration
    12. //注意这里springboot不让在写EnableWeb
    13. public class MvcConfig implements WebMvcConfigurer {
    14. @Autowired
    15. private LoginInterceptor loginInterceptor;
    16. public void addInterceptors(InterceptorRegistry registry) {
    17. registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
    18. }
    19. }

    2.异常处理

    2.1 Springboot有默认的错误处理

    默认情况下,springboot会根据客户端的类型,返回不同的错误信息

    如果在resources文件夹下的static或者public文件夹下的error目录400.jsp、500.jsp等就会执行jsp的页面的错误提示  --可以识别404等客户端的错误

     2.2 springmvc的全局处理--只能识别服务器错误

     

    实现HandlerExceptionResolver的接口 ,这个是返回的页面 是同步的异常处理器

    1. package com.sofwin.ex;
    2. import org.springframework.stereotype.Component;
    3. import org.springframework.web.servlet.HandlerExceptionResolver;
    4. import org.springframework.web.servlet.ModelAndView;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. /**
    8. * @author : wentao
    9. * @version : 1.0
    10. */
    11. //全局异常处理器只能处理服务的异常
    12. @Component
    13. public class MyExcepotr implements HandlerExceptionResolver {
    14. public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    15. ModelAndView modelAndView=new ModelAndView("ex");
    16. return modelAndView;
    17. // if (ex instanceof NullPointerException)
    18. //可以使用这样进行不同的异常反映不同的结果
    19. }
    20. }

    2.3 异步的异常处理

    1. package com.sofwin.ex;
    2. import org.springframework.web.bind.annotation.ControllerAdvice;
    3. import org.springframework.web.bind.annotation.ExceptionHandler;
    4. import org.springframework.web.bind.annotation.ResponseBody;
    5. import java.util.HashMap;
    6. import java.util.Map;
    7. /**
    8. * @author : wentao
    9. * @version : 1.0
    10. */
    11. //一般用于异步的异常处理
    12. @ControllerAdvice
    13. public class ResponseException {
    14. @ResponseBody
    15. @ExceptionHandler(NullPointerException.class)
    16. public Map test01(){
    17. Map map =new HashMap();
    18. map.put("message","空异步异常处理");
    19. return map;
    20. }
    21. @ResponseBody
    22. @ExceptionHandler(Exception.class)
    23. public Map test02(){
    24. Map map =new HashMap();
    25. map.put("message","全异步异常处理");
    26. return map;
    27. }
    28. }

    这个返回的就是json字符串数据 

    三、任务管理

    1、异步任务

    在java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成迟缓的情况。在spring3.x之后,已经内置了@Async来完美解决这个问题。

    1.1开启异步任务

    1. package com.sofwin;
    2. import com.sofwin.service.impl.schedulingServiceImpl;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.boot.SpringApplication;
    5. import org.springframework.boot.autoconfigure.SpringBootApplication;
    6. import org.springframework.scheduling.annotation.EnableAsync;
    7. import org.springframework.scheduling.annotation.EnableScheduling;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.web.bind.annotation.GetMapping;
    10. import java.util.Map;
    11. /**
    12. * @author : wentao
    13. * @version : 1.0
    14. */
    15. @SpringBootApplication
    16. @EnableAsync //异步任务
    17. public class App {
    18. public static void main(String[]args){
    19. SpringApplication.run(App.class,args);
    20. }
    21. }

    1.2 将方法设置为异步任务

     

    1. package com.sofwin.service.impl;
    2. import org.springframework.scheduling.annotation.Async;
    3. import org.springframework.stereotype.Service;
    4. /**
    5. * @author : wentao
    6. * @version : 1.0
    7. */
    8. //异步任务
    9. //异步任务就是当这个方法没执行完,也会执行性下面的语句
    10. @Service
    11. public class AsyncServiceImpl {
    12. @Async
    13. public void service01(){
    14. System.out.println("任务1开始");
    15. try {
    16. Thread.sleep(1000);
    17. } catch (InterruptedException e) {
    18. e.printStackTrace();
    19. }
    20. System.out.println("任务1结束");
    21. }
    22. @Async
    23. public void service02(){
    24. System.out.println("任务2开始");
    25. try {
    26. Thread.sleep(1000);
    27. } catch (InterruptedException e) {
    28. e.printStackTrace();
    29. }
    30. System.out.println("任务2结束");
    31. }
    32. }

    1.3 测试

    1. package com.sofwin;
    2. import com.sofwin.service.impl.AsyncServiceImpl;
    3. import org.junit.jupiter.api.Test;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. import java.io.IOException;
    7. /**
    8. * @author : wentao
    9. * @version : 1.0
    10. */
    11. @SpringBootTest
    12. public class MyTest {
    13. @Autowired
    14. private AsyncServiceImpl asyncService;
    15. @Test
    16. public void test01(){
    17. System.out.println("start");
    18. asyncService.service01();
    19. asyncService.service02();
    20. System.out.println("end");
    21. try {
    22. //阻塞方法
    23. System.in.read();
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. }

     


     2. 定时任务

    我们经常需要执行一些定时任务,如果需要在每条凌晨的时候,分析一次前一天的日志信息。Spring为我们体用了异步执行任务调度的方式

     2.1 开启定时任务

    @EnableScheduling 

    1. package com.sofwin;
    2. import com.sofwin.service.impl.schedulingServiceImpl;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.boot.SpringApplication;
    5. import org.springframework.boot.autoconfigure.SpringBootApplication;
    6. import org.springframework.scheduling.annotation.EnableAsync;
    7. import org.springframework.scheduling.annotation.EnableScheduling;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.web.bind.annotation.GetMapping;
    10. import springfox.documentation.swagger2.annotations.EnableSwagger2;
    11. import java.util.Map;
    12. /**
    13. * @author : wentao
    14. * @version : 1.0
    15. */
    16. @SpringBootApplication
    17. @Controller
    18. @EnableAsync //异步任务
    19. @EnableScheduling //开启定时任务
    20. @EnableSwagger2
    21. public class App {
    22. public static void main(String[]args){
    23. SpringApplication.run(App.class,args);
    24. }
    25. @Autowired
    26. private schedulingServiceImpl schedulingService;
    27. @GetMapping("/test")
    28. public String test(){
    29. // Map map =null;
    30. map.put("ww",11);
    31. // int i=1/0;
    32. schedulingService.service01();
    33. return "index";
    34. }
    35. }

     2.2 在方法中声明条件

    @Scheduled(cron ="1/5 * * * * ?")

    cron表达式的含义

    cron表达式网上有在线的工具,直接使用即可、

    网址:Cron - 在线Cron表达式生成器

    1. package com.sofwin.service.impl;
    2. import org.springframework.scheduling.annotation.Async;
    3. import org.springframework.scheduling.annotation.Scheduled;
    4. import org.springframework.stereotype.Service;
    5. import java.util.Date;
    6. /**
    7. * @author : wentao
    8. * @version : 1.0
    9. */
    10. //异步任务
    11. //异步任务就是当这个方法没执行完,也会执行性下面的语句
    12. @Service
    13. public class schedulingServiceImpl {
    14. //conn 表达式规则: 直接在网上查找conn表达式的在线工具
    15. //从第一秒开始 每过5秒执行一次
    16. @Scheduled(cron ="1/5 * * * * ?")
    17. public void service01(){
    18. System.out.println("schedulingServiceImpl"+new Date());
    19. }
    20. }

    2.3 测试

     

     四、健康监控

    我们经常要了解当前应用的运行情况,通常引入spring-boot-starter-actuator,可以使用springboot为我们提供的准生成环境下的应用的监控和管理功能。我们可以通过Http、jmx、ssh进行操作,自动得到审计、监控及指标信息等。

     1、基本使用

    导入依赖

    1. org.springframework.boot
    2. spring-boot-starter-actuator

     配置文件

    在springboot中,Actuator默认只开放health和info两个端点,添加一下配置可以开放完整的监控端点

    1. management:
    2. endpoints:
    3. web:
    4. exposure:
    5. # 开放所有端口
    6. #直接访问http://localhost/actuator即可得到所有的端口
    7. include: "*"
    8. server:
    9. # 设置端口9999
    10. port: 9999
    11. # 修改访问路径 manager
    12. #http://localhost:9999/manager/actuator
    13. base-path: /manager

    访问

    如果不设置默认是 localhost/actuator

    因为设置了端口和path因此变成了localhost:9999/manager/actuator

     

    常见的端口

     

     

     

    向要查看的话直接复制访问即可  

    例如访问beans

    yH5BAAAAAAALAAAAAAOAA4AAAIMhI+py+0Po5y02qsKADs= 

     

     2. springboot-admin

    这样查询到的数据很乱,因此 actuator提供了可视化的界面,可以监控其他boot工程的各个端点

    2.1 先创建客户端

    可与有多个客户端  然后通过一个服务端进行接收、

    导入依赖

    1. <dependency>
    2. <groupId>de.codecentricgroupId>
    3. <artifactId>spring-boot-admin-starter-clientartifactId>
    4. <version>2.5.2version>
    5. dependency>

    配置url

    1. boot:
    2. admin:
    3. client:
    4. # springboot-admin可视化界面的url设置
    5. url: http://127.0.0.1:90

    2.2 创建服务端端来接受客户端 

    新创建一个工程

    导入依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.bootgroupId>
    4. <artifactId>spring-boot-starter-webartifactId>
    5. dependency>
    6. <dependency>
    7. <groupId>de.codecentricgroupId>
    8. <artifactId>spring-boot-admin-serverartifactId>
    9. <version>2.5.2version>
    10. dependency>
    11. <dependency>
    12. <groupId>de.codecentricgroupId>
    13. <artifactId>spring-boot-admin-server-uiartifactId>
    14. <version>2.5.2version> dependency>
    15. dependencies>

    设置端口  因为客户端设置url的端口是90  因此 服务端要设置

    1. server:
    2. port: 90

    创建启动类 

    1. package com.sofwin;
    2. import de.codecentric.boot.admin.server.config.EnableAdminServer;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. /**
    6. * @author : wentao
    7. * @version : 1.0
    8. */
    9. @SpringBootApplication
    10. @EnableAdminServer
    11. public class App {
    12. public static void main(String[]args){
    13. SpringApplication.run(App.class,args);
    14. }
    15. }

    然后分别启动客户端和服务端

     直接访问url即可  http://127.0.0.1:90/

     

     进入后对应的页面就是各种端口

     五、swapper 文档框架

    swapper 是一个api框架,可以帮助我们自动生成api的文档,还可以在线测试api的接口

    1、导入依赖

    1. <dependency>
    2. <groupId>io.springfoxgroupId>
    3. <artifactId>springfox-boot-starterartifactId>
    4. <version>3.0.0version>
    5. dependency>

    这样要注意的是 swagger的3.0的版本,我试了一下哟啊跟springboot的2.4.8使用,boot的版本太高会出现问题

     2、在app中加入swapper2的注解

    1. package com.sofwin;
    2. import com.sofwin.service.impl.schedulingServiceImpl;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.boot.SpringApplication;
    5. import org.springframework.boot.autoconfigure.SpringBootApplication;
    6. import org.springframework.scheduling.annotation.EnableAsync;
    7. import org.springframework.scheduling.annotation.EnableScheduling;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.web.bind.annotation.GetMapping;
    10. import springfox.documentation.swagger2.annotations.EnableSwagger2;
    11. import java.util.Map;
    12. /**
    13. * @author : wentao
    14. * @version : 1.0
    15. */
    16. @SpringBootApplication
    17. @Controller
    18. @EnableAsync //异步任务
    19. @EnableScheduling //开启定时任务
    20. @EnableSwagger2 //开启swapper2
    21. public class App {
    22. public static void main(String[]args){
    23. SpringApplication.run(App.class,args);
    24. }
    25. @Autowired
    26. private schedulingServiceImpl schedulingService;
    27. @GetMapping("/test")
    28. public String test(){
    29. // Map map =null;
    30. map.put("ww",11);
    31. // int i=1/0;
    32. schedulingService.service01();
    33. return "index";
    34. }
    35. }

    3、设置config,注解配置类 

    1. package com.sofwin.config;
    2. import io.swagger.annotations.ApiOperation;
    3. import org.springframework.context.annotation.Bean;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    6. import springfox.documentation.builders.ApiInfoBuilder;
    7. import springfox.documentation.builders.PathSelectors;
    8. import springfox.documentation.builders.RequestHandlerSelectors;
    9. import springfox.documentation.oas.annotations.EnableOpenApi;
    10. import springfox.documentation.service.ApiInfo;
    11. import springfox.documentation.service.Contact;
    12. import springfox.documentation.spi.DocumentationType;
    13. import springfox.documentation.spring.web.plugins.Docket;
    14. /**
    15. * @author : wentao
    16. * @version : 1.0
    17. */
    18. @Configuration
    19. @EnableOpenApi
    20. //http://127.0.0.1/swagger-ui/index.html 直接访问这个即可
    21. //如果有端口就写端口
    22. public class SwaggerConfig {
    23. @Bean
    24. public Docket createRestApi(){
    25. return new Docket(DocumentationType.SWAGGER_2)
    26. // 是否启用Swagger
    27. .enable(true)
    28. // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
    29. .apiInfo(apiInfo())
    30. // 设置哪些接口暴露给Swagger展示
    31. .select()
    32. // 扫描所有有注解的api,用这种方式更灵活
    33. .build();
    34. //.pathMapping(pathMapping);
    35. }
    36. /**
    37. * 添加摘要信息
    38. */
    39. private ApiInfo apiInfo(){
    40. // 用ApiInfoBuilder进行定制
    41. return new ApiInfoBuilder()
    42. // 设置标题
    43. .title("系统数据接口")
    44. // 描述
    45. .description("适用于V1.0版本")
    46. // 作者信息
    47. .contact(new Contact("sofwin", "http://www.sofwin.com", "laomake@hotmail.com"))
    48. // 版本
    49. .version("V1.0")
    50. .build();
    51. }
    52. }

    4、访问

    启动App然后访问

    网址是:127.0.0.1/swagger-ui/index.html

     出现这个页面代表正确了

     5、标注接口

    1. package com.sofwin.pojo;
    2. import io.swagger.annotations.ApiModel;
    3. import io.swagger.annotations.ApiModelProperty;
    4. import lombok.Data;
    5. /**
    6. * @author : wentao
    7. * @version : 1.0
    8. */
    9. @Data
    10. @ApiModel(value = "用户实体类")
    11. public class User {
    12. @ApiModelProperty(value = "id",name = "主键")
    13. private Integer id;
    14. @ApiModelProperty(value = "userName",name = "用户名")
    15. private String userName;
    16. }

     

    1. package com.sofwin.controller;
    2. import com.sofwin.pojo.User;
    3. import io.swagger.annotations.Api;
    4. import io.swagger.annotations.ApiOperation;
    5. import io.swagger.annotations.ApiParam;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.ResponseBody;
    10. /**
    11. * @author : wentao
    12. * @version : 1.0
    13. */
    14. @Controller
    15. @RequestMapping("/user")
    16. @Api(value = "/user", description = "用户管理")
    17. public class SwapperController {
    18. @GetMapping("/test")
    19. @ResponseBody
    20. @ApiOperation(value ="/test", notes="用户查询")
    21. public String test(@ApiParam(value = "主键",defaultValue ="1" ) Integer id){
    22. return id.toString();
    23. }
    24. @GetMapping("/query")
    25. @ResponseBody
    26. @ApiOperation(value ="/query", notes="查询单个用户")
    27. public User test02(@ApiParam(value = "主键",defaultValue ="1" ) Integer id,
    28. @ApiParam(value = "用户名",defaultValue ="zhangsan" ) String userName){
    29. User user=new User();
    30. user.setId(id);
    31. user.setUserName(userName);
    32. System.out.println(user);
    33. return user;
    34. }
    35. }

    接口的常用注解 

     

     

     

     

    设置后效果

  • 相关阅读:
    六、redis安装和配置
    TYPE-C接口桌面显示器:视频与充电的双重革新
    传统Android 开发与 Android 音视频开发的差距……
    深度学习 Day 18——利用卷神经网络实现猫狗识别 Ⅱ
    第八章:网络设备文件管理)
    基于TextRank算法生成文本摘要有代码+数据+可直接运行
    (附源码)计算机毕业设计SSM基于驾校管理系统
    【翻译】一种减小运动伪影的新方法基于AS-LMS自适应滤波器的PPG信号
    获取当前时间并转换为想要的格式
    禁止Chrome更新弹窗弹出
  • 原文地址:https://blog.csdn.net/weixin_52574640/article/details/126551075