狂神说SpringBoot学习笔记_暂存

1.全面接管SpringMVC的配置!实操!

2.yaml可以直接给实体类赋值。

jar:webapp!

自动装配

Springboot到底帮我们配置了什么?我们能不能进行修改?能修改哪些东西?能不能扩展?

  • xxxxAutoConfiguration...向容器中自动配置组件
  • xxxProperties:自动配置类,装配配置文件中自定义的一些内容!

要解决的问题:

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

总结:

  1. 在springboot中我们可以使用以下方式处理静态资源:
    1. webjars  localhost:8080/webjars
    2. public, static, /**, resources  localhost:8080
  2. 优先级:resources>static(默认)>public

首页如何定制:

模板引擎:

结论:只要需要使用thymeleaf,只需要导入对应的依赖就可以了!我们将html放在我们的templates目录下即可!

1 public static final String DEFAULT_PREFIX = "classpath:/templates/";
2 public static final String DEFAULT_SUFFIX = ".html";

 在springboot中,有非常多的xxxxConfiguration帮助我们进行扩展配置,只要看见了这个东西,我们就要注意了!

1.首页配置:

  1.注意点,所有页面的静态资源都需要使用thymeleaf接管;

  2.url: @{}

2.页面国际化:

  1.我们需要配置i18n文件

  2.我们如果需要在项目中进行按钮自动切换,我们需要自定义一个组件LocaleResolver

  3.记得将自己写的组件配置到spring容器“@Bean”

  4.#{}

3.登录+拦截器

4.员工列表展示

  1.提取公共页面

    1.th:fragment="sidebar"

    2.<div th:replace="~{commons/commons::topbar}"></div>

    3.如果要传递参数,可以直接使用()传参,接收判断即可

  2.列表循环展示

5.添加员工

  1.按钮提交

  2.跳转到添加页面

  3.添加员工成功

  4.返回首页

6.CRUD搞定

7.404

 

前端:

  • 模板:别人写好的,我们拿来改成自己需要的
  • 框架:组件:自己手动组合拼接!    Bootstrap,Layui,semantic-ui
    • 栅格系统
    • 导航栏
    • 侧边栏
    • 表单

 

# 1. 前端搞定:页面长什么样子:数据

# 2. 设计数据库(数据库设计难点!)

# 3. 前端让他能够自动运行,独立化工程

# 4. 数据接口如何对接:json,对象 all in one !

# 5. 前后端联调测试!


1. 有一套自己熟悉的后台模板:工作必要!x-admin
2. 前端界面:至少自己能够通过前端框架,组合出来一个网站页面
- index
- about
- blog
- post
- user
3. 让这个网站能够独立运行!(哪怕是增删改查,到目前为之,全心全意扑在上面至少也要花一个月的时间)

一个月!

上述具体见springboot-03-web项目。

上周回顾:
  • SpringBoot是什么?
  • 微服务
  • HelloWorld~
  • 探究源码~自动装配原理~
  • 配置 yaml
  • 多文档环境切换
  • 静态资源映射
  • Thymeleaf th:xxx
  • SpringBoot如何扩展MVC javaconfig~
  • 如何修改SpringBoot的默认配置
  • CRUD
  • 国际化
  • 拦截器
  • 定制首页,错误页

这周:

  • JDBC
  • MyBatis:重点
  • Druid:重点
  • Shiro:安全:重点
  • Spring Security:安全:重点
  • 异步任务,邮件发送,定时任务
  • Swagger
  • Dubbo + Zookeeper

Data:

Spring:bean

MyBatis:

整合包:

mybatis-spring-boot-starter

MVC:

M:数据和业务

V:HTML

C:交接

1.导入包

2.配置文件

3.mybatis配置

4.编写sql

5.业务层调用dao层

6.controller调用service层

SpringSecurity(安全)

在web开发中,安全第一位!过滤器,拦截器

功能性需求:否

做网站:安全应该在什么时候考虑?设计之初

  • 漏洞,隐私泄露
  • 架构一旦确定

shiro、SpringSecurity:很像,除了类不一样,名字不一样

认证,授权(vip1,vip2,vip3)

  • 功能权限
  • 访问权限
  • 菜单权限
  • ...拦截器,过滤器:大量的原生代码,冗余

MVC----Spring----SpringBoot----框架思想

2023-03-08;

P34;

RouterController;

package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouterController {

    @RequestMapping({"/", "/index"})
    public String index() {
        return "index";
    }

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

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id) {
        return "views/level1/" + id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id) {
        return "views/level2/" + id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id) {
        return "views/level3/" + id;
    }
}

AOP:横切~配置类;

2023-03-09;

P35;用户认证和授权;


/**
* AOP:拦截器!
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

/**
* 授权
* @param http
* @throws Exception
*/
@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("/");
}

