SpringBoot学习之应用开发篇(二)1.8 - 构建Web应用-1

目录

一、Swagger2构建RESTful API

1、引用依赖pom.xml

2、配置SwaggerConfig

3、展示效果

3-1、控制层代码

3-2、效果图

二、Actuator监控

1、pom.xml引入依赖jar

2、配置Actuator

3、访问接口列表

三、发送邮件

1、pom.xml引入依赖jar

2、配置邮箱发件人

3、发送邮件程序


一、Swagger2构建RESTful API

① 说明:Swagger是一款可以快速生成符合RESTful风格API并进行在线调试的插件。

② Swagger常用注解
    @Api:修饰整个类,描述Controller的作用;
    @ApiOperation:描述一个类的一个方法,或者说一个接口;
    @ApiParam:单个参数描述;
    @ApiModel:用对象来接收参数;
    @ApiProperty:用对象接收参数时,描述对象的一个字段;
    @ApiResponse:HTTP响应其中1个描述;
    @ApiResponses:HTTP响应整体描述;
    @ApiIgnore:使用该注解忽略这个API;
    @ApiError :发生错误返回的信息;
    @ApiImplicitParam:一个请求参数;
    @ApiImplicitParams:多个请求参数。

③ Spring Boot中包含了一些注解,对应于HTTP协议中的方法:
    @GetMapping对应HTTP中的GET方法;
    @PostMapping对应HTTP中的POST方法;
    @PutMapping对应HTTP中的PUT方法;
    @DeleteMapping对应HTTP中的DELETE方法;
    @PatchMapping对应HTTP中的PATCH方法。

1、引用依赖pom.xml

<!-- 整合Swagger2构建RESTful API --> 
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2、配置SwaggerConfig

在org.springboot.springboot01.config包下,新增SwaggerConfig配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createAppWebApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("SpringBoot的API接口文档")
                .apiInfo(getApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.springboot.springboot01.controller"))
                .paths(PathSelectors.any()).build()
                ;
    }

    /**
     * 构建api文档的详情信息
     * @return ApiInfo
     */
    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                // 设置页面标题
                .title("SpringBoot系统")
                // 设置接口描述
                .description("SpringBoot系统")
                // 设置联系方式
                .contact(new Contact("li,", "https://blog.csdn.net/liyb1078422974", "229364050@qq.com"))
                // 设置版本
                .version("1.0.0")
                // 构建
                .build();
    }
}

3、展示效果

3-1、控制层代码

在org.springboot.springboot01.controller包下,新增SwaggerConfigController类

@Api(value = "Swagger展示")
@RequestMapping("user")
@Controller
public class SwaggerConfigController {
    private static final Logger log = LoggerFactory.getLogger(SwaggerConfigController.class);

    @ApiIgnore
    @GetMapping("notShow")
    public @ResponseBody
    String hello() {
        return "notShow";
    }

    @ApiOperation(value = "获取学生信息", notes = "根据主键ID获取学生信息")
    @ApiImplicitParam(name = "id", value = "学生id", required = true, dataType = "String")
    @GetMapping("/{id}")
    @ResponseBody
    public Student getStudent(@PathVariable(value = "id") String id) {
        log.debug("根据学生ID:{},获取学生信息", id);
        Student student = new Student();
        student.setId(Integer.parseInt(id));
        student.setName("学生A");
        student.setSex("保密");
        return student;
    }

    @ApiOperation(value = "新增学生信息", notes = "根据学生实体创建学生纪录")
    @ApiImplicitParam(name = "user", value = "学生实体", required = true, dataType = "user")
    @PostMapping("/addStudent")
    @ResponseBody
    public Student addStudent(@RequestBody Student student) {
        log.debug("创建学生信息:{}", JSON.toJSONString(student));
        return student;
    }
}

3-2、效果图

启动后,访问地址:http://127.0.0.1:8080/springboot/swagger-ui.html

二、Actuator监控

1、pom.xml引入依赖jar

<!-- actuator监控 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2、配置Actuator

# 方式一:启用端点:env(默认情况下,端点都不启用,此时需要按需启用端点)
management.endpoint.env.enabled=true
# 方式一:启用端点:beans(默认情况下,端点都不启用,此时需要按需启用端点)
management.endpoint.beans.enabled=true
# 方式一:启用端点:shutdown(启动关闭应用程序 - POST访问)
management.endpoint.shutdown.enabled=true
# 方式一:暴露端点 env 配置多个用,隔开
management.endpoints.web.exposure.include=env,beans,shutdown

# 方式二:直接开启和暴露所有端点
#management.endpoints.web.exposure.include=*

# 端点前缀->监控访问路径,默认:/actuator。即:http://127.0.0.1:8080/springboot/actuator/beans
# 下列base-path的配置可以更改默认访问路径,即:http://127.0.0.1:8080/springboot/monitor/beans
#management.endpoints.web.base-path=/monitor

# 将原来的beans请求路径修改为instance,即访问路径:http://127.0.0.1:8080/springboot/actuator/instance
#management.endpoints.web.path-mapping.beans=instance

