主頁 > 後端開發 > 02-Spring Security 安全框架應用

02-Spring Security 安全框架應用

2021-07-21 13:28:30 後端開發

Spring Security 簡介

背景分析

企業中資料是最重要的資源,對于這些資料而言,有些可以直接匿名訪問,有些只能登錄以后才能訪問,還有一些你登錄成功以后,權限不夠也不能訪問.總之這些規則都是保護系統資源不被破壞的一種手段.幾乎每個系統中都需要這樣的措施對資料(資源)進行保護.我們通常會通過軟體技術對這樣業務進行具體的設計和實作.早期沒有統一的標準,每個系統都有自己獨立的設計實作,但是對于這個業務又是一個共性,后續市場上就基于共享做了具體的落地實作,例如Spring Security,Apache shiro誕生了.

認證授權分析

用戶在進行資源訪問時,要求系統要對用戶進行權限控制,其具體流程如圖所示:
在這里插入圖片描述

Spring Security 概述

Spring Security 是一個企業級安全框架,由spring官方推出,它對軟體系統中的認證,授權,加密等功能進行封裝,并在springboot技術推出以后,配置方面做了很大的簡化.市場上現在的分布式架構下的安全控制正在逐步的轉向Spring Security.

Spring Security 基本架構

Spring Security 在企業中實作認證和授權業務時,底層構建了大量的過濾器.
在這里插入圖片描述
其中:
綠色部分為認證過濾器,需要我們自己配置,也可以配置過個認證過濾器.也可以使用Spring Security提供的默認認證過濾器.黃色部分為授權過濾器.Spring Security就是通過這些過濾器然后呼叫相關物件一起完成認證和授權操作.

Spring Security 快速入門

創建工程

在這里插入圖片描述

添加專案依賴

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <groupId>com.cy</groupId>
    <artifactId>02-jt-spring-security</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>

創建組態檔

在resources目錄下創建application.yml檔案,并指定服務埠

server:
   port: 8080

創建專案啟動類

package com.cy.jt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringSecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(
                SpringSecurityApplication.class,
                args);
    }
}

運行啟動類訪問測驗

第一步:檢查控制輸出,是否自動生成了一個密碼,例如:

Using generated security password: 360123aa-df93-4cd9-bab4-5212af421d2c

第二步:打開瀏覽器輸入http://localhost:8080,然后呈現登錄頁面,例如:

在這里插入圖片描述
在登錄視窗中輸入用戶名user(系統默認),密碼(服務啟動時,控制臺默認輸出的
密碼),然后點擊Sign in進行登錄,登錄成功默認會出現,如下界面:

在這里插入圖片描述

定義登錄成功頁面

在專案的resources目錄下創建static目錄,并在此目錄創建一個index.html檔案,例如:

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

啟動服務,再次進行登錄訪問測驗,登錄成功以后系統默認會跳轉到index.html頁面,例如

在這里插入圖片描述

配置登錄密碼

第一步:撰寫一個方法(可以在啟動類中呼叫執行),對一個名文進行加密,例如:

 static void encodePwd(){
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        String password="123456";//明文
        String newPwd=encoder.encode("123456");
        System.out.println(newPwd);//$2a$10$fahHJIe3SJm3KcyiPPQ2d.a2qR029gB3qKHrKanQ87u.KbtZ6Phr.
    }

第二步:將用戶和密碼在在springboot工程的application.yml檔案中進行配置,例如:

spring:
  security:
    user:
      name: jack
      #password: 123456 #這種寫法,密碼太簡單了
      password: '{bcrypt}$2a$10$fahHJIe3SJm3KcyiPPQ2d.a2qR029gB3qKHrKanQ87u.KbtZ6Phr.'

其中,{bcrypt}指定了密碼加密時使用的演算法

第三步:啟動服務,重新進行登錄測驗.

SpringSecurity 認證邏輯實作

自定義登陸邏輯

