springBoot案例

SpringBoot

java企业级开发框架
码云地址

解决问题

  • 导入静态资源
  • 首页
  • jsp模板引擎
  • 装配扩展SpringMVC
  • 增删改查
  • 拦截器
  • 国际化

静态资源

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }

访问静态资源

1.通过webjars
2.public,static,resources
在这里插入图片描述优先级
resources>static>public

首页如何定制

templates目录下页面只能通过@Controller访问需要thymeleaf模板引擎跳转

细分

JDBC

java连接数据库规范

  1. 数据库连接
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

Mybatis

MyBatis 是一款优秀的持久层框架

  1. 项目目录
    在这里插入图片描述
  2. 配置文件
mybatis:
  type-aliases-package: com.llt.pojo#实体类包
  mapper-locations: classpath:mybatis/mapper/*.xml#xmlsql配置文件

3.xmlSql

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.llt.mapper.UserMapper">
    <insert id="addUser" parameterType="User">
      insert into users(user,passd) values(#{user}, #{passd})
    </insert>
    <select id="queryUserList" resultType="User">
      select * from users
    </select>
</mapper>

Druid

阿里巴巴用来高效数据查询系统
配置文件application.yaml

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #Spring Boot 默认不注入这些属性值 需要自己绑定
    # druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvict ionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    # 配置监控统计拦截filters stat 监控统计 log4j 日志记录 wall防御sql注入
    # 如果允许时报错 java.lang.ClassNotFoundException
    # 则导入 log4J 以来即可
    filters: stat, wall, 1og4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.s1owSqlMi1lis=500
    #合并执行的相同sql,避免因为参数不同而统计多条sql语句
#用来配置SQL慢的标准,执行时间超过s LowSqLMillis的就是慢

需要生效这些配置 需要自定义配置springmvc
固定写法

package com.llt.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return  new DruidDataSource();
    }
    //后台监控 web.xml bean 相当于 之前的spring的xml配置载入容器
    //引入spring boot内置了servlet容器所以没有web.xml
    //替代方法 ServletRegistrationBean
    @Bean
    public ServletRegistrationBean a(){
        ServletRegistrationBean<StatViewServlet> statViewServletServletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
    //后台需要有人登录,账户密码配置
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("loginUsername","admin");
        objectObjectHashMap.put("loginPassword","123456");
        //允许谁可以访问
        objectObjectHashMap.put("allow","");
        //禁止谁能访问
        objectObjectHashMap.put("狂胜","192.168.2.6");
        //设置初始化参数
        statViewServletServletRegistrationBean.setInitParameters(objectObjectHashMap);
    return statViewServletServletRegistrationBean;
    }
       @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean<Filter> filterFilterRegistrationBean
                = new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setFilter(new WebStatFilter());
        //可以过滤那些请求
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        //这些不进行统计
        objectObjectHashMap.put("exclusions","*.js,*.css,/druid/*");
        filterFilterRegistrationBean.setInitParameters(objectObjectHashMap);
        return filterFilterRegistrationBean;
    }
}


Shiro 安全框架

maven 配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.llt</groupId>
    <artifactId>springboot-data</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-data</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.74</version>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-security</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

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

</project>


Shiro控制器

package com.llt.controller;

import com.llt.impl.UserServiceImpl;
import com.llt.pojo.User;
import com.llt.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class mybatisController {
    @Autowired
    private UserService userService;
    @GetMapping("/getuserlist")
    @ResponseBody
    public List<User> getAll(){
        List<User> all = userService.getAll();
        return all;
    }
    @GetMapping("/adduser")
    @ResponseBody
    public int add(User user){
        int i;
        if(user.getUser()==null || user.getPassd()==null){
            return 0;
        }
       return userService.addUser(user);
    }
    @RequestMapping("/login")
    public String login(String name, String password , Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(name, password);
       try {
           //登录没有异常说明可以登录
           subject.login(usernamePasswordToken);
           return "index";
       }catch (UnknownAccountException e){//用户名不纯在
           model.addAttribute("msg","用户名错误");
           return "login";
       }catch (IncorrectCredentialsException e){//用户名不纯在
           model.addAttribute("msg","密码不纯在");
           return "login";
       }
    }
}

Shiro配置文件

package com.llt.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean 传到前端
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean
    (@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加内置过滤器
//        anon 无需认证就可以访问
       // authc 必须认证了才能让问
        //user 必须拥有记住我功能才能用
        //perms 拥有对某个资源的权限才能访问
        //role 拥有某个角色权限才能访问
        Map<String,String> filter = new LinkedHashMap<>();
        filter.put("/getuserlist","anon");
        filter.put("/adduser","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filter);
//        shiroFilterFactoryBean.setLoginUrl("/tologin");
        return shiroFilterFactoryBean;
    }
    //Dafaul twebSecurityManager 接管对象
    @Bean(name = "getDefaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
       //关联UserRealm
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }
    //创建realm 对象
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return  new UserRealm();
    }
}

subject 用户

subject currentUser = Securityutils.getsubject(); //获取对象
Session session = currentuser.getSession();//获取session
currentuser.isAuthenticated()//判断当前用户是否被认证
currentuser.getPrincipal()//获取当前用户认证
currentuser.hasRole ("schwartz")//获取用户是否有当前的角色
currentuser.isPermi tted("lightsaber :wield")//获取当前权限
currentuser.logoutO);//登出

SecurityManager 管理所有用户

Realm 连接数据

package com.llt.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

public class UserRealm extends AuthorizingRealm {
    //授权·1
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了 授权 doGetAuthorizationInfo");
        return null;
    }
    //认证·2
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了 认证 doGetAuthenticationInfo");
        String name = "root";
        String password = "123456";
        UsernamePasswordToken userTokens = (UsernamePasswordToken)authenticationToken;
        if (!userTokens.getUsername().equals(name)){
            return null;
        }
        return new SimpleAuthenticationInfo("",password,"");
    }
}

Spring Security 安全框架

Spring Security于Shiro 非常像除了类名不一样

  • 功能权限
  • 访问权限
  • 菜单权限

固定骨架

package com.llt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurtyConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    AjaxAuthenticationEntryPoint authenticationEntryPoint;  //  未登陆时返回 JSON 格式的数据给前端(否则为 html)

    @Autowired
    AjaxAuthenticationSuccessHandler authenticationSuccessHandler;  // 登录成功返回的 JSON 格式数据给前端(否则为 html)

    @Autowired
    AjaxAuthenticationFailureHandler authenticationFailureHandler;  //  登录失败返回的 JSON 格式数据给前端(否则为 html)
    //授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        所有页面可以访问 功能页面有权限才可以访问
//        antMatchers 访问路径  permitAll 所有人都可以访问
        //hasRole 访问规则/权限·
        http.authorizeRequests()
         .antMatchers("/getuserlist").permitAll()
        .antMatchers("/adduser").hasRole("admin1")
        .and()
          .httpBasic()
           .authenticationEntryPoint(authenticationEntryPoint)

        ;

        //没权限进入登录页面 开启登录
        http.formLogin()
                .loginProcessingUrl("/adminlogin")
                .successHandler(authenticationSuccessHandler) // 登录成功
                .failureHandler(authenticationFailureHandler) // 登录失败
        ;
        //注销
        http.logout()
        .logoutUrl("/logout");
    }
    //认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //withUser 用户 password密码 roles 对应的规则
        //正常从数据库读取
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
         .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("admin1")
        .and()
            .withUser("lantian")
            .password(new BCryptPasswordEncoder().encode("123456")).roles("admin2")

        ;

    }
}


前后分离demo

  1. AjaxResponseBody 实体类
package com.llt.pojo;

import java.io.Serializable;

public class AjaxResponseBody implements Serializable {
    private String status;//状态码
    private String msg;//消息
    private Object result;//返回内容
    private String jwtToken;//加密
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public String getJwtToken() {
        return jwtToken;
    }

    public void setJwtToken(String jwtToken) {
        this.jwtToken = jwtToken;
    }
}

  1. AjaxAuthenticationEntryPoint 类方法
package com.llt.config;

import com.alibaba.fastjson.JSON;
import com.llt.pojo.AjaxResponseBody;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class AjaxAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        AjaxResponseBody responseBody = new AjaxResponseBody();
        responseBody.setStatus("000");
        responseBody.setMsg("Need Authorities!");
        httpServletResponse.getWriter().write(JSON.toJSONString(responseBody));
    }
}

  1. 配置文件
package com.llt.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.llt.pojo.AjaxResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@EnableWebSecurity
public class SecurtyJSONConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    AjaxAuthenticationEntryPoint authenticationEntryPoint; //未登陆时返回 JSON 格式的数据给前端(否则为 html)
    //授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/getuserlist").permitAll()
                .antMatchers("/adduser").hasRole("admin1")
                .and()
                .httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint);
    }
    //认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //withUser 用户 password密码 roles 对应的规则
        //正常从数据库读取
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
         .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("admin1")
        .and()
            .withUser("lantian")
            .password(new BCryptPasswordEncoder().encode("123456")).roles("admin2")

        ;

    }
}

异步任务 邮件发送 定时任务

  • 开启异步功能
package com.llt;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import springfox.documentation.oas.annotations.EnableOpenApi;

@EnableOpenApi
@EnableAsync//开启异步注解
@SpringBootApplication
//@MapperScan("com.llt.mapper") 都可以
public class SpringbootDataApplication {
//http://localhost:8080/swagger-ui/index.html api接口地址
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDataApplication.class, args);
    }

}

  • 异步任务注解 @Async
package com.llt.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class HelloService {
    @Async//配置步功能
  public void hello(){
      try {
          Thread.sleep(3000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      System.out.println("数据正在处理");
  }
}

  • 异步控制器
package com.llt.controller;

import com.llt.service.HelloService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(value = "异步测试接口",tags = {"异步测试接口"})
public class AsyncController {
    @Autowired
    HelloService helloService;
    @ApiOperation("三秒延迟接口")
    @GetMapping("/hello3s")

    public String getHello(){
        helloService.hello();//停止3s
        return "3s结束";
    }
}

邮件发送

  • xml
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • application yaml
spring:
  profiles:
    active: dev
  mail:
    username: asdasda@qq.com
    password: asdasda
    host: smtp.qq.com
    # QQ开启加密验证
    properties:
      mail:
        smtl:
          ssl:
            enable: true
  • 实现类已经帮我们实现了 我们可以直接用
package com.llt;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import sun.misc.BASE64Encoder;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.sql.DataSource;
import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class SpringbootDataApplicationTests {
    @Autowired
    DataSource dataSource;
    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Test
    void contextLoads() throws SQLException {

//        获得数据库连接
       Connection connection = dataSource.getConnection();
        System.out.println(connection);

        connection.close();
    }
    @Test
    public void sendMail(){
        //实现类
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("你好啊!!!");
        simpleMailMessage.setText("这是测试的数据你看你收到没回复我");
        simpleMailMessage.setFrom("asdasd@qq.com");
        simpleMailMessage.setTo("sadad@qq.com");
        javaMailSender.send(simpleMailMessage);
    }
    @Test
    //复杂的
    public void sendMail2() throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //组装
        /**
         * MimeMessageHelper 参数2 true 开启多文件
         */
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        mimeMessageHelper.setSubject("你好啊老色痞");
//        String s = ImageToBase64("D:\\class\\个人\\图库\\112.jpg");
        mimeMessageHelper.setText(
                "<h1 style='color:red'>福利板块哈哈</h1>" +
                        "<img src='sdasda.png' width='100%' height='100%'>",true
        );
        //附件

        mimeMessageHelper.addAttachment("1.jpg",
               new File("D:\\sadasd\\asdas\\asdasd\\112.jpg"));
        mimeMessageHelper.setFrom("asdasd@qq.com");
        mimeMessageHelper.setTo("asdasda@qq.com");
        javaMailSender.send(mimeMessage);
    }
    public static String ImageToBase64(String imagePath)  {
        InputStream in  = null;
        byte[] data = null;

        try {
            in =  new FileInputStream(imagePath);
            data = new byte[in.available()];//获取读的文件所有的字节个数
            in.read(data);//将文件上的字节读取到字节data数组中(内存上-容易内存溢出)
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(data);
    }

}

