主頁 > 後端開發 > springboot整合spring security最完整,只看這一篇就夠了

springboot整合spring security最完整,只看這一篇就夠了

2021-04-09 06:17:56 後端開發

本人結合其他博客和自己查詢的資料,一步一步實作整合了security安全框架,其中踩過不少的坑,也有遇到許多不懂的地方,為此做個記錄,

開發工具:ide、資料庫:mysql5.7、springboot版本:2.3.7

個人對Spring Security的執行程序大致理解(僅供參考)

 

 

使用Spring Security很簡單,只要在pom.xml檔案中,引入spring security的依賴就可以了

pom配置:

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

這個時候我們不在組態檔中做任何配置,隨便寫一個Controller 

@RestController
public class TestController {
    @GetMapping("/hello")
    public String request() {
        return "hello";
    }
}

啟動專案,我們會發現有這么一段日志

此時表示Security生效,默認對專案進行了保護,我們訪問該Controller中的介面(http://localhost:8080/securitydemo/hello),會見到如下登錄界面(此界面為security框架自帶的默認登錄界面,后期不用可以換成自定義登錄界面)

 這里面的用戶名和密碼是什么呢?此時我們需要輸入用戶名:user,密碼則為之前日志中的"19262f35-9ded-49c2-a8f6-5431536cc50c",輸入之后,我們可以看到此時可以正常訪問該介面

 

在老版本的Springboot中(比如說Springboot 1.x版本中),可以通過如下方式來關閉Spring Security的生效,但是現在Springboot 2中已經不再支持

security:
  basic:
    enabled: false

springboot2.x后可以在啟動類中設定

1、配置基于記憶體的角色授權和認證資訊

  1.1目錄

  

  1.2 WebSecurityConfg配置類

  Spring Security的核心配置類是 WebSecurityConfigurerAdapter抽象類,這是權限管理啟動的入口,這里我們自定義一個實作類去它,

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description SpringSecurity安全框架配置
 */
@Configuration
@EnableWebSecurity//開啟Spring Security的功能
//prePostEnabled屬性決定Spring Security在介面前注解是否可用@PreAuthorize,@PostAuthorize等注解,設定為true,會攔截加了這些注解的介面
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfg extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
        * 基于記憶體的方式,創建兩個用戶admin/123456,user/123456
        * */
        auth.inMemoryAuthentication()
                .withUser("admin")//用戶名
                .password(passwordEncoder().encode("123456"))//密碼
                .roles("ADMIN");//角色
        auth.inMemoryAuthentication()
                .withUser("user")//用戶名
                .password(passwordEncoder().encode("123456"))//密碼
                .roles("USER");//角色
    }

    /**
     * 指定加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        // 使用BCrypt加密密碼
        return new BCryptPasswordEncoder();
    }
}

  1.3 MainController控制器介面

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description 主控制器
 */
@RestController
public class MainController {

    @GetMapping("/hello")
    public String printStr(){
        System.out.println("hello success");
        return "Hello success!";
    }

}

這樣重新運行后我們就可以通過admin/123456、user/123456兩個用戶登錄了,

當然,你也可以基于組態檔創建用戶賬號,在pom.xml中添加:

 2、配置基于資料庫的認證資訊和角色授權

  2.1 目錄

   2.2  CustomUserDetailsService實作類

UserDetailsService是需要實作的登錄用戶查詢的service介面,實作loadUserByUsername()方法,這里我們自定義CustomUserDetailsService實作類去實作UserDetailsService介面

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description
 */

@Component
public class CustomUserDetailsService implements UserDetailsService {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        /**
         * 1/通過userName 獲取到userInfo資訊
         * 2/通過User(UserDetails)回傳details,
         */
        //通過userName獲取用戶資訊
        UserInfo userInfo = userInfoService.getUserInfoByUsername(userName);
        if(userInfo == null) {
            throw new UsernameNotFoundException("not found");
        }
        //定義權限串列.
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 用戶可以訪問的資源名稱(或者說用戶所擁有的權限) 注意:必須"ROLE_"開頭
        authorities.add(new SimpleGrantedAuthority("ROLE_"+ userInfo.getRole()));
        User userDetails = new User(userInfo.getUserName(),passwordEncoder.encode(userInfo.getPassword()),authorities);
        return userDetails;
    }
}
WebSecurityConfg配置類:
/**
 * @Author qt
 * @Date 2021/3/25
 * @Description SpringSecurity安全框架配置
 */