SpringSecurity支持通過組態檔的方式定義用戶資訊(賬號密碼和角色等),但這種方式有明顯的缺點,那就是系統上線后,用戶資訊的變更比較麻煩,因此SpringSecurity還支持通過實作UserDetailsService介面的方式來提供用戶認證授權資訊,其應用程序如下:
第一步:定義security配置類,例如:

/**
 * 由@Configuration注解描述的類為spring中的配置類,配置類會在spring
 * 工程啟動時優先加載,在配置類中通常會對第三方資源進行初始配置.
 */
@Configuration
public class SecurityConfig {
    /**
     * 定義SpringSecurity密碼加密物件
     * @Bean 注解通常會在@Configuration注解描述的類中描述方法,
     * 用于告訴spring框架這個方法的回傳值會交給spring管理,并spring
     * 管理的這個物件起個默認的名字,這個名字與方法名相同,當然也可以通過
     * @Bean注解起名字
     */
    @Bean //物件名默認為方法名
    //@Bean("bcryptPasswordEncoder")//bean物件名字為bcryptPasswordEncoder
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

第二步:定義UserDetailService介面實作類,自定義登陸邏輯,代碼如下:
UserDetailService為SpringSecurity官方提供的登錄邏輯處理物件,我們自己可以實作此介面,然后在對應的方法中進行登錄邏輯的撰寫即可.

package com.cy.jt.security.service;
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    /**
     * 當我們執行登錄操作時,底層會通過過濾器等物件,呼叫這個方法.
     * @param username 這個引數為頁面輸出的用戶名
     * @return 一般是從資料庫基于用戶名查詢到的用戶資訊
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //1.基于用戶名從資料庫查詢用戶資訊
        //User user=userMapper.selectUserByUsername(username);
        if(!"jack".equals(username))//假設這是從資料庫查詢的資訊
            throw new UsernameNotFoundException("user not exists");
        //2.將用戶資訊封裝到UserDetails物件中并回傳
        //假設這個密碼是從資料庫查詢出來的
        String encodedPwd=passwordEncoder.encode("123456");
        //假設這個權限資訊也是從資料庫查詢到的
        //假如分配權限的方式是角色,撰寫字串時用"ROLE_"做前綴
        List<GrantedAuthority> grantedAuthorities =
                AuthorityUtils.commaSeparatedStringToAuthorityList(
                "ROLE_admin,ROLE_normal,sys:res:retrieve,sys:res:create");
        //這個user是SpringSecurity提供的UserDetails介面的實作,用于封裝用戶資訊
        //后續我們也可以基于需要自己構建UserDetails介面的實作
        User user=new User(username,encodedPwd,grantedAuthorities);
        return user;
    }
}

說明,這里的User物件會交給SpringSecurity框架,框架提取出密碼資訊,然后與用戶輸入的密碼進行匹配校驗.

第三步:啟動服務進行登陸,訪問測驗,

在這里插入圖片描述

在這里插入圖片描述

自定義登陸頁面

第一步:定義登陸頁面(直接在static目錄下創建即可),關鍵代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Please sign in</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <form class="form-signin" method="post" action="/login">
        <h2 class="form-signin-heading">Please sign in</h2>
        <p>
            <label for="username" class="sr-only">Username</label>
            <input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
        </p>
        <p>
            <label for="password" class="sr-only">Password</label>
            <input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
        </p>
        <input name="_csrf" type="hidden" value="cc1471a5-3246-43ff-bef7-31d714273899" />
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
</div>
</body>
</html>

注意:請求的url暫時為”/login”,請求方式必須為post方式,請求的引數暫時必須為username,password,這些規則默認在UsernamePasswordAuthenticationFilter中進行了定義,

第二步:修改安全配置類,讓其實作介面,并重寫相關config方法,進行登陸設計,代碼如下:

@Configuration
public class SecutiryConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        //關閉跨域攻擊,不關閉容易出錯
        http.csrf().disable();
        //自定義登陸表單
        http.formLogin()
                //設定登陸頁面
                .loginPage("/login.html")
                //設定登陸請求處理地址(對應form表單中的action),登陸時會訪問UserDetailService物件
                .loginProcessingUrl("/login")
                //設定請求用戶名引數為username(默認就是username,可以自己修改,需要與表單同步)
                .usernameParameter("username")
                //請求請求密碼引數為password(默認就是password,可以自己修改,需要與表單同步)
                .passwordParameter("password")
                //設定登陸成功跳轉頁面(默認為/index.html)
                .defaultSuccessUrl("/index.html")
                //登陸失敗訪問的頁面(默認為/login.html?error)
                .failureUrl("/login.html?error");
        //認證設計
        http.authorizeRequests()
                //設定要放行的咨詢
                .antMatchers("/login.html").permitAll()
                //設定需要認證的請求(除了上面的要放行,其它都要進行認證)
                .anyRequest().authenticated();
    }
}

登陸成功和失敗處理器

現在的很多系統都采用的是前后端分離設計,我們登陸成功以后可能會跳轉到前端系統的某個地址,或者回傳一個json資料,我們可以自己定義登錄成功的處理操作,例如:

定義登陸成功處理器:

方案1:可以直接執行重定向的處理器,例如

package com.cy.jt.auth.config.authentication;
public class RedirectAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//定義要跳轉的url
    private String redirectUrl;
    public RedirectAuthenticationSuccessHandler(String redirectUrl){
        this.redirectUrl=redirectUrl;
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
                            Authentication authentication)
            throws IOException, ServletException {
            httpServletResponse.sendRedirect(redirectUrl);
    }
}

方案2:可以直接回傳JSON資料的處理器,例如:

package com.cy.jt.security.config.handler;
/**處理登錄失敗
 * 0)Default-默認
 * 1)Authentication-認證
 * 2)Failure-失敗
 * 3)Handler-處理器
 * */
public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse,
            AuthenticationException e) throws IOException, ServletException {
        //1.設定回應資料的編碼
        httpServletResponse.setCharacterEncoding("utf-8");
        //2.告訴客戶端回應資料的型別,以及客戶端以怎樣的編碼進行顯示
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //3.獲取一個輸出流物件
        PrintWriter out=httpServletResponse.getWriter();
        //4.向客戶端輸出一個json格式字串
        //4.1構建一個map物件
        Map<String,Object> map=new HashMap<>();
        map.put("state","500");
        map.put("msg","username or password error");
        //4.2基于jackson中的ObjectMapper物件將一個物件轉換為json格式字串
        String jsonStr= new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();
    }
}