定时任务

  1. TaskScheduler 任务调度
  2. TaskExecutor 任务执行
  3. @EnableScheduling 开启定时功能的注解
  4. Scheduled 表示什么时候执行
  5. Cron表达式
  • 案例 需要在· 启动类上添加 @EnableScheduling
package com.llt.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
    //在特定时间执行代码
    //秒 分 时 日 月 周几
   @Scheduled(cron = "0/2 * * * * ?")
    public void hello(){
        System.out.println("hello 你被执行了");
    }
}

Swagger 处理接口文档

xml文件 3.0只要这一个就可以就包括ui部分
 <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
</dependency>
  • 3.0特殊之处 废除之前的注解在启动类上面添加 @EnableOpenApi
package com.llt;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;
@EnableOpenApi//开启接口UI
@SpringBootApplication
//@MapperScan("com.llt.mapper") 都可以
public class SpringbootDataApplication {
//http://localhost:8080/swagger-ui/index.html api接口地址
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDataApplication.class, args);
    }

}

配置文件

package com.llt.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {
//分多个组在添加一个docker
   @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.OAS_30)
                .groupName("后台信息");
    }
    @Bean
    public Docket createRestApi(Environment environment) {
        //设置现实swagger 环境
        Profiles of = Profiles.of("dev", "test");
        //通过environment.acceptsProfiles(of 获取当前是否在上面设置的环境
        boolean flag = environment.acceptsProfiles(of);
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())//基础配置信息
                .enable(flag)
                .select()

                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();

    }
    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()
                .title("刘蓝天web演示接口")
                .description("用于测试")
                .contact(new Contact("llt", "127.0.0.1:8080/swagger", "229236940@qq.com"))
                .version("1.0")
                .build();

    }
}

条件编译 开发环境用 生产环境不用

  • 注解
    @Vlaue("${swagger.enable}")
  • 通过类
 //设置现实swagger 环境
        Profiles of = Profiles.of("dev", "test");
        //通过environment.acceptsProfiles(of 获取当前是否在上面设置的环境
        boolean b = environment.acceptsProfiles(of);
  1. application配置文件
spring:
  profiles:
    active: dev

在这里插入图片描述

给控制器与接口添加注解

@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class mybatisController {


  @Autowired
    private UserService userService;
    @GetMapping("/getuserlist")
    @ResponseBody
    @ApiOperation("获取所有用户")
    public List<User> getAll(){
        List<User> all = userService.getAll();
        return all;
    }

给实体类添加api注解

package com.llt.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户ID")
    private Integer id;
    @ApiModelProperty("用户名")
    private String user;
    @ApiModelProperty("秘密")
    private String passd;

    public User() {

    }

    public User(Integer id, String user, String passd) {
        this.id = id;
        this.user = user;
        this.passd = passd;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassd() {
        return passd;
    }

    public void setPassd(String passd) {
        this.passd = passd;
    }
}

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页