springboot笔记

springboot

1.springboot是快速开发框架。微服务:将一个应用程序拆分为一个个可独立运行的微服务,每个服务专注于做一件事。

2.第一个springboot程序

主程序

@SpringBootApplication//标记为这是一个springboot的应用
public class Springboot01HelloworldApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(Springboot01HelloworldApplication.class, args);
    }
}

pom.xml依赖

<?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.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    //gav
    <groupId>com.scholar</groupId>
    <artifactId>springboot-01-helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-01-helloworld</name>
    <description>springboot-01-helloworld</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
<!-- 启动器,自动装配了web的所有环境-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
//单元测试
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
//插件
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
​
</project>
​

2.spring原理

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

spring-boot-starter就是启动器,想使用什么就导入什么。spring-boot-starter-web就是导入了web环境的所有依赖

3.springboot的理解

自动装配,run()方法

4.yml的使用

yaml可以替代peoperties。通过key:空格value来赋值

# 对象写法
student:
  name: lang
  age: 3
  #行内写法
  student: {name= lang,age: 3}
# 数组写法
pets:
  - cat
  - dog
  - bird
# 行内写法
  pets: [cat,dog,bird]
#可以通过debug= true来看哪些自动配置类生效了。哪些没生效

5.自动装配原理

//首先找到总的配置spring.factories,这个总的配置了spring的值。
//spring.factories里有不同的自动装配类,每个自动装配类@xxxautoConfiguration自动装配类,将这些类交给spring进行管理,每个自动装配类绑定一个@ConfigurationProperties(prefix = "xxx")对属性进行自定义赋值,当我们需要用到哪些属性时再application.yml对属性进行赋值。

6.静态资源加载

静态资源加载一般可以放在classpath(resource)下的static,public,resource中,其中优先级顺序是static>public>resource

7.首页加载

在静态资源下创建index.html,系统会默认访问这个页面为首页。如果出现乱码,添加
<meta charset="UTF-8">将乱码转换为utf-8。

8.页面跳转

如果需要进行页面跳转,springboot默认配置了视图解析器是在templates下的html页面,所以我们要跳转的页面必须放在templates下并且以html作为后缀名。如果要在页面接收参数,要通过th:text="${msg}来获取参数

9.thymeleaf前端语法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">//防止中文乱码
    <title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
<hr>

//foreach:将后端传的参数lang的值赋给user,然后将user输出到前端页面上
<div th:each="user:${lang}" th:text="${user}"></div>

</body>
</html>

10.cookie的作用域

cookie作用域是在一个浏览器内生效(默认),可以自己设置存活时间

11.员工管理系统

11.1编写实体类,连接数据库

11.2首页配置:
         1静态资源配置要导入thymeleaf依赖
         2.路径用@{/}

11.3页面国际化:
         1.我们需要配置i8n(国际化英文的简写,首字母和尾字母中间有18)文件
         2.我们如果需要在项目中使用按钮自动切换,需要自定义一个组件localeResolver
         3.要将自己写的组件装配到spring容器中,用@bean
         4.页面用#{}
11.4登录和拦截器
11.5员工列表展示
         1.提取公共页面
                 1.
                 2.
                 3.如果要传递参数,可以直接使用()传参,接收判断即可
         2.列表循坏展示

12.springboot-mybatis整合

//接口类
//mapper相当于以前的扫描包
@Mapper
//将这个接口注册到myabtis里
@Repository
public interface UserMapper {
    List<User> queryUser();
    User queryUserByid(int id);
    int addUser(User user);
    int updateUser(Map<String,Object> map);
    int deleteUser(int id);
}
//在resource下编写sql
<?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.scholar.mapper.UserMapper">
   <select id="queryUser" resultType="user">
      select * from user;
   </select>
<select id="queryUserByid" resultType="user">
   select * from user where id=#{id}