@Configuration
@EnableWebSecurity//開啟Spring Security的功能
//prePostEnabled屬性決定Spring Security在介面前注解是否可用@PreAuthorize,@PostAuthorize等注解,設定為true,會攔截加了這些注解的介面
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfg extends WebSecurityConfigurerAdapter {
    /**
     * 指定加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        // 使用BCrypt加密密碼
        return new BCryptPasswordEncoder();
    }
}

對于通過userName獲取用戶資訊的服務層,持久層和資料庫陳述句就不介紹了,這里使用的是SSM框架,使用mybaits,

  2.3 資料庫設計

 

 角色表 roles

用戶表 user

用戶角色關系表 roles_user

 3、自定義表單認證登錄

  3.1 目錄

  

   3.2  WebSecurityConfg核心配置類

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description spring-security權限管理的核心配置
 */
@Configuration
@EnableWebSecurity//開啟Spring Security的功能
//prePostEnabled屬性決定Spring Security在介面前注解是否可用@PreAuthorize,@PostAuthorize等注解,設定為true,會攔截加了這些注解的介面
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfg extends WebSecurityConfigurerAdapter {

    @Resource
    private AuthenticationSuccessHandler loginSuccessHandler; //認證成功結果處理器
    @Resource
    private AuthenticationFailureHandler loginFailureHandler; //認證失敗結果處理器

    //http請求攔截配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();//開啟運行iframe嵌套頁面

        http//1、配置權限認證
            .authorizeRequests()
                //配置不攔截路由
                .antMatchers("/500").permitAll()
                .antMatchers("/403").permitAll()
                .antMatchers("/404").permitAll()
                .antMatchers("/login").permitAll()
                .anyRequest() //任何其它請求
                .authenticated() //都需要身份認證
                .and()
             //2、登錄配置表單認證方式
            .formLogin()
                .loginPage("/login")//自定義登錄頁面的url
                .usernameParameter("username")//設定登錄賬號引數,與表單引數一致
                .passwordParameter("password")//設定登錄密碼引數,與表單引數一致
                // 告訴Spring Security在發送指定路徑時處理提交的憑證,默認情況下,將用戶重定向回用戶來自的頁面,登錄表單form中action的地址,也就是處理認證請求的路徑,
                // 只要保持表單中action和HttpSecurity里配置的loginProcessingUrl一致就可以了,也不用自己去處理,它不會將請求傳遞給Spring MVC和您的控制器,所以我們就不需要自己再去寫一個/user/login的控制器介面了
                .loginProcessingUrl("/user/login")//配置默認登錄入口
                .defaultSuccessUrl("/index")//登錄成功后默認的跳轉頁面路徑
                .failureUrl("/login?error=true")
                .successHandler(loginSuccessHandler)//使用自定義的成功結果處理器
                .failureHandler(loginFailureHandler)//使用自定義失敗的結果處理器
                .and()
            //3、注銷
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new CustomLogoutSuccessHandler())
                .permitAll()
                .and()
            //4、session管理
            .sessionManagement()
                .invalidSessionUrl("/login") //失效后跳轉到登陸頁面
                //單用戶登錄,如果有一個登錄了,同一個用戶在其他地方登錄將前一個剔除下線
                //.maximumSessions(1).expiredSessionStrategy(expiredSessionStrategy())
                //單用戶登錄,如果有一個登錄了,同一個用戶在其他地方不能登錄
                //.maximumSessions(1).maxSessionsPreventsLogin(true) ;
                .and()
            //5、禁用跨站csrf攻擊防御
            .csrf()
                .disable();
    }
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        //配置靜態檔案不需要認證
        web.ignoring().antMatchers("/static/**");
    }

    /**
     * 指定加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        // 使用BCrypt加密密碼
        return new BCryptPasswordEncoder();
    }
}

踩坑點1:登錄頁面介面/login和登錄驗證介面/user/login,這里是自己之前一直搞錯的重點,這里就用網上的圖片展示了

踩坑點2:springboot配置spring security 靜態資源不能訪問

security的配置:在類WebSecurityConfig繼承WebSecurityConfigurerAdapter,這個類是我們在配置security的時候,對我們請求的url及權限規則的一些認證配置,具體的不說了,這里主要是靜態資源的問題,

在這個類中我們會重寫一些方法,其中就有一個方法,可以為我們配置一下靜態資源不需要認證,

@Override
    public void configure(WebSecurity web) throws Exception {
        //配置靜態檔案不需要認證
        web.ignoring().antMatchers("/static/**");
    }

頁面的參考如下:

 <link rel="stylesheet" th:href="https://www.cnblogs.com/qiantao/p/@{static/layui/css/layui.css}">

之后我們啟動專案:看到css并沒有生效

 這時候僅僅通過spring security配置是不夠的,我們還需要去重寫addResourceHandlers方法去映射下靜態資源,這個方法應該很熟悉了,我們通過springboot添加攔截器的時候就會用到這個,

寫一個類WebMvcConfig繼承WebMvcConfigurationSupport,注意spring boot2版本和1版本是不一樣的,spring boot1版本繼承的WebMvcConfigurerAdapter在spring boot2版本中已經提示過時了

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 配置靜態資源
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }
}

現在重新啟動專案:css檔案已經參考成功,

 3.3  ErrorPageConfig 配置錯誤頁面

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description 配置錯誤頁面 403 404 500  適用于 SpringBoot 2.x
 */