定義登陸失敗處理器:

方案1:登陸失敗重定向到頁面,例如

package com.cy.jt.auth.config.authentication;
public class RedirectAuthenticationFailureSuccessHandler implements AuthenticationFailureHandler {
    private String redirectUrl;
    public RedirectAuthenticationFailureSuccessHandler(String redirectUrl){
        this.redirectUrl=redirectUrl;
    }
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.sendRedirect(redirectUrl);
    }
}

方案2:定義登陸失敗處理器,例如:

package com.cy.jt.security.config.handler;

/**處理登錄失敗
 * 0)Default-默認
 * 1)Authentication-認證
 * 2)Failure-失敗
 * 3)Handler-處理器
 * */
public class DefaultAuthenticationFailureHandler
         implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse,
            AuthenticationException e) throws IOException, ServletException {
        //1.設定回應資料的編碼
        httpServletResponse.setCharacterEncoding("utf-8");
        //2.告訴客戶端回應資料的型別,以及客戶端以怎樣的編碼進行顯示
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //3.獲取一個輸出流物件
        PrintWriter out=httpServletResponse.getWriter();
        //4.向客戶端輸出一個json格式字串
        //4.1構建一個map物件
        Map<String,Object> map=new HashMap<>();
        map.put("state","500");
        map.put("msg","username or password error");
        //4.2基于jackson中的ObjectMapper物件將一個物件轉換為json格式字串
        String jsonStr= new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();
    }
}