/**
* 认证,springboot 2.1.X 可以直接使用
* 密码编码:PasswordEncoder
* 在Spring Security 5.0+ 新增了很多的加密方法
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

// 这些数据正常应该从数据库中读
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");

}
}
 

2023-03-10;

<!--登录注销-->
            <div class="right menu">

                <!-- 如果未登录 -->
                <div sec:authorize="!isAuthenticated()">
                    <a class="item" th:href="@{/toLogin}">
                        <i class="address card icon"></i> 登录
                    </a>
                </div>

                <!--如果登录:用户名,注销-->
                <div sec:authorize="isAuthenticated()">
                    <a class="item">
                        用户名:<span sec:authentication="name"></span>
                        <!--                        角色:<span sec:authentication=""></span>-->
                    </a>
                </div>
                <div sec:authorize="isAuthenticated()">
                    <a class="item" th:href="@{/logout}">
                        <i class="sign-out icon"></i> 注销
                    </a>
                </div>

            </div>
<!-- security-thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

2023-03-15;

// SecurityConfig.java

/**
     * 授权
     * @param http
     * @throws Exception
     */
    @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
        // 定制登录页 loginPage("/toLogin");
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

        // 注销,开启了注销功能,跳到首页

        // 防止网站攻击:get,post
        http.csrf().disable(); // 关闭csrf功能,登出失败可能存在的原因
        http.logout().logoutSuccessUrl("/");

        // 开启记住我功能 cookie,默认保存两周
        http.rememberMe();
    }
<!-- login.html -->

<form th:action="@{/login}" method="post">
                            <div class="field">
                                <label>Username</label>
                                <div class="ui left icon input">
                                    <input type="text" placeholder="Username" name="user">
                                    <i class="user icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <label>Password</label>
                                <div class="ui left icon input">
                                    <input type="password" name="pwd">
                                    <i class="lock icon"></i>
                                </div>
                            </div>
                            <input type="submit" class="ui blue submit button"/>
                        </form>

 2023-03-16;

<div class="field">
                                <input type="checkbox" name="remember"> 记住我
                            </div>
// 开启记住我功能 cookie,默认保存两周,自定义接收前端的参数
        http.rememberMe().rememberMeParameter("remember");

Shiro

1.导入依赖;

<dependencies>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

2.配置文件;

3.hello world;

2023-03-19;

1.Shrio的Subject分析;

Spring Security都有!

Subject currentUser = SecurityUtils.getSubject();
Sesscion session = currentUser.getSession();
currentUser.isAuthenticated();
currentUser.getPrincipal();
currentUser.hasRole("schwartz");
currentUser.isPermitted("lightsaber:wield");
currentUser.logout();

2023-03-20;

1.Spring Boot中集成;

1.1引入依赖:

<dependencies>

<!--
Subject 用户
SecurityManager 管理所有用户
Realm 连接数据
-->

<!-- shiro整合spring的包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf模板 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

1.2UserRealm.java;

/**
 * 自定义的 UserRealm   extends AuthorizingRealm
 */
public class UserRealm extends AuthorizingRealm {

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        return null;
    }
}

1.3ShiroConfig.java;

@Configuration
public class ShiroConfig {

    /**
     * ShiroFilterFactoryBean:3
     * @param defaultWebSecurityManager
     * @return
     */
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        return bean;
    }

    /**
     * DefaultWebSecurityManager:2
     * @param userRealm
     * @return
     */
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 创建 realm 对象,需要自定义:1
     * @return
     */
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

1.4测试页面;

MyController.java;

@Controller
public class MyController {

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

    @RequestMapping("/user/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update() {
        return "user/update";
    }
}

index.html;

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>首页</h1>
<p th:text="${msg}"></p>
<hr>

<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>


</body>
</html>

add.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>add</h1>

</body>
</html>

update.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>update</h1>

</body>
</html>

2023-03-21;

1.Shiro实现登录拦截;

ShiroConfig.java;

/**
     * ShiroFilterFactoryBean:3
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        // 添加shiro的内置过滤器
        /**
         * anon:无需认证就可以访问
         * authc:必须认证了才能访问
         * user:必须拥有 记住我 功能才能用
         * perms:拥有对某个资源的权限才能访问;
         * role:拥有某个角色权限才能访问
         *
         * filterMap.put("/user/add", "authc");
         * filterMap.put("/user/update", "authc");
         */
        // 拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/*", "authc");
        bean.setFilterChainDefinitionMap(filterMap);

        // 设置登录的请求
        bean.setLoginUrl("/toLogin");

        return bean;
    }

2.Shiro实现用户认证;

UserRealm.java;