@Configuration
public class ErrorPageConfig {

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        WebServerFactoryCustomizer<ConfigurableWebServerFactory> webCustomizer = new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                ErrorPage[] errorPages = new ErrorPage[] {
                        new ErrorPage(HttpStatus.FORBIDDEN, "/403"),
                        new ErrorPage(HttpStatus.NOT_FOUND, "/404"),
                        new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"),
                };
                factory.addErrorPages(errorPages);
            }
        };
        return webCustomizer;
    }
}

 3.4 MainController 控制器

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description 主控制器
 */
@Controller
public class MainController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @GetMapping("/login")
    public String loginPage(){
        System.out.println("login page");
        return "login";
    }
    @GetMapping("/index")
    @PreAuthorize("hasAnyRole('USER','ADMIN')")
    public String index(){
        System.out.println("index page");
        return "index";
    }


    @GetMapping("/admin")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public String printAdmin(){
        System.out.println("hello admin");
        return "admin";
    }

    @GetMapping("/user")
    @PreAuthorize("hasAnyRole('USER','ADMIN')")
    public String printUser(){
        System.out.println("hello user");
        return "user";
    }

    /**
     * 找不到頁面
     */
    @GetMapping("/404")
    public String notFoundPage() {
        return "/error/404";
    }
    /**
     * 未授權
     */
    @GetMapping("/403")
    public String accessError() {
        return "/error/403";
    }
    /**
     * 服務器錯誤
     */
    @GetMapping("/500")
    public String internalError() {
        return "/error/500";
    }
}

3.5 UserInfoController 用戶控制器

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description
 */
@Controller
@RequestMapping("/user")
public class UserInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private UserInfoService userInfoService;

    @GetMapping("/getUserInfo")
    @ResponseBody
    public User getUserInfo(@RequestParam String username){
        return userInfoService.getUserInfoByUsername(username);
    }
}

SMM框架的其他部分就省略了,非這里重點,

3.6 CustomAccessDecisionManager 自定義權限決策管理器

/**
 * @Author qt
 * @Date 2021/3/31
 * @Description 自定義權限決策管理器
 */
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {

    /**
     * @Author: qt
     * @Description: 取當前用戶的權限與這次請求的這個url需要的權限作對比,決定是否放行
     * auth 包含了當前的用戶資訊,包括擁有的權限,即之前UserDetailsService登錄時候存盤的用戶物件
     * object 就是FilterInvocation物件,可以得到request等web資源,
     * configAttributes 是本次訪問需要的權限,即上一步的 MyFilterInvocationSecurityMetadataSource 中查詢核對得到的權限串列
     **/
    @Override
    public void decide(Authentication auth, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        Iterator<ConfigAttribute> iterator = collection.iterator();
        while (iterator.hasNext()) {
            if (auth == null) {
                throw new AccessDeniedException("當前訪問沒有權限");
            }
            ConfigAttribute ca = iterator.next();
            //當前請求需要的權限
            String needRole = ca.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) {
                if (auth instanceof AnonymousAuthenticationToken) {
                    throw new BadCredentialsException("未登錄");
                } else
                    return;
            }
            //當前用戶所具有的權限
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("權限不足!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

3.7 CustomLogoutSuccessHandler 注銷登錄處理

/**
 * @Author qt
 * @Date 2021/3/31
 * @Description 注銷登錄處理
 */
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("注銷成功!");
        //這里寫你登錄成功后的邏輯
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("注銷成功!");
    }
}

3.8 LoginFailureHandler 登錄失敗處理

/**
 * @Author qt
 * @Date 2021/3/24
 * @Description 登錄失敗處理
 */
@Component("loginFailureHandler")
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("登錄失敗");
        this.saveException(request, exception);
        this.getRedirectStrategy().sendRedirect(request, response, "/login?error=true");
    }
}

 3.9 LoginSuccessHandler 登錄成功處理