修改配置類,設定登陸成功與失敗處理器,

@Configuration
public class SecutiryConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        //關閉跨域攻擊,不關閉容易出錯
        http.csrf().disable();
        //自定義登陸表單
        http.formLogin()
                //設定登陸頁面
                .loginPage("/login.html")
                //設定登陸請求處理地址(對應form表單中的action),登陸時會訪問UserDetailService物件
                .loginProcessingUrl("/login")
                //設定請求用戶名引數為username(默認就是username,可以自己修改,需要與表單同步)
                .usernameParameter("username")
                //請求請求密碼引數為password(默認就是password,可以自己修改,需要與表單同步)
                .passwordParameter("password")
                //設定登陸成功跳轉頁面(默認為/index.html)
                .successHandler(new RedirectAuthenticationSuccessHandler("你的url"))
                //登陸失敗訪問的頁面(默認為/login.html?error)
               .failureHandler(new RedirectAuthenticationFailureHandler("你的url"))
        //認證設計
                http.authorizeRequests()
                //設定要放行的咨詢
                .antMatchers("/login.html").permitAll()
                //設定需要認證的請求(除了上面的要放行,其它都要進行認證)
               .anyRequest().authenticated();
    }
}

第四步:啟動服務進行訪問測驗(分別用正確和錯誤的賬號進行測驗),

放行靜態資源

在SecurityManager配置類中的configure(HttpSecurity http)方法中我們可以通過對anMatchers方法定義要放行靜態資源,例如:

.authorizeRequests() //設定請求的授權
        .antMatchers(   //配置下列路徑的授權
                "/index.html",
                "/js/*",
                "/css/*",
                "/img/**",
                "/bower_components/**",
                "/login.html"
        ).permitAll()   //設定上述所有路徑不需要登錄就能訪問(放行)

其中:

  • “*”用于匹配0個或多個字符
  • “**”用于匹配0個或多個目錄及字符

登出設計及實作

在SecurityManager配置類中的configure(HttpSecurity http)方法中,添加登出配置,例如

  http.logout()       //開始設定登出資訊
        .logoutUrl("/logout")   //登出路徑
        .logoutSuccessUrl("/login.html?logout");//設定登出后顯示的頁面

SpringSecurity授權邏輯實作

修改授權配置類

在權限配置類上添加啟用全域方法訪問控制注解,例如:

package com.cy.auth.config;
//這個配置類是配置Spring-Security的,
//prePostEnabled= true表示啟動權限管理功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter {
    ……
}

定義資源Controller

定義一個ResourceController類,作為資源訪問物件,例如

package com.cy.jt.auth.controller;

@RestController
public class ResourceController {
    @PreAuthorize("hasAuthority('sys:res:create')")
    @RequestMapping("/doCreate")
    public String doCreate(){
        return "add resource";
    }
    @PreAuthorize("hasAuthority('sys:res:update')")
    @RequestMapping("doUpdate")
    public String doUpdate(){
        return "update resource";
    }
    @PreAuthorize("hasAuthority('sys:res:delete')")
    @RequestMapping("/doDelete")
    public String doDelete(){
        return "delete resource";
    }
    @PreAuthorize("hasAuthority('sys:res:retrieve')")
    @RequestMapping("/doRetrieve")
    public String doRetrieve(){
        return "retrieve resource";
    }
}

其中,@PreAuthorize注解描述方法時,用于告訴系統訪問此方法時需要進行權限檢測,需要具備指定權限才可以訪問,例如:

  • @PreAuthorize(“hasAuthority('sys:res:delete”) 需要具備sys:res:delete權限
  • @PreAuthorize(“hasRole(‘admin’)”) 需要具備admin角色

啟動服務訪問測驗

使用不同用戶進行登陸,然后執行資源訪問,假如沒有權限,則會看到回應狀態嗎403,如圖所示:
在這里插入圖片描述

Spring認證和授權例外處理

例外型別

對于SpringSecurity框架而言,在實作認證和授權業務時,可能出現如下兩大型別例外:
1)AuthenticationException (用戶還沒有認證就去訪問某個需要認證才可訪問的方法時,可能出現的例外,這個例外通常對應的狀態碼401)
2)AccessDeniedException (用戶認證以后,在訪問一些沒有權限的資源時,可能會出現的例外,這個例外通常對應的狀態嗎為403)

例外處理規范

SpringSecurity框架給了默認的例外處理方式,當默認的例外處理方式不滿足我們實際業務需求時,此時我們就要自己定義例外處理邏輯,撰寫邏輯時需要遵循如下規范:
1)AuthenticationEntryPoint:統一處理 AuthenticationException 例外
2)AccessDeniedHandler:統一處理 AccessDeniedException 例外.

自定義例外處理物件

處理沒有認證的訪問例外

package com.cy.jt.config;
public class DefaultAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e) throws IOException, ServletException {
        //設定回應資料的編碼
        response.setCharacterEncoding("utf-8");
        //告訴瀏覽器要回應的內容型別,以及編碼
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> map=new HashMap<>();
        map.put("state",401);
        map.put("message","請先登錄");
        PrintWriter out=response.getWriter();
        out.println(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }
}

處理沒有權限時拋出的例外

package com.cy.jt.config;

public class DefaultAccessDeniedExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
        //設定回應資料的編碼
        response.setCharacterEncoding("utf-8");
        //告訴瀏覽器要回應的內容型別,以及編碼
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> map=new HashMap<>();
        map.put("state",403);
        map.put("message","沒有此資源的訪問權限");
        PrintWriter out=response.getWriter();
        out.println(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }
}

配置例外處理物件

在配置類SecurityConfig中添加自定義例外處理物件,代碼如下

 http.exceptionHandling()
            .authenticationEntryPoint(new DefaultAuthenticationEntryPoint())
            .accessDeniedHandler(new DefaultAccessDeniedExceptionHandler());

配置完成后,重啟服務進行訪問測驗分析.

總結(Summary)

重難點分析

  • SpringSecurity 產生背景?
  • SpringSecurity 快速入門?(依賴,配置,登錄認證,密碼的加密-啟動生成,組態檔)
  • SpringSecurity 認證邏輯分析及實踐?(認證方式-用戶名和密碼,登錄頁面,SecurityConfig.UserServiceDetail,成功,失敗,放行)

FAQ 分析

  • 如何理解認證?(判定用戶身份的合法性)
  • 如何校驗用戶身份的合法性?(用戶密碼,指紋,刷臉,刷身份證,…)
  • 如何進行身份認證?(自己寫認證邏輯,借助框架去寫認證邏輯-尊重框架規則)
  • 市場上的認證和授權框架有哪些?(SpringSecurity,Shiro)
  • 為什么會選擇SpringSecurity?(功能強大,SpringBoot誕生后在配置方面做了大量的簡化)
  • SpringSecurity中的加密方式你用的什么?(Bcrypt,底層基于隨機鹽方式對密碼進行hash不可逆加密,更加安全,缺陷是慢)
  • SpringSecurity中你用過哪些API?(BcryptPasswordEncoder,UserDetailService,UserDetail,User,
    AuthenticationSuccessHandler,AuthenticationFailureHandler,…)

Bug 分析

  • 依賴下載不完整

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

標籤:java

上一篇:Arthas使用教程 阿里巴巴開源專案、史上最強java線上診斷工具

下一篇:三分鐘極速體驗:Java版人臉檢測

標籤雲
其他(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