/**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");

        // 用户名,密码~  数据库中取
        String name = "root";
        String password = "123456";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        if (!name.equals(userToken.getUsername())) {
            return null; // 抛出异常 UnknownAccountException
        }

        // 密码认证,Shiro做
        return new SimpleAuthenticationInfo("", password,"");
    }

login.html;

<h1>登录</h1>
<hr>
<p th:text="${msg}" style="color: red;"></p>
<form th:action="@{/login}">
    <p>用户名:<input type="text" name="username"></p>
    <p>密码:<input type="text" name="password"></p>
    <p><input type="submit"></p>
</form>

2023-03-25;

1.pom.xml;

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <!-- 引入myBatis,这是MyBatis官方提供的适配pringBoot的,而不是SpringBoot自己的 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

2.application.yaml;

spring:
  datasource:
    username: root
    password: root
    #?serverTimezone=UTC解决时区的问题
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spirng Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    # 配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御SQL注入
    # 如果允许时报错 java.lang.ClassNotFoundException:org.apache.log4j.Priority
    # 则导入log4j依赖即可,Maven地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.application.properties;

mybatis.type-aliases-package=com.kuang.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

4.UserMapper.java;

@Repository
@Mapper
public interface UserMapper {

    public User queryUserByName(String name);
}

5.UserMapper.xml;

<?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.kuang.mapper.UserMapper">

    <select id="queryUserByName" parameterType="String" resultType="User">
        select * from mybatis.user where name = #{name}
    </select>

</mapper>

6.UserService.java;

public interface UserService {

    public User queryUserByName(String name);
}

7.UserServiceImpl.java;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

8.ShiroSpringbootApplicationTests.java;

@SpringBootTest
class ShiroSpringbootApplicationTests {

    @Autowired
    UserServiceImpl userService;

    @Test
    void contextLoads() {
        System.out.println(userService.queryUserByName("kuangshen"));
    }

}

9.结果:输出;

User(id=1, name=kuangshen, pwd=123456)

2023-03-26;

1.Shiro整合MyBatis;

UserRealm.java;

/**
 * 自定义的 UserRealm   extends AuthorizingRealm
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());

        if (user == null) { // 没有这个人
            return null; // UnknownAccountException
        }

        // 可以加密:    MD5:e10adc3949ba59abbe56e057f20f883e    MD5盐值加密:e10adc3949ba59abbe56e057f20f883eusername
        // 密码认证,Shiro做,加密了
        return new SimpleAuthenticationInfo("", user.getPwd(),"");
    }
}

2.Shiro请求授权实现;

UserRealm.java;

/**
 * 自定义的 UserRealm   extends AuthorizingRealm
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        // SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");

        // 拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal(); // 拿到user对象

        // 设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        // return info;
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());

        if (user == null) { // 没有这个人
            return null; // UnknownAccountException
        }

        // 可以加密:    MD5:e10adc3949ba59abbe56e057f20f883e    MD5盐值加密:e10adc3949ba59abbe56e057f20f883eusername
        // 密码认证,Shiro做,加密了
        return new SimpleAuthenticationInfo(user, user.getPwd(),"");
    }
}

ShiroConfig.java;

/**
     * ShiroFilterFactoryBean:3
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        // 添加shiro的内置过滤器
        /**
         * anon:无需认证就可以访问
         * authc:必须认证了才能访问
         * user:必须拥有 记住我 功能才能用
         * perms:拥有对某个资源的权限才能访问;
         * role:拥有某个角色权限才能访问
         *
         * filterMap.put("/user/add", "authc");
         * filterMap.put("/user/update", "authc");
         */
        // 拦截
        Map<String, String> filterMap = new LinkedHashMap<>();

        // 授权,正常的情况下,没有授权会跳转到未授权页面
        filterMap.put("/user/add", "perms[user:add]");
        filterMap.put("/user/update", "perms[user:update]");

        filterMap.put("/user/*", "authc");
        bean.setFilterChainDefinitionMap(filterMap);

        // 设置登录的请求
        bean.setLoginUrl("/toLogin");
        // 未授权页面
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

MyController.java;

@RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized() {
        return "未经授权无法访问此页面";
    }

User.java;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    private int id;
    private String name;
    private String pwd;
    private String perms;
}

 2023-04-08;

P45:Shiro整合Thymeleaf;

1.pom.xml;

<!-- shiro-thymeleaf整合 -->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

2.UserRealm.java;

/**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());

        if (user == null) { // 没有这个人
            return null; // UnknownAccountException
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser", user);

        // 可以加密:    MD5:e10adc3949ba59abbe56e057f20f883e    MD5盐值加密:e10adc3949ba59abbe56e057f20f883eusername
        // 密码认证,Shiro做,加密了
        return new SimpleAuthenticationInfo(user, user.getPwd(),"");
    }

3.ShiroConfig.java;

// 整合ShiroDialect:用来整合 Shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }

4.index.html;

<!-- 从session中判断值 -->
<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录</a>
</div>
<p th:text="${msg}"></p>
<hr>

<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">add</a>
</div>

<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">update</a>
</div>

P47:Swagger介绍及集成;

 1.pom.xml;

<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.HelloController.java;

@RestController
public class HelloController {

    // /error
    @RequestMapping(value = "/hello")
    public String hello() {
        return "hello";
    }
}

3.SwaggerConfig.java;

@Configuration
@EnableSwagger2  // 开启Swagger2
public class SwaggerConfig {

    /**
     * 配置了Swagger的Docket的bean实例
     * @return
     */
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    /**
     * 配置Swagger信息=apiInfo
     */
    private ApiInfo apiInfo() {
        return new ApiInfo("Api Documentation",
                "Api Documentation",
                "1.0",
                "urn:tos",
                DEFAULT_CONTACT,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }
}

 

进行到P48 05:47。

posted on 2023-03-08 23:25  平凡力量  阅读(227)  评论(0编辑  收藏  举报