3、访问接口列表

① 默认访问基础路径:http://127.0.0.1:8080/springboot/actuator/

② 配置management.endpoints.web.base-path=/monitor后,访问基础路径:http://127.0.0.1:8080/springboot/monitor/

HTTP 方法路径描述
GET/autoconfig提供了一份自动配置报告,记录哪些自动配置条件通过了,哪些没通过
GET/configprops描述配置属性(包含默认值)如何注入Bean
GET/beans描述应用程序上下文里全部的Bean,以及它们的关系
GET/dump获取线程活动的快照
GET/env获取全部环境属性
GET/env/{name}根据名称获取特定的环境属性值
GET/health报告应用程序的健康指标,这些值由HealthIndicator的实现类提供
GET/info获取应用程序的定制信息,这些信息由info打头的属性提供
GET/mappings描述全部的URI路径,以及它们和控制器(包含Actuator端点)的映射关系
GET/metrics报告各种应用程序度量信息,比如内存用量和HTTP请求计数
GET/metrics/{name}报告指定名称的应用程序度量值
POST/shutdown关闭应用程序,要求management.endpoint.shutdown.enabled设置为true
GET/trace提供基本的HTTP请求跟踪信息(时间戳、HTTP头等)

三、发送邮件

1、pom.xml引入依赖jar

<!-- 发送邮件所需依赖包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Spring用于支持HTML,静态等文件和页面展示(如果有则不用添加。本次用于邮件模板解析) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、配置邮箱发件人

spring.mail.host=smtp.exmail.qq.com
spring.mail.username=***@***.com
spring.mail.password=******
spring.mail.properties.mail.smtp.auth=true
# 使用 starttls 安全连接
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.default-encoding=UTF-8

3、发送邮件程序

3-1、 在org.springboot.springboot01.controller下,新增EmailController类,用于发送各类型的邮件

@RestController
@RequestMapping("/email")
public class EmailController {
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender jms;
    @Resource
    private TemplateEngine templateEngine;


    // http://127.0.0.1:8080/springboot/email/sendEmail
    @RequestMapping("sendEmail")
    public String sendEmail() {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo("***@***.com");
            message.setSubject("这是一封测试邮件");
            message.setText("测试发送简单的邮件");
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    // http://127.0.0.1:8080/springboot/email/sendHtmlEmail
    @RequestMapping("sendHtmlEmail")
    public String sendHtmlEmail() {
        MimeMessage message;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("***@***.com");
            helper.setSubject("这是一封测试HTML的邮件");
            // 带HTML格式的内容
            String html = "<p style='color:#6db33f'>使用Spring Boot发送HTML格式邮件。</p>";
            helper.setText(html, true);
            jms.send(message);
            return "发送Html格式的邮件成功";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    // http://127.0.0.1:8080/springboot/email/sendAttachmentsMail
    @RequestMapping("sendAttachmentsMail")
    public String sendAttachmentsMail() {
        MimeMessage message;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("***@***.com");
            helper.setSubject("一封带附件的邮件");
            helper.setText("详情参见附件内容");
            // 传入附件
            FileSystemResource file = new FileSystemResource(new File("E:\\picture.jpg"));
            helper.addAttachment("picture.jpg", file);
            jms.send(message);
            return "发送带附件的邮件成功";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    // http://127.0.0.1:8080/springboot/email/sendInlineMail
    @RequestMapping("sendInlineMail")
    public String sendInlineMail() {
        MimeMessage message;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("***@***.com");
            helper.setSubject("一封带静态资源的邮件");
            String html = "<html><body>测试图:<img src='cid:img'/></body></html>";
            helper.setText(html, true);
            // 传入附件
            FileSystemResource file = new FileSystemResource(new File("E:\\picture.jpg"));
            // helper.addInline("img", file);中的img和图片标签里cid后的名称相对应
            helper.addInline("img", file);
            jms.send(message);
            return "发送带静态资源的邮件成功";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    // 请求地址:http://127.0.0.1:8080/springboot/email/sendTemplateEmail?code=123456
    @RequestMapping("sendTemplateEmail")
    public String sendTemplateEmail(@RequestParam String code) {
        MimeMessage message;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo("***@***.com");
            helper.setSubject("邮件模板测试");
            // 处理邮件模板
            Context context = new Context();
            // code对应模板里的${code}变量
            context.setVariable("code", code);
            context.setVariable("time", "9点");
            // emailTemplate对应templates目录下的emailTemplate.html
            String template = templateEngine.process("emailTemplate", context);
            helper.setText(template, true);
            jms.send(message);
            return "发送使用模板的邮件成功,code="+ code;
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

3-2、在src/main/resources/templates下,新增emailTemplate.html文件,用于发送使用邮件模板的测试。

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>邮件模板测试</title>
</head>

<body>
    您好,您本次的编号为<span th:text="${code}"></span> ,请早点来公司上班(<span th:text="${time}"></span>之前),请勿迟到(本次是测试请忽略)。
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员的微笑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值