”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Spring Security 保护微服务:实施 JWT

使用 Spring Security 保护微服务:实施 JWT

发布于2024-11-07
浏览:118

JSON WEB TOKEN (JWT)

JWT (JSON Web Token) is a method for securely transmitting information between two parties (such as a client and a server) as a JSON object. It's designed to be compact and URL-safe, making it easy to pass around in URLs, headers.

  1. Header
  2. Payload
  3. Signature

Header
The header typically consist two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.

{
"alg":"HS256",
"typ":"JWT"
}

Payload
This is where the actual data is stored. It can include information like the user ID, roles, expiration time, and other claims (data about the user or session).

{
"email":"[email protected]",
"name":"Ayush"
}

Signature
Ensures the integrity of the token. This is a security feature that ensures the token hasn’t been altered. It’s created by combining the encoded header and payload with a secret key using the specified algorithm. The signature helps the server verify that the token is legitimate and hasn’t been tampered with.

The benefits of JWT

No Need to Repeatedly Send Credentials: With JWT, you don't have to send your username and password with every request. Instead, you log in once, and the server gives you a token. You then send this token with each request to prove your identity, making the process more secure and efficient.

Built-in Expiration: Each JWT comes with an expiration time, meaning it’s only valid for a specific period. This reduces the risk of long-term misuse if a token is somehow intercepted. After it expires, the user needs to log in again to get a new token, adding an extra layer of security.

JWT with Spring Boot securely manages user authentication by issuing tokens after login. These tokens are sent with each request, ensuring secure, stateless communication without repeatedly sending credentials.

Stateless communication means the server doesn't remember past requests. Each request carries everything needed (like a JWT), so the server doesn't store session info.

Implementing JWT in a Java Spring Boot application involves several steps. Here's a simplified outline to get you started:

1. Add Dependencies

Include the necessary dependencies in your pom.xml file

                
            io.jsonwebtoken
            jjwt-api
            0.12.5
        
        
            io.jsonwebtoken
            jjwt-impl
            0.12.5
            runtime
        
        
            io.jsonwebtoken
            jjwt-jackson
            0.12.5
            runtime
        

All the dependencies that we need to create the spring-boot application with JWT



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        3.3.3
         
    
    com.tier3Hub
    user-auth-service
    0.0.1-SNAPSHOT
    user-auth-service
    The user-auth-service is a microservice responsible for handling user authentication and authorization within a distributed system. It is designed to manage user login, registration, and secure access to various services using robust security practices. This service implements authentication mechanisms like JSON Web Tokens (JWT) and integrates with OAuth 2.0 for third-party authentication. Built with Spring Boot, it ensures scalability, reliability, and easy integration with other microservices in the system.
    
    
        
    
    
        
    
    
        
        
        
        
    
    
        21
    
    
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            io.jsonwebtoken
            jjwt-api
            0.12.5
        
        
            io.jsonwebtoken
            jjwt-impl
            0.12.5
            runtime
        
        
            io.jsonwebtoken
            jjwt-jackson
            0.12.5
            runtime
        
        
            com.mysql
            mysql-connector-j
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.security
            spring-security-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-validation
        
        
            org.springdoc
            springdoc-openapi-starter-webmvc-ui
            2.5.0
        
        
            org.modelmapper
            modelmapper
            3.1.1
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



we are using different types of dependencies like

  • Spring Boot Starter Actuator: 3.3.3 - Adds production-ready features like monitoring and health checks.
  • Spring Boot Starter Data JPA: 3.3.3 - Simplifies database interactions with JPA support.
  • Spring Boot Starter Security: 3.3.3 - Provides security features like authentication and authorization.
  • Spring Boot Starter Web: 3.3.3 - Supports building web applications, including RESTful services.
  • JJWT API: 0.12.5 - Handles JWT creation and parsing for secure token management.
  • JJWT Impl: 0.12.5 - Implements core JWT functionalities.
  • JJWT Jackson: 0.12.5 - Enables JWT JSON parsing using Jackson.
  • MySQL Connector: Runtime - Connects your application to a MySQL database.
  • Lombok: Not specified - Reduces boilerplate code with annotations.
  • Spring Boot Starter Test: 3.3.3 - Provides testing support for Spring Boot applications.
  • Spring Security Test: 3.3.3 - Helps with testing security configurations.
  • Spring Boot Starter Validation: 3.3.3 - Adds validation support for request and response objects.
  • SpringDoc OpenAPI Starter WebMVC UI: 2.5.0 - Integrates Swagger UI for API documentation.
  • ModelMapper: 3.1.1 - Simplifies object mapping between different layers.

*2. Project structure *

Securing Microservices with Spring Security: Implementing JWT

3. Add the configuration in application.properties file

spring.application.name=user-auth-service

server.port=8000

spring.datasource.url=jdbc:mysql://localhost:3306/auth_services
spring.datasource.username=root
spring.datasource.password=ayush@123

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

#debug logs
logging.level.org.springframework.security=debug

spring.main.allow-circular-references=true 

4. Create the USER entity

package com.tier3Hub.user_auth_service.entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.List;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Table
@Entity(name = "User")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String email;
    private String phoneNumber;
    private List roles;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
}

** 5. create the service and repository class and interface**

Repository.java

package com.tier3Hub.user_auth_service.Repository;

import com.tier3Hub.user_auth_service.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface AuthRepository extends JpaRepository {

    User findByUsername(String username);
}

service.java

package com.tier3Hub.user_auth_service.service;

import com.tier3Hub.user_auth_service.dto.LoginResponse;
import com.tier3Hub.user_auth_service.dto.RegisterDTO;
import com.tier3Hub.user_auth_service.dto.RegisterResponse;

public interface AuthService {
    RegisterResponse register(RegisterDTO registerDTO);
}

6. create the DTO's for login and signin request and response

CreateloginDTO.java

package com.tier3Hub.user_auth_service.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class LoginDTO {
    @NotBlank(message = "Username is required")
    @Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters")
    private String username;

    @NotBlank(message = "Password is required")
    private String password;
}

loginResponse.java

package com.tier3Hub.user_auth_service.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class LoginResponse {
    private String accessToken;
    private String tokenType = "Bearer";
}

RegisterDTO.java

package com.tier3Hub.user_auth_service.dto;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class RegisterDTO {
    @NotBlank(message = "Username is required")
    @Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters")
    private String username;

    @NotBlank(message = "Password is required")
    @Size(min = 8, message = "Password must be at least 8 characters")
    private String password;

    @NotBlank(message = "Email is required")
    @Email(message = "Email should be valid")
    private String email;
}

RegisterResponse.java

package com.tier3Hub.user_auth_service.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class RegisterResponse {
    private Long id;
    private String username;
    private String email;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
}

*7. for sending custom response from the API we use the ResponseHandler.java *

package com.tier3Hub.user_auth_service.utils;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;
import java.util.Map;

public class ResponseHandler {
    public static ResponseEntity generateResponse(String message, HttpStatus status, Object responseObj) {
        Map map = new HashMap();
        map.put("message", message);
        map.put("status", status.value());
        map.put("data", responseObj);
        return new ResponseEntity(map, status);
    }

}

8. for storing some constants we create the class inside the utils package that is ApplicationConstants.java

package com.tier3Hub.user_auth_service.utils;

public class AppConstants {
    public static final String[] PUBLIC_URLS = { "/v3/api-docs/**", "/swagger-ui/**", "/api/auth/register/**", "/api/auth/login/**","/api/auth/registerAdmin/**" };
}

9. for converting the object one to another we use the dependency that is model mapper for configuration that we create the class inside the config package that is ApplicationConfigs.java

package com.tier3Hub.user_auth_service.config;

import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfigs {
    @Bean
    public ModelMapper modelMapper()
    {
        return new ModelMapper();
    }
}

**
This is the basic setup that we do for every spring-boot application we create now securing the rest endpoint with JWT we started.
**

now inside the security package we create the class called JWTFilter.java

The JWTFilter is a custom Spring Security filter that intercepts HTTP requests to validate JWTs. It checks for the "Authorization" header, extracts the token, and retrieves the username. If the token is valid, it creates an authentication token with user details and sets it in the security context, allowing the application to recognize the authenticated user for further processing.

package com.tier3Hub.user_auth_service.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Service
public class JWTFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authorizationHeader = request.getHeader("Authorization");
        String username = null;
        String jwt = null;
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }
        if (username != null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (jwtUtil.validateToken(jwt)) {
                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        chain.doFilter(request, response);
    }
}

create the class JWTUtil.java

The JWTUtil class manages JWT operations, including extracting usernames and expiration dates from tokens. It generates new tokens using a secret key and validates existing tokens by checking their expiration. The class uses HMAC for signing and includes methods to parse claims and determine if tokens are expired, ensuring secure authentication and authorization in the application.

package com.tier3Hub.user_auth_service.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class JWTUtil {

    private String SECRET_KEY = "TaK HaV^uvCHEFsEVfypW#7g9^k*Z8$V";

    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
    }

    public String extractUsername(String token) {
        Claims claims = extractAllClaims(token);
        return claims.getSubject();
    }

    public Date extractExpiration(String token) {
        return extractAllClaims(token).getExpiration();
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser()
                .verifyWith(getSigningKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    public String generateToken(String username) {
        Map claims = new HashMap();
        return createToken(claims, username);
    }

    private String createToken(Map claims, String subject) {
        return Jwts.builder()
                .claims(claims)
                .subject(subject)
                .header().empty().add("typ","JWT")
                .and()
                .issuedAt(new Date(System.currentTimeMillis()))
                .expiration(new Date(System.currentTimeMillis()   1000 * 60 * 50)) // 5 minutes expiration time
                .signWith(getSigningKey())
                .compact();
    }

    public Boolean validateToken(String token) {
        return !isTokenExpired(token);
    }
}

*configure the Spring security and add some modifictaion we create the class SecurityConfig.java *

The SecurityConfig class sets up security for the application using Spring Security. It defines access rules, allowing public endpoints while restricting others based on user roles. The class incorporates a JWT filter to validate tokens and uses BCrypt for password encoding. It also configures an authentication manager with a custom user details service for secure user authentication.

package com.tier3Hub.user_auth_service.config;

import com.tier3Hub.user_auth_service.security.JWTFilter;
import com.tier3Hub.user_auth_service.service.UserInfoConfigManager;
import com.tier3Hub.user_auth_service.utils.AppConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private JWTFilter jwtFilter;

    @Autowired
    private UserInfoConfigManager userInfoConfigManager;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests(request -> request
                        .requestMatchers(AppConstants.PUBLIC_URLS).permitAll()
                        .requestMatchers("/api/test/public/hello/**").hasAnyRole("USER","ADMIN")
                        .requestMatchers("/api/test/private/**").hasRole("ADMIN")
                        .anyRequest()
                        .authenticated())
                .csrf(AbstractHttpConfigurer::disable)
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userInfoConfigManager).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration auth) throws Exception {
        return auth.getAuthenticationManager();
    }
}

The securityFilterChain method configures access rules for different API endpoints in the Spring application. It permits public URLs and applies role-based access control for user and admin roles. Role-based authentication restricts resource access based on user roles (e.g., USER, ADMIN). In Spring Boot, you define roles and configure security settings in the SecurityConfig class to specify access permissions. During user registration, assign roles, and use annotations like @PreAuthorize to enforce role checks in controllers. This approach enhances security, allows easy permission management, and simplifies user access rights as the application scales. Implementing role-based auth provides flexibility and maintainability for your user management system. CSRF protection is disabled, and a custom JWT filter is added to authenticate requests based on JSON Web Tokens, ensuring secure and controlled access to resources.

configureGlobal method handle configures global authentication settings in a Spring application. It uses a custom user details service for loading user data and a BCrypt password encoder for secure password hashing. Additionally, it provides an AuthenticationManager bean for handling authentication processes, ensuring a secure and efficient user authentication system that leverages strong password management practices.

create the endpoints for register and login

package com.tier3Hub.user_auth_service.Controller;


import com.tier3Hub.user_auth_service.dto.LoginDTO;
import com.tier3Hub.user_auth_service.dto.LoginResponse;
import com.tier3Hub.user_auth_service.dto.RegisterDTO;
import com.tier3Hub.user_auth_service.security.JWTUtil;
import com.tier3Hub.user_auth_service.service.AuthService;
import com.tier3Hub.user_auth_service.service.UserInfoConfigManager;
import com.tier3Hub.user_auth_service.utils.ResponseHandler;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    AuthService authService;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private UserInfoConfigManager userInfoConfigManager;

    @PostMapping("/register")
    public ResponseEntity register(@Valid @RequestBody RegisterDTO registerDTO) {
        return ResponseHandler.generateResponse("User registered successfully", HttpStatus.OK, authService.register(registerDTO));
    }

    @PostMapping("/login")
    public ResponseEntity login(@Valid @RequestBody LoginDTO loginDTO) {
        try {
            Authentication authenticate = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword()));
            UserDetails userDetails = userInfoConfigManager.loadUserByUsername(loginDTO.getUsername());
            String jwt = jwtUtil.generateToken(userDetails.getUsername());
            LoginResponse loginResponse = LoginResponse
                    .builder()
                    .accessToken(jwt)
                    .build();
            return ResponseHandler.generateResponse("User logged in successfully", HttpStatus.OK, loginResponse);
        }
        catch (Exception e)
        {
            return new ResponseEntity("Incorrect username or password", HttpStatus.BAD_REQUEST);
        }
    }
}

This login method in the AuthController handles user login requests. It takes a LoginDTO containing the username and password, validates them, and attempts authentication using the AuthenticationManager. Upon successful authentication, it retrieves user details and generates a JWT token using the JWTUtil class. The token is then included in a LoginResponse object and returned with a success message. If authentication fails, it catches the exception and returns a "Incorrect username or password" response with a 400 status code.

generateToken(String username): This method creates an empty claims map and calls the createToken method with the username as the subject. It serves as the entry point for token generation.

c*reateToken(Map claims, String subject):* This method builds the JWT using the Jwts.builder(). It sets the claims, subject, and token metadata, such as issue date and expiration time (set to 5 minutes). The token is then signed with a secret key and compacted into a string format for transmission.

Testing

now we run the application

Securing Microservices with Spring Security: Implementing JWT

and hit the URL here our application is runing on 8000 port

http://localhost:8000/swagger-ui/index.html

Using Swagger in your project enhances API documentation and testing. It provides a user-friendly interface for developers to explore your APIs, understand request/response structures, and test endpoints directly from the documentation. By integrating Swagger, you enable automatic generation of API docs based on your code annotations, making it easier for both front-end and back-end developers to collaborate efficiently.

Securing Microservices with Spring Security: Implementing JWT

first we register the user

Securing Microservices with Spring Security: Implementing JWT

we get the response like this

Securing Microservices with Spring Security: Implementing JWT

after that we login the user

Securing Microservices with Spring Security: Implementing JWT

we get the response like this

Securing Microservices with Spring Security: Implementing JWT

Conclusion

The project implements role-based authentication using JWT (JSON Web Tokens) in a Spring Boot application. It features a secure authentication mechanism where users can register and log in, receiving a JWT that grants access based on their assigned roles (like USER or ADMIN). The SecurityConfig class configures access permissions, ensuring that public endpoints are accessible to everyone while restricting sensitive operations to authorized users only. The JWTUtil class handles token creation, validation, and user extraction. Overall, this setup enhances security, enabling seamless and robust access control across the application.

The project employs a comprehensive security framework that leverages Spring Security for user authentication and authorization. The AuthController facilitates user registration and login, generating a JWT upon successful authentication. The application uses a JWTFilter to intercept requests and validate tokens, ensuring that only authenticated users can access protected resources. By integrating role-based access control, the project provides a flexible and secure user management system. This design not only improves security but also enhances user experience by minimizing the need for repeated logins. Overall, it lays a solid foundation for building scalable and secure microservices.

You can explore the complete source code for the User Authentication Service on my GitHub repository. This project showcases various features such as user registration, login, and secure access using JWT for authentication. Feel free to check it out, contribute, or use it as a reference for your own projects!

GitHub Repository: https://github.com/ishrivasayush/user-auth-service

For those interested in diving deeper into JSON Web Tokens (JWT), I recommend visiting jwt.io. This resource provides comprehensive information about JWT, including how it works, its structure, and practical examples. It's an excellent starting point for understanding token-based authentication and authorization, which are essential for modern web applications. Whether you're a beginner or looking to refresh your knowledge, jwt.io offers valuable insights into securely managing user sessions.

版本声明 本文转载于:https://dev.to/ayushstwt/securing-microservices-with-spring-security-implementing-jwt-38m6?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何处理PHP文件系统功能中的UTF-8文件名?
    如何处理PHP文件系统功能中的UTF-8文件名?
    在PHP的Filesystem functions中处理UTF-8 FileNames 在使用PHP的MKDIR函数中含有UTF-8字符的文件很多flusf-8字符时,您可能会在Windows Explorer中遇到comploreer grounder grounder grounder gro...
    编程 发布于2025-04-16
  • JavaScript事件处理中如何保留实例作用域:通过变量别名捕获“this”
    JavaScript事件处理中如何保留实例作用域:通过变量别名捕获“this”
    在事件处理程序中的acpoping:javascript中的“ this” conundrum 在JAVAScript中,实例方法用作事件处理程序可以导致求程问题。当触发事件处理程序时,“此”的范围从预期的实例转移到调用回调的元素。这需要使用变量来“捕获”并维护实例的范围。声明“自我”变量以使“别...
    编程 发布于2025-04-16
  • .NET XML序列化中如何控制命名空间前缀?
    .NET XML序列化中如何控制命名空间前缀?
    .NET XML序列化:命名空间前缀控制 .NET 提供两种主要的 XML 序列化机制:DataContractSerializer 和 XmlSerializer。然而,它们默认生成的命名空间前缀由内部机制管理,这限制了自定义前缀的需求。 利用 XmlSerializerNamespaces 若...
    编程 发布于2025-04-16
  • 在Matplotlib中如何创建可重用的AxesSubplot对象?
    在Matplotlib中如何创建可重用的AxesSubplot对象?
    在matplotlib 从图实例中解除AxessSubplot创建的情况,人们可以将传递轴实例的功能考虑到函数。例如: def plot(x,y,ax = none): 如果斧头没有: ax = plt.gca()#获取当前轴实例(默认) ax.plot(x,y,&...
    编程 发布于2025-04-16
  • 如何避免Go语言切片时的内存泄漏?
    如何避免Go语言切片时的内存泄漏?
    ,a [j:] ...虽然通常有效,但如果使用指针,可能会导致内存泄漏。这是因为原始的备份阵列保持完整,这意味着新切片外部指针引用的任何对象仍然可能占据内存。 copy(a [i:] 对于k,n:= len(a)-j i,len(a); k
    编程 发布于2025-04-16
  • 如何使用Python理解有效地创建字典?
    如何使用Python理解有效地创建字典?
    在python中,词典综合提供了一种生成新词典的简洁方法。尽管它们与列表综合相似,但存在一些显着差异。与问题所暗示的不同,您无法为钥匙创建字典理解。您必须明确指定键和值。 For example:d = {n: n**2 for n in range(5)}This creates a dicti...
    编程 发布于2025-04-16
  • Java静态初始化块使用时机及原因
    Java静态初始化块使用时机及原因
    在Java中理解静态初始化块,静态初始化块提供了一种特殊的机制,可以在类中初始化静态字段。静态字段仅初始化一次,并在类的所有实例中共享相同的值。虽然可以在声明中的静态字段中分配值,但在某些情况下,这种方法是不切实际的。为什么使用静态初始化障碍?在其声明点上无法确定静态字段的值。例如,想象一下您的字...
    编程 发布于2025-04-16
  • 为什么不使用CSS`content'属性显示图像?
    为什么不使用CSS`content'属性显示图像?
    在Firefox extemers属性为某些图像很大,&& && && &&华倍华倍[华氏华倍华氏度]很少见,却是某些浏览属性很少,尤其是特定于Firefox的某些浏览器未能在使用内容属性引用时未能显示图像的情况。这可以在提供的CSS类中看到:。googlepic { 内容:url(&#...
    编程 发布于2025-04-16
  • 左连接为何在右表WHERE子句过滤时像内连接?
    左连接为何在右表WHERE子句过滤时像内连接?
    左JOIN CONUNDRUM:WITCHING小时在数据库Wizard的领域中变成内在的加入很有趣,当将c.foobar条件放置在上面的Where子句中时,据说左联接似乎会转换为内部连接。仅当满足A.Foo和C.Foobar标准时,才会返回结果。为什么要变形?关键在于其中的子句。当左联接的右侧值...
    编程 发布于2025-04-16
  • 在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在C中的显式删除 在C中的动态内存分配时,开发人员通常会想知道是否有必要在heap-procal extrable exit exit上进行手动调用“ delete”操作员,但开发人员通常会想知道是否需要手动调用“ delete”操作员。本文深入研究了这个主题。 在C主函数中,使用了动态分配变量(H...
    编程 发布于2025-04-16
  • 无需刷新页面,如何重新加载CSS?
    无需刷新页面,如何重新加载CSS?
    不用页面refresh 重新加载CSS 一个常见的UX Enhancement是启用Live CSS编辑,使用户可以立即看到更改而无需重新加载页面。了解处理样式更新的最佳方法可以显着简化此过程。解决方案: 的挑战很大,请考虑动态性动态性动态多多,以动态操纵样式图。以下代码片段演示了一种有效的方法...
    编程 发布于2025-04-16
  • 实现IValidatableObject条件验证:属性级别与情景忽略
    实现IValidatableObject条件验证:属性级别与情景忽略
    实现 IValidatableObject 中的条件验证:属性级特性和基于场景的忽略 问题: 我知道 IValidatableObject 可用于在比较属性时进行对象验证。但是,我希望使用属性来验证单个属性,并在某些场景中忽略特定的属性失败。我的以下实现是否不正确? public class Va...
    编程 发布于2025-04-16
  • 使用Pandas read_csv解析带不规则分隔符的数据方法
    使用Pandas read_csv解析带不规则分隔符的数据方法
    在pandas read_csv 以解决这一挑战,pandas为定义分离器提供了多功能选项。一种方法涉及采用正则表达式(REGEX)。通过在READ_CSV中使用定界符参数,您可以指定捕获所需分离器的正则表达式模式。这使您可以考虑空间和选项卡的组合,确保准确解析。另外,您可以利用与python ...
    编程 发布于2025-04-16
  • Python中何时用"try"而非"if"检测变量值?
    Python中何时用"try"而非"if"检测变量值?
    使用“ try“ vs.” if”来测试python 在python中的变量值,在某些情况下,您可能需要在处理之前检查变量是否具有值。在使用“如果”或“ try”构建体之间决定。“ if” constructs result = function() 如果结果: 对于结果: ...
    编程 发布于2025-04-16
  • input: Why Does "Warning: mysqli_query() expects parameter 1 to be mysqli, resource given" Error Occur and How to Fix It?

output: 解决“Warning: mysqli_query() 参数应为 mysqli 而非 resource”错误的解析与修复方法
    input: Why Does "Warning: mysqli_query() expects parameter 1 to be mysqli, resource given" Error Occur and How to Fix It? output: 解决“Warning: mysqli_query() 参数应为 mysqli 而非 resource”错误的解析与修复方法
    mysqli_query()期望参数1是mysqli,resource给定的,尝试使用mysql Query进行执行MySQLI_QUERY_QUERY formation,be be yessqli:sqli:sqli:sqli:sqli:sqli:sqli: mysqli,给定的资源“可能发...
    编程 发布于2025-04-16

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3