/** @Author qt 
* @Date 2021/3/24 * @Description 登錄成功處理
*/ @Component("loginSuccessHandler") public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Resource private ObjectMapper objectMapper; private RequestCache requestCache; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { // 獲取前端傳到后端的全部引數 Enumeration enu = request.getParameterNames(); while (enu.hasMoreElements()) { String paraName = (String) enu.nextElement(); System.out.println("引數- " + paraName + " : " + request.getParameter(paraName)); } logger.info("登錄認證成功"); //這里寫你登錄成功后的邏輯,可以驗證其他資訊,如驗證碼等,
response.setContentType("application/json;charset=UTF-8"); JSONObject resultObj = new JSONObject(); resultObj.put("code", HttpStatus.OK.value()); resultObj.put("msg","登錄成功"); resultObj.put("authentication",objectMapper.writeValueAsString(authentication)); response.getWriter().write(resultObj.toString()); this.getRedirectStrategy().sendRedirect(request, response, "/index");//重定向 } }

3.10 login.html 登錄頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
    <link rel="stylesheet" type="text/css" th:href="@{static/layui/css/layui.css}">
</head>
<body>
<form method="POST" th:action="@{/user/login}">
    <div>
        用戶名:<input type="text" name="username" id="username">
    </div>
    <div>
        密碼:<input type="password" name="password" id="password">
    </div>
    <div>
         <button type="submit">立即登陸</button>
    </div>
    <!-- 以下為顯示認證失敗等提示資訊(th:if=""一定要寫 )-->
    <span style="color: red;" th:if="${param.error}" th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message}"></span>
</form>
</body>
</html>

 3.11 效果圖片

登錄失敗

 

 登錄成功

 4、自定義ajax請求認證登錄

本人比較喜歡使用ajax的登錄認證方式,這個比較靈活,

   4.1 目錄

   4.2、較表單登錄認證的改變

  LoginFailureHandler 登錄失敗處理

/**
 * @Author qt
 * @Date 2021/3/24
 * @Description 登錄失敗處理
 */
@Component("loginFailureHandler")
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("登錄失敗");
        response.setContentType("application/json;charset=UTF-8");
        //這里寫你登錄失敗后的邏輯,可加驗證碼驗證等
        String errorInfo = "";
        if (exception instanceof BadCredentialsException ||
                exception instanceof UsernameNotFoundException) {
            errorInfo = "賬戶名或者密碼輸入錯誤!";
        } else if (exception instanceof LockedException) {
            errorInfo = "賬戶被鎖定,請聯系管理員!";
        } else if (exception instanceof CredentialsExpiredException) {
            errorInfo = "密碼過期,請聯系管理員!";
        } else if (exception instanceof AccountExpiredException) {
            errorInfo = "賬戶過期,請聯系管理員!";
        } else if (exception instanceof DisabledException) {
            errorInfo = "賬戶被禁用,請聯系管理員!";
        } else {
            errorInfo = "登錄失敗!";
        }
        logger.info("登錄失敗原因:" + errorInfo);
        //ajax請求認證方式
        JSONObject resultObj = new JSONObject();
        resultObj.put("code", HttpStatus.UNAUTHORIZED.value());
        resultObj.put("msg",errorInfo);
        resultObj.put("exception",objectMapper.writeValueAsString(exception));
        response.getWriter().write(resultObj.toString());

        //表單認證方式
        //this.saveException(request, exception);
        //this.getRedirectStrategy().sendRedirect(request, response, "/login?error=true");
    }
}
LoginSuccessHandler 登錄成功處理
/**
 * @Author qt
 * @Date 2021/3/24
 * @Description 登錄成功處理
 */
@Component("loginSuccessHandler")
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        // 獲取前端傳到后端的全部引數
          Enumeration enu = request.getParameterNames();
          while (enu.hasMoreElements()) {
              String paraName = (String) enu.nextElement(); System.out.println("引數- " + paraName + " : " + request.getParameter(paraName));
          }
        logger.info("登錄認證成功");
        //這里寫你登錄成功后的邏輯,可加驗證碼驗證等

        //ajax請求認證方式
        JSONObject resultObj = new JSONObject();
        resultObj.put("code", HttpStatus.OK.value());
        resultObj.put("msg","登錄成功");
        resultObj.put("authentication",objectMapper.writeValueAsString(authentication));
        response.getWriter().write(resultObj.toString());

        //表單認證方式
        //this.getRedirectStrategy().sendRedirect(request, response, "/index");//重定向
    }
}

login.html 登錄頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
    <link rel="stylesheet" type="text/css" th:href="@{static/layui/css/layui.css}">
</head>
<body>
<form method="POST" action="">
    <div>
        用戶名:<input type="text" name="username" id="username">
    </div>
    <div>
        密碼:<input type="password" name="password" id="password">
    </div>
    <div>
        <input type="button" name="login" id="login" th:value="立即登陸" onclick="mylogin()">
    </div>
</form>

<script type="text/javascript" charset="utf-8" th:src="@{static/jquery/jquery-3.5.1.min.js}"></script>
<script type="text/javascript" charset="utf-8" th:src="@{static/layui/layui.js}"></script>
<script th:inline="javascript" type="text/javascript">
    layui.use(['form','jquery','layedit', 'laydate'], function () {
        var $ = layui.jquery,
            form = layui.form,
            layer = layui.layer;
    });
    function mylogin() {
        var username = $("#username").val();
        var password = $("#password").val();
        console.log("username:" + username + "password:" + password);
        var index = layer.load(1);
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "user/login",
            data: {
                "username": username,
                "password": password
                //可加驗證碼引數等,后臺登陸處理LoginSuccessHandler中會傳入這些引數
            },
            success: function (data) {
                layer.close(index);
                console.log("data=https://www.cnblogs.com/qiantao/p/==>:" + JSON.stringify(data));
                if (data.code == 200) { //登錄成功
                    window.location.href = "index";
                } else {
                    layer.msg(data.msg, {
                        icon: 2,
                        time: 3000 //2秒關閉(如果不配置,默認是3秒)
                    });
                }
            },
            error: function () {
                layer.close(index);
                layer.msg("資料請求例外!", {
                    icon: 2,
                    time: 2000 //2秒關閉(如果不配置,默認是3秒)
                });
            }
        });
    }
</script>
</body>
</html>

4.3 演示圖片

登錄失敗

 登錄成功

 最后添加一個我寫的一個小demo,里面也整合了security框架,使用springboot + ssm后端框架 + maven依賴包管理 + thmeleaf模板引擎 + pear-admin-layui前端框架等,

 demo演示地址:http://www.qnto.top/springfashionsys/login

 demo只對資料分析頁面做了權限設定,只有admin才可訪問,

轉載需要加鏈接哦,整理不易,

總結:實踐是檢驗真理的唯一標準,親測可用,

 參考鏈接:

 https://blog.csdn.net/qq_40298902/article/details/106433192

 https://www.e-learn.cn/topic/3143567

 https://blog.csdn.net/qq_20108595/article/details/89647419

 http://www.spring4all.com/article/428

 https://blog.csdn.net/tanleijin/article/details/100698486

 https://blog.csdn.net/zhaoxichen_10/article/details/88713799

 https://blog.csdn.net/hanxiaotongtong/article/details/103095906

 https://www.jb51.net/article/140429.htm

 https://www.jianshu.com/p/29d10ad22531

 https://blog.csdn.net/weixin_39588542/article/details/110507502

 https://blog.csdn.net/sinat_33151213/article/details/89931819

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/273966.html

標籤:Java

上一篇:SpringCloud簡介

下一篇:使用EasyExcel匯入匯出excel

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more