</select>
<insert id="addUser" parameterType="user">
   insert into user(id,name,password) values (#{id},#{name},#{password})
</insert>
   <update id="updateUser" parameterType="map">
      update user set name=#{name},password=#{password} where id=#{id}
   </update>
<delete id="deleteUser" parameterType="int">
   delete from user where id=#{id}
</delete>

</mapper>
mybatis:
  type-aliases-package: com.scholar.pojo  //对实体类起别名

  mapper-locations: classpath:mybatis/mapper/*.xml      //绑定xml配置文件,这个意思是resource下的mybatis目录下的mapper下的任意.xml文件,注意mybatis前不能加/因为加了就定位到了项目名了,这里定位的是resource
//将类注册到myabtis里
@RestController
public class MyController {
    //将类注入
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/queryByid")
    public User queryUserByid(){
        User user = userMapper.queryUserByid(1);
        return user;
    }
}

13.springboot-security搭建

1.先导入依赖

spring-boot-start-security

2.编写配置类,进行授权和认证,注意要对密码进行加密

package com.scholar.config;

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;
import sun.security.util.Password;

/**
 * //@auther huhuho
 * //@date 2022/4/16 16:04
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //授权
        http.authorizeRequests()
               .antMatchers("/").permitAll()
               .antMatchers("/level1/**").hasRole("vip1")
               .antMatchers("/level2/**").hasRole("vip2")
               .antMatchers("/level3/**").hasRole("vip3");
        //跳转到login
http.formLogin();
        //注销,然后放回到/下的页面
http.logout().logoutSuccessUrl("/");
        //记住我
http.rememberMe();
    }
    //认证

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("scholar").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
}

14.shiro

1.快速开始
​      1.1先导依赖(shiro-core,jcl-over-slf4j,log4j,slf4j-log4j)
       1.2编写shiro.xml
       1.3编写日志log4j.properties
       1.4编写实体类quickstart

15.shiro集成springboot

1.环境搭建,导入shiro-spring包

2.写配置类,UserRealm实现授权和认证,ShiroConfig实现shiro基本3大类

//创建realm对象
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        return null;
    }
}
@Configuration
public class ShiroConfig {
    //shirofilterfactorybean=====第三步
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //关联defaultWebSecurityManager
        bean.setSecurityManager(defaultWebSecurityManager);
        
        //拦截请求到login
         Map<String, String> filterMap=new LinkedHashMap<>();
        //拦截user路径下的所有路径,authc表示认证了才能访问
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);
        //如果没有认证就跳转到/toLogin
        bean.setLoginUrl("/toLogin");
        
        return bean;
    }
    //defaultwebsecuritymanager==========第二步
    @Bean(name ="SecurityManager" )
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager();
        //关联userRealm
        SecurityManager.setRealm(userRealm);
        return SecurityManager;
    }
    //创建realm对象,需要自定义====第一步
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

3.实现页面跳转和前端页面编写

@Controller
public class MyController {
    @RequestMapping("/")
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }
//跳转页面不需要加/,页面本身就在classpath下,路径要写/代表localhost:8080
    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
}

16.swagger

1.导包springfox-swagger2springfox-swagger-ui

2.编写配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    //创建多个docket可以创建多个角色
    @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("B");
    }
    @Bean
    public Docket docket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("C");
    }
    //一个docket就是一个角色
    @Bean
    public Docket docket(Environment environment){
//设置要显示swagger环境
        Profiles profiles = Profiles.of("dev", "test");
        //通过environment.acceptsProfiles来判断自己在哪个环境中,环境在properties里配置
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
               //设置是否启动,如果是在开发中启动,发布时不启动,通过配置文件
            //设置默认配置为dev的spring.profiles.active=dev,然后在dev里修改端口号
             .enable(flag)
                .select()
                //RequestHandlerSelectors:配置要扫描接口的方式
                //basePackage指定扫描包
                .apis(RequestHandlerSelectors.basePackage("com.scholar.controller"))
                .build();
    }
    //修改默认信息
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("scholar", "https://www.bilibili.com/", "6666@qq.com");
        return  new ApiInfo("scholar swagger",
                "牛哇",
                "1.0",
                "urn:tos",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }
}

3.实体类

//使用注解来进行注释
@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户名")
    public  String username;
    @ApiModelProperty("密码")
    public  String password;
}

4.提供接口

@RestController
public class MyController {
    @RequestMapping("/swagger")
    public String swagger(){
        return "hello,swagger";
    }

    @PostMapping("/user")
    public User user(){
        return  new User();
    }
}

小结:swagger是调节前后端分离的工具,使用swagger只需要导入springfox-swagger2springfox-swagger-ui,再在类上加@Configuration,@EnableSwagger2这两个注解就行.可以修改默认值和多个对象以及对复杂的类进行注释,方便前端使用。并且可以进行测试。

17.三大任务

1.异步任务

1.在方法上面加@aysnc
2.在主启动类上加@EnableAsync

2.邮件任务

先在配置文件中properties配置

spring.mail.username=1942682514@qq.com
//密码是smtp加密后的
spring.mail.password=dotwalllnyhzdbec
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

然后再测试类里(简单邮件发送)

@SpringBootTest
class TaskApplicationTests {
    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage MailMessage = new SimpleMailMessage();
        MailMessage.setSubject("你好,scholar");
        MailMessage.setText("加油,你是最棒的");
        MailMessage.setTo("1942682514@qq.com");
        MailMessage.setFrom("1942682514@qq.com");
        //邮件发送信息
        mailSender.send(MailMessage);
    }

}

复杂邮件发送

   @Test
    void contextLoads2() throws MessagingException {
//创建一个复杂邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper Helper = new MimeMessageHelper(mimeMessage, true);
        //发送标题
Helper.setSubject("你好,scholar");
//正文,带格式
Helper.setText("<p style='color:red'>\"加油,你是最棒的\"</p>",true);
//附件
Helper.addAttachment("qq",new File("C:\\Users\\19426\\Desktop\\1.png"));
//发送给谁
Helper.setTo("1942682514@qq.com");
//谁发送消息
        Helper.setFrom("1942682514@qq.com");
        //邮件发送信息
        mailSender.send(mimeMessage);

    }

3.定时执行任务

3.1先在主启动类上加注解@EnableScheduling//开启定时执行注解,再类上加注解 @Scheduled//启动定时

3.2然后编写类

@Service
public class ScheduledService {
    //6个数分别代表秒,分,时,日,月,周几(周天表达为0或7),?代表是随便是周几  6#3代表每个月第三周礼拜五
    @Scheduled(cron = "0 * * * * ?")
    public void hello(){
        System.out.println("定时操作");
    }
}

3.3启动主启动类加载任务

18分布式以及RPC

18.1.分布式:指当一个计算机无法完成某个任务时,将这个任务交给某些计算机完成。这些计算机连接了同一网络,为了完成同一目标而运行,我们将这些计算机看作是一个计算机系统,通过nigax进行负载均衡。例如淘宝(多个计算机完成,但是用户看相当于同一计算机)

18.2:RPC类似于http协议,都是基于网络进行通信的。是远程通信协议。有两个最大的特点:通信和序列化
序列化:在两台计算机通信时,发送方将信息封装到文件中,序列化变成计算机能看懂得二进制代码,接收方将进行反序列化,读取文件。
18.3:dubbo是RPC框架,而RPC是是远程调用,帮助分布式调用计算机之间的联系。
18.4:zookeeper是分布式的,开放源码的分布式应用程序协调服务

19.idea注意事项

1.maven项目有父依赖,maven项目的依赖在父依赖导就行。
  springboot项目都是独立的,poml要单独导。
2.maven项目在父依赖导就行
依赖就是一些jar包,jar包就是将编写的类进行打包,项目中导入jar包就可以调用类的方法。
extreme lib里放的是本地仓库里的东西

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值