溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot攔截器實(shí)現(xiàn)登錄攔截的方法示例

發(fā)布時(shí)間:2020-10-17 15:10:47 來(lái)源:腳本之家 閱讀:186 作者:斷橋殘雪 欄目:編程語(yǔ)言

源碼

GitHub:https://github.com/291685399/springboot-learning/tree/master/springboot-interceptor01

SpringBoot攔截器可以做什么

可以對(duì)URL路徑進(jìn)行攔截,可以用于權(quán)限驗(yàn)證、解決亂碼、操作日志記錄、性能監(jiān)控、異常處理等

SpringBoot攔截器實(shí)現(xiàn)登錄攔截

pom.xml:

<?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>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/>
  </parent>
  <groupId>com.wyj</groupId>
  <artifactId>springboot-interceptor01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot-interceptor01</name>
  <description>springboot攔截器</description>

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <!-- springboot -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>

    <!-- lombok -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>

    <!-- thymeleaf -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  </dependencies>

  <build>
    <finalName>springboot-interceptor01</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

WebMvcConfigurer:繼承WebMvcConfigurationSupport類,重寫addInterceptors方法

/**
 * 在springboot2.0.0之后,WebMvcConfigurerAdapter已經(jīng)過(guò)時(shí)了
 * 會(huì)使用WebMvcConfigurer或者WebMvcConfigurationSupport替代
 *
 * @author wyj
 * @create 2019-06-01 21:48
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

  /**
   * 在springboot2.0.0之前繼承WebMvcConfigurerAdapter類,重寫addInterceptors方法
   *
   * @param registry
   */
//  @Override
//  public void addInterceptors(InterceptorRegistry registry) {
//    /**
//     * 攔截器按照順序執(zhí)行,如果不同攔截器攔截存在相同的URL,前面的攔截器會(huì)執(zhí)行,后面的攔截器將不執(zhí)行
//     */
//    registry.addInterceptor(new AuthorityInterceptor())
//        .addPathPatterns("/user/**");
//    super.addInterceptors(registry);
//  }

  /**
   * 在springboot2.0.0之后實(shí)現(xiàn)WebMvcConfigurer接口,重寫addInterceptors方法
   *
   * @param registry
   */
//  @Override
//  public void addInterceptors(InterceptorRegistry registry) {
//    /**
//     * 攔截器按照順序執(zhí)行,如果不同攔截器攔截存在相同的URL,前面的攔截器會(huì)執(zhí)行,后面的攔截器將不執(zhí)行
//     */
//    registry.addInterceptor(new AuthorityInterceptor())
//        .addPathPatterns("/user/**");
//  }

  /**
   * 在springboot2.0.0之后繼承WebMvcConfigurationSupport類,重寫addInterceptors方法
   *
   * @param registry
   */
  @Override
  protected void addInterceptors(InterceptorRegistry registry) {
    /**
     * 攔截器按照順序執(zhí)行,如果不同攔截器攔截存在相同的URL,前面的攔截器會(huì)執(zhí)行,后面的攔截器將不執(zhí)行
     */
    registry.addInterceptor(new AuthorityInterceptor())
        .addPathPatterns("/user/**");
    super.addInterceptors(registry);
  }
}

AuthorityInterceptor:實(shí)現(xiàn)HandlerInterceptor接口,重寫preHandle、postHandle、afterCompletion方法

  • preHandle:在請(qǐng)求處理之前進(jìn)行調(diào)用(Controller方法調(diào)用之前)
  • postHandle:請(qǐng)求處理之后進(jìn)行調(diào)用,但是在視圖被渲染之前(Controller方法調(diào)用之后)
  • afterCompletion:在整個(gè)請(qǐng)求結(jié)束之后被調(diào)用,也就是在DispatcherServlet 渲染了對(duì)應(yīng)的視圖之后執(zhí)行(主要是用于進(jìn)行資源清理工作)
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

  private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();//不攔截的URI

  static {
    NOT_INTERCEPT_URI.add("/user/login.html");
    NOT_INTERCEPT_URI.add("/user/login");
  }

  /**
   * 在請(qǐng)求處理之前進(jìn)行調(diào)用(Controller方法調(diào)用之前)
   */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
               Object object) throws Exception {
    String uri = request.getRequestURI();
    if (NOT_INTERCEPT_URI.contains(uri)) {
      log.info("不攔截" + uri);
      return true;
    }
    log.info("攔截" + uri);
    HttpSession session = request.getSession();
    UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session");
    if (userInfo == null) {
      throw new RuntimeException("用戶未登陸");
    }
    return true;
  }

  /**
   * 請(qǐng)求處理之后進(jìn)行調(diào)用,但是在視圖被渲染之前(Controller方法調(diào)用之后)
   */
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception {
  }

  /**
   * 在整個(gè)請(qǐng)求結(jié)束之后被調(diào)用,也就是在DispatcherServlet 渲染了對(duì)應(yīng)的視圖之后執(zhí)行
   * (主要是用于進(jìn)行資源清理工作)
   */
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception {
  }
}

UserController:

@Controller
@RequestMapping(value = "/user")
public class UserController {

  @RequestMapping(value = "/login.html")
  public String index() {
    return "login";
  }

  @RequestMapping(value = "/login")
  public String login(User user) {
    //查詢數(shù)據(jù)庫(kù),我這里直接寫死
    User dbUser = new User(1, "zhangsan", "123456", "admin");
    if (dbUser.getPassword().equals(user.getPassword())) {
      UserInfo userInfo = new UserInfo(dbUser.getId(), dbUser.getUsername(), dbUser.getRole());
      HttpSession session = getRequest().getSession();
      session.setAttribute("user_info_in_the_session", userInfo);
      return "admin";
    }
    return "login";
  }

  @RequestMapping(value = "/userInfo")
  @ResponseBody
  public String userInfo() {
    HttpSession session = getRequest().getSession();
    UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session");
    return userInfo.toString();
  }

  private HttpServletRequest getRequest() {
    return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
  }
}

User:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

  private int id;
  private String username;
  private String password;
  private String role;

}

UserInfo: 用于存在用戶信息儲(chǔ)存在session中

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo implements Serializable {

  private int id;
  private String username; 
  private String role;

}

login.html:只是一個(gè)很簡(jiǎn)單的登錄表單

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>登陸頁(yè)面</title>
</head>
<body>
<form action="/user/login" method="post">
  登陸:<br/>
  用戶名:<input name="username" id="username" type="text"/><br/>
  密&nbsp;&nbsp;&nbsp;碼:<input name="password" id="password" type="password"/><br/>
  <input type="submit" value="登陸"/>
</form>
</body>
</html>

admin.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首頁(yè)</title>
</head>
<body>
<form action="/user/userInfo" method="get">
  <input type="submit" value="用戶信息"/></form>
</body>
</html>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI