JavaWeb learning route (8) - login

1. Basic login function

(1) Requirement: Determine whether the user can log in according to the account number and password

(2) Implementation steps

  • The Controller receives the data in JSON format, uses @RequestBody+ entity class to receive it, and calls the Service for specific processing.
  • Service creates a login interface, and the implementation class calls Mapper to query whether a specific user exists according to the conditions. If it exists, it returns the specific user, otherwise it returns null.
  • Mapper creates a conditional query interface and uses conditional query SQL to query users.

(3) Code implementation
UserController.java

@RestController //@Controller+@ResponseBody
public class LoginCtroller{
    
    
	@PostMapping("/login")
    public int login(@RequestBody User user){
    
    
        User u = userService.login(user);
        return u !=null?200:-1;
    }
}

UserService.java

public interface UserService {
    
    
    User login(User user);
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService{
    
    

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) {
    
    
        return userMapper.getUserByUsernameAndPassword(user);
    }
}

UserMapper.java

@Mapper
public interface UserMapper {
    
    
    @Select("select * from user where username = #{username} and password = #{password}")
    User getUserByUsernameAndPassword(User user);
}

(4) Defects of existing registrations

  • There is no way to restrict users from directly accessing content pages.

2. Login verification

(1) Concept: User login authorization is required for every request.

(2) Login verification related technologies
insert image description here

1. Login token: Session technology is generally used. After the user logs in successfully, the token will be obtained in each request.

2. Unified interception: two ways

  • Filter Filter
  • Interceptor Interceptor

(3) Conversational technology

1. Concept

  • Session: The user opens the browser, accesses the resources of the we server, and the session is established until one party disconnects, and the session ends. Multiple requests and responses can be made in one session .
  • Session Tracking: A method of maintaining browser state. The server needs to identify whether multiple requests come from the same browser in order to share data between multiple requests in the same session .
  • Session tracking scheme:
    • Client Session Tracking Technology - Cookie
    • Server session tracking technology - Session
    • token technology

2. Client session tracking cookie

(1) Cookie usage process:

  • After the user logs in successfully, the server creates a cookie and automatically sends it to the browser .
  • The browser receives the cookie and automatically stores it locally in the browser .
  • The user uses the browser to send a request to the server, and the browser automatically sends the Cookie request header (Set-Cookie: name=value) to the same interception layer of the server for verification , and the request is processed after the verification is passed.

Simulate the operation of cookies on the server side

@Slf4j
@RestController
public class SessionController {
    
    
    @GetMapping("/c1")
    public int cookie1(HttpServletResponse response){
    
    
        response.addCookie(new Cookie("login_username","zengoo"));
        return 200;
    }

    @GetMapping("/c2")
    public int cookie(HttpServletRequest request){
    
    
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
    
    
            if (cookie.getName().equals("login_username")) System.out.println("用户登录的账号为 " + cookie.getValue());
        }
        return 200;
    }
}

Execute the C1 method request to the server rendering
insert image description here

Execute the C2 method to obtain the rendering of the specified cookie content

insert image description here

(2) Advantages and disadvantages of cookies

  • advantage
    • Technologies Supported by the HTTP Protocol
  • shortcoming
    • Cookies cannot be used on mobile
    • Not secure, user can disable cookies
    • Cookies do not support cross-domain

3. Server session tracking technology Session

(1) Session usage process

  • After the user logs in successfully, the session is common, and the SessionID is recorded through the cookie and sent to the browser
  • The browser receives the cookie and stores it locally
  • When a request to the server occurs, the SessionID is sent to the server, and the server searches for the corresponding Session to connect.

(2) Simulation Session

@Slf4j
@RestController
public class SessionController {
    
    
    @GetMapping("/s1")
    public int session1(HttpSession session){
    
    
        log.info("HttpSession-s1:{}",session.hashCode());
        session.setAttribute("login_account","tom1101");
        return 200;
    }

    @GetMapping("/s2")
    public int session2(HttpSession session){
    
    
        log.info("HttpSession-s2:{}",session.hashCode());
        Object user = session.getAttribute("login_account");
        log.info("user:{}",user);
        return 200;
    }
}

Set session renderings

insert image description here
The server obtains the Session effect diagram

insert image description here
(3) Advantages and disadvantages of Session

  • advantage
    • Stored on the server side, high security
  • shortcoming
    • Session cannot be used in a server cluster environment (the reason is that the server generating the Session may not be the same server as the server assigned by the service)
    • Disadvantages of Cookie (the bottom layer of Session is Cookie)

4. Token Technology

(1) The process of using token technology

  • After the user logs in successfully, get a token (such as token, accessKey...) from the server, and the server returns it to the browser
  • The browser receives the token and stores it locally (either using Cookie or Session)
  • When a request to the server occurs, the browser sends the token to the server, and the server processes the request after verification

(2) Advantages and disadvantages of token technology

  • advantage
    • Support PC, mobile
    • Solve the authentication problem in the cluster environment
    • Reduce server storage pressure
  • shortcoming
    • Requires manual implementation (generate, store, etc.)

(3) JWT token technology

  • Introduction
    • Full name: JSON Web Token (official website: https://jwt.io/ )
    • Role: Defines a concise (JWT is a string), self-contained (custom data can be inserted) format, which is used to securely transmit information in JSON data format between the two parties in communication. This information is reliable due to the presence of digital signatures.
    • structure:
      • The first part: Header (header) , record token type, signature algorithm, etc. For example {"alg": "HS256", "type": "JWT"}
      • The second part: Payload (payload) , customized content, default information, etc. For example {"id":"1","username":"Tom"}
      • The third part: Signature (signature) , to prevent Token from being tampered with and to ensure security. Add the header, payload, and the specified key, and calculate it through the specified signature algorithm.
    • JWT use
      • Introduce JWT dependency.io.jsonwebtoken.jjwt - 0.9.1
    • Precautions for using JWT
      • The corresponding signature key must be used for JWT verification
      • Reasons for JWT token invalidation:
        • Tokens have been tampered with
        • token expires

Produce JWTs

public class DataTest {
    
    
    @Test
    public void getJWT(){
    
    
        //载荷内容
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",1);
        claims.put("username","tom");

        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,"zengoo")//签名算法Base64+签名密钥"zengoo"
                .setClaims(claims) //载荷
                .setExpiration(new Date(System.currentTimeMillis()+ (12*3600*1000))) //有效期
                .compact();
                
        System.out.println(jwt);
    }
}

/*打印结果*/
eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNjg4MDYzMzUwLCJ1c2VybmFtZSI6InRvbSJ9.occWRYeyio23As2Xd0RilmZtASE3wF0bYc_6F3OFE-M

parsing token

    @Test
    public void parseJWT(){
    
    
        Claims claim = Jwts.parser()
                .setSigningKey("zengoo") //签名密钥
                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNjg4MDYzMzUwLCJ1c2VybmFtZSI6InRvbSJ9.occWRYeyio23As2Xd0RilmZtASE3wF0bYc_6F3OFE-M") //JWT内容
                .getBody();
        System.out.println(claim);
    }
/*打印输入*/
{
    
    id=1, exp=1688063350, username=tom}

(4) Filter filter

1 Introduction

  • Concept: Filter filter is Servlet、Filter、Listenerone of the three major components of JavaWeb ( ).
  • Function: The filter can intercept resource requests and complete common operations, such as: login verification, unified encoding processing, sensitive word character processing, etc.

2. use

(1) Define Filter: define a class, implement the Filter interface, and rewrite the method.

@WebFilter(urlPatterns = "/*") //拦截所有请求
public class LoginFilter implements Filter {
    
    
    //初始化方法,web服务器启动,创建Filter时调用,仅调用一次
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        Filter.super.init(filterConfig);
    }
    //对请求方法进行拦截处理,可多次调用
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        //处理代码
        System.out.println("拦截方法执行");
        //放开请求
        filterChain.doFilter(servletRequest,servletResponse);
    }

    //销毁方法,服务器关闭时调用,仅调用一次
    @Override
    public void destroy() {
    
    
        Filter.super.destroy();
    }
}

(2) Configure Filter:@WebFilter Add annotations to the Filter class , configure the path to intercept resources, add @ServletComponentScanannotations to the startup class, and enable Servlet component support.

@ServletComponentScan //开启Servlet组件扫描
@SpringBootApplication
public class SpringbootMybatisApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}

3. The details of the filter

(1) Execution process

  • The web server starts, the filter starts the initialization method init
  • The browser sends any request to the web server, and the filter intercepts the request
  • The filter starts the doFilter method to judge the request or process the request content, and after confirming that it is correct, submit it to the doFilter() method of the FilterChain class to release the request to access resources.
  • If there is still logic that needs to be processed, it can be written and executed after releasing the request.

(2) interception path

  • Common Intercept Paths
path mode example illustrate
specific path /login Intercept when accessing /login
directory interception /userAPI/* Intercept when accessing resources under /userAPI
block all /* Access to all resources will be blocked

(3) Filter chain

  • Concept: In a web application, multiple filters can be configured, and the filtering channels formed by multiple filters form a filtering chain.
  • Function: Through the filter chain in the order of class names, the server can perform multiple additional processing through multiple filters.

(5) Interceptor interceptor

1 Introduction

  • Concept: A mechanism for dynamically intercepting method calls provided in the Spring framework, similar to a filter, so the scope of the interceptor is the entire Spring framework, and other resources are not intercepted.
  • Function: Intercept the request, execute the pre-set code according to the business requirements before and after the specified method call.

2. Use interceptors
(1) Define interceptors: implement the HandlerInterceptor interface and rewrite all methods

@Component
public class LoginInterceptor implements HandlerInterceptor {
    
    
    @Override   //Controller之前执行,true——放开拦截;false——不放开
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("前期处理");
        return true;
    }

    @Override   //Controller之后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    
        System.out.println("请求被拦截");
    }

    @Override   //视图渲染完毕后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    
        System.out.println("后期处理");
    }
}

(2) Register interceptor

@Configuration
public class LoginConfig implements WebMvcConfigurer {
    
    
    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
    	//注册拦截器并配置拦截路径与非拦截路径
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/loign");
    }
}

3. The details of the interceptor

(1) Execution process

  • When the web server starts, first start the Filter class init() method.
  • The browser sends a request. After the server receives the request, the filter Filterfirst intercepts it, DispatcherServletand forwards it to the interceptor through the front-end controller. The data is processed before Interceptorthe request enters the controller . After judging that it can be released, the request enters resource access.Controller
  • After the request to access resources is completed, it returns to the interceptor for processing, then forwards to the front controller, then forwards to the filter, and finally returns to the browser.

insert image description here

(2) interception path

  • Common Intercept Paths
path mode example illustrate
primary path /* Intercept /login, /list, cannot intercept /depts/1
Arbitrary interception /** full path interception
A first-level path under a certain path /depts/* Can intercept /depts/1, cannot intercept /depts/1/2, /depts
All paths under a certain path /depts/** Can intercept all paths under /depts

(6) The difference between filters and interceptors

  • Interface Specification: Filter—— Filter; Interceptor——HandlerInterceptor
  • Intercept scope: filter - intercept all resources; interceptor - intercept resources in the Spring environment

3. Exception handling

two solutions

  • Solution 1: Perform try...catch processing in all methods of Controller
  • Solution 2: Define a global exception handler

(1) Use of exception handlers

1. Define the exception handler

@RestControllerAdvice   //声明控制器异常处理,相当于@ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {
    
    
    //统一进行异常处理,并向浏览器返回异常结果
    @ExceptionHandler(Exception.class)	//定义捕获的异常类型 Exception是所有异常的父类
    public int ex(Exception ex){
    
    
        ex.printStackTrace();
        return 500;
    }
}

Guess you like

Origin blog.csdn.net/Zain_horse/article/details/131450435