SpringBoot 错误处理机制与自定义错误处理实现详解

【1】SpringBoot的默认错误处理

① 浏览器访问

请求头如下:

② 使用“PostMan”访问

{
  "timestamp": 1529479254647,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/aaa1"
}

请求头如下:

总结:如果是浏览器访问,则SpringBoot默认返回错误页面;如果是其他客户端访问,则默认返回JSON数据。

【2】默认错误处理原理

SpringBoot默认配置了许多xxxAutoConfiguration,这里我们找ErrorMvcAutoConfiguration。

其注册部分组件如下:

① DefaultErrorAttributes

@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
  return new DefaultErrorAttributes();
}

跟踪其源码如下:

public class DefaultErrorAttributes
    implements ErrorAttributes, HandlerExceptionResolver, Ordered {

  private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName()
      + ".ERROR";

  @Override
  public int getOrder() {
    return Ordered.HIGHEST_PRECEDENCE;
  }

  @Override
  public ModelAndView resolveException(HttpServletRequest request,
      HttpServletResponse response, Object handler, Exception ex) {
    storeErrorAttributes(request, ex);
    return null;
  }

  private void storeErrorAttributes(HttpServletRequest request, Exception ex) {
    request.setAttribute(ERROR_ATTRIBUTE, ex);
  }

  @Override
  public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
      boolean includeStackTrace) {
    Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
    errorAttributes.put("timestamp", new Date());
    addStatus(errorAttributes, requestAttributes);
    addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
    addPath(errorAttributes, requestAttributes);
    return errorAttributes;
  }

  private void addStatus(Map<String, Object> errorAttributes,
      RequestAttributes requestAttributes) {
    Integer status = getAttribute(requestAttributes,
        "javax.servlet.error.status_code");
    if (status == null) {
      errorAttributes.put("status", 999);
      errorAttributes.put("error", "None");
      return;
    }
    errorAttributes.put("status", status);
    try {
      errorAttributes.put("error", HttpStatus.valueOf(status).getReasonPhrase());
    }
    catch (Exception ex) {
      // Unable to obtain a reason
      errorAttributes.put("error", "Http Status " + status);
    }
  }

  private void addErrorDetails(Map<String, Object> errorAttributes,
      RequestAttributes requestAttributes, boolean includeStackTrace) {
    Throwable error = getError(requestAttributes);
    if (error != null) {
      while (error instanceof ServletException && error.getCause() != null) {
        error = ((ServletException) error).getCause();
      }
      errorAttributes.put("exception", error.getClass().getName());
      addErrorMessage(errorAttributes, error);
      if (includeStackTrace) {
        addStackTrace(errorAttributes, error);
      }
    }
    Object message = getAttribute(requestAttributes, "javax.servlet.error.message");
    if ((!StringUtils.isEmpty(message) || errorAttributes.get("message") == null)
        && !(error instanceof BindingResult)) {
      errorAttributes.put("message",
          StringUtils.isEmpty(message) ? "No message available" : message);
    }
  }

  private void addErrorMessage(Map<String, Object> errorAttributes, Throwable error) {
    BindingResult result = extractBindingResult(error);
    if (result == null) {
      errorAttributes.put("message", error.getMessage());
      return;
    }
    if (result.getErrorCount() > 0) {
      errorAttributes.put("errors", result.getAllErrors());
      errorAttributes.put("message",
          "Validation failed for object='" + result.getObjectName()
              + "'. Error count: " + result.getErrorCount());
    }
    else {
      errorAttributes.put("message", "No errors");
    }
  }

  private BindingResult extractBindingResult(Throwable error) {
    if (error instanceof BindingResult) {
      return (BindingResult) error;
    }
    if (error instanceof MethodArgumentNotValidException) {
      return ((MethodArgumentNotValidException) error).getBindingResult();
    }
    return null;
  }

  private void addStackTrace(Map<String, Object> errorAttributes, Throwable error) {
    StringWriter stackTrace = new StringWriter();
    error.printStackTrace(new PrintWriter(stackTrace));
    stackTrace.flush();
    errorAttributes.put("trace", stackTrace.toString());
  }

  private void addPath(Map<String, Object> errorAttributes,
      RequestAttributes requestAttributes) {
    String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri");
    if (path != null) {
      errorAttributes.put("path", path);
    }
  }

  @Override
  public Throwable getError(RequestAttributes requestAttributes) {
    Throwable exception = getAttribute(requestAttributes, ERROR_ATTRIBUTE);
    if (exception == null) {
      exception = getAttribute(requestAttributes, "javax.servlet.error.exception");
    }
    return exception;
  }

  @SuppressWarnings("unchecked")
  private <T> T getAttribute(RequestAttributes requestAttributes, String name) {
    return (T) requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
  }

}

即,填充错误数据!

② BasicErrorController

@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
  return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
      this.errorViewResolvers);
}

跟踪其源码:

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
  //产生html类型的数据;浏览器发送的请求来到这个方法处理
  @RequestMapping(produces = "text/html")
  public ModelAndView errorHtml(HttpServletRequest request,
      HttpServletResponse response) {
    HttpStatus status = getStatus(request);
    Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
        request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
    response.setStatus(status.value());
    //去哪个页面作为错误页面;包含页面地址和页面内容
    ModelAndView modelAndView = resolveErrorView(request, response, status, model);
    return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
  }
  //产生json数据,其他客户端来到这个方法处理;
  @RequestMapping
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request,
        isIncludeStackTrace(request, MediaType.ALL));
    HttpStatus status = getStatus(request);
    return new ResponseEntity<Map<String, Object>>(body, status);
  }
  //...
}

其中 resolveErrorView(request, response, status, model);方法跟踪如下:

public abstract class AbstractErrorController implements ErrorController {
protected ModelAndView resolveErrorView(HttpServletRequest request,
      HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
      //拿到所有的错误视图解析器
    for (ErrorViewResolver resolver : this.errorViewResolvers) {
      ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
      if (modelAndView != null) {
        return modelAndView;
      }
    }
    return null;
  }
//...
}

③ ErrorPageCustomizer

@Bean
public ErrorPageCustomizer errorPageCustomizer() {
  return new ErrorPageCustomizer(this.serverProperties);
}

跟踪其源码:

@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
  ErrorPage errorPage = new ErrorPage(this.properties.getServletPrefix()
      + this.properties.getError().getPath());
  errorPageRegistry.addErrorPages(errorPage);
}
//getPath()->go on
  /**
   * Path of the error controller.
   */
  @Value("${error.path:/error}")
  private String path = "/error";

即,系统出现错误以后来到error请求进行处理(web.xml注册的错误页面规则)。

④ DefaultErrorViewResolver

@Bean
@ConditionalOnBean(DispatcherServlet.class)
@ConditionalOnMissingBean
public DefaultErrorViewResolver conventionErrorViewResolver() {
  return new DefaultErrorViewResolver(this.applicationContext,
      this.resourceProperties);
}

跟踪其源码:

public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {

  private static final Map<Series, String> SERIES_VIEWS;
  //错误状态码
  static {
    Map<Series, String> views = new HashMap<Series, String>();
    views.put(Series.CLIENT_ERROR, "4xx");
    views.put(Series.SERVER_ERROR, "5xx");
    SERIES_VIEWS = Collections.unmodifiableMap(views);
  }
  //...
  @Override
  public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
      Map<String, Object> model) {
  // 这里如果没有拿到精确状态码(如404)的视图,则尝试拿4XX(或5XX)的视图
    ModelAndView modelAndView = resolve(String.valueOf(status), model);
    if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
      modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
    }
    return modelAndView;
  }

  private ModelAndView resolve(String viewName, Map<String, Object> model) {
    //默认SpringBoot可以去找到一个页面? error/404||error/4xx
    String errorViewName = "error/" + viewName;
    //模板引擎可以解析这个页面地址就用模板引擎解析
    TemplateAvailabilityProvider provider = this.templateAvailabilityProviders
        .getProvider(errorViewName, this.applicationContext);
    if (provider != null) {
      //模板引擎可用的情况下返回到errorViewName指定的视图地址
      return new ModelAndView(errorViewName, model);
    }
    //模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
    return resolveResource(errorViewName, model);
  }

  private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
    //从静态资源文件夹下面找错误页面
    for (String location : this.resourceProperties.getStaticLocations()) {
      try {
        Resource resource = this.applicationContext.getResource(location);
        resource = resource.createRelative(viewName + ".html");
        if (resource.exists()) {
          return new ModelAndView(new HtmlResourceView(resource), model);
        }
      }
      catch (Exception ex) {
      }
    }
    return null;
  }

总结如下:

一但系统出现4xx或者5xx之类的错误,ErrorPageCustomizer就会生效(定制错误的响应规则),就会来到/error请求,然后被BasicErrorController处理返回ModelAndView或者JSON。

【3】定制错误响应

① 定制错误响应页面

1)有模板引擎的情况下

error/状态码–将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的error文件夹下,发生此状态码的错误就会来到 对应的页面。

我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)。

如下图所示:

页面能获取的信息;

timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里

2)没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找。

3)以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面。

WebMVCAutoConfiguration源码如下:

@Configuration
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
@Conditional(ErrorTemplateMissingCondition.class)
protected static class WhitelabelErrorViewConfiguration {

  private final SpelView defaultErrorView = new SpelView(
      "<html><body><h1>Whitelabel Error Page</h1>"
          + "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"
          + "<div id='created'>${timestamp}</div>"
          + "<div>There was an unexpected error (type=${error}, status=${status}).</div>"
          + "<div>${message}</div></body></html>");

  @Bean(name = "error")
  @ConditionalOnMissingBean(name = "error")
  public View defaultErrorView() {
    return this.defaultErrorView;
  }

  // If the user adds @EnableWebMvc then the bean name view resolver from
  // WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.
  @Bean
  @ConditionalOnMissingBean(BeanNameViewResolver.class)
  public BeanNameViewResolver beanNameViewResolver() {
    BeanNameViewResolver resolver = new BeanNameViewResolver();
    resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
    return resolver;
  }

}

② 定制错误响应数据

第一种,使用SpringMVC的异常处理器

@ControllerAdvice
public class MyExceptionHandler {

  //浏览器客户端返回的都是json
  @ResponseBody
  @ExceptionHandler(UserNotExistException.class)
  public Map<String,Object> handleException(Exception e){
    Map<String,Object> map = new HashMap<>();
    map.put("code","user.notexist");
    map.put("message",e.getMessage());
    return map;
  }
}

这样无论浏览器还是PostMan返回的都是JSON!

第二种,转发到/error请求进行自适应效果处理

 @ExceptionHandler(UserNotExistException.class)
 public String handleException(Exception e, HttpServletRequest request){
    Map<String,Object> map = new HashMap<>();
    //传入我们自己的错误状态码 4xx 5xx
    /**
    * Integer statusCode = (Integer) request
    .getAttribute("javax.servlet.error.status_code");
    */
    request.setAttribute("javax.servlet.error.status_code",500);
    map.put("code","user.notexist");
    map.put("message","用户出错啦");
    //转发到/error
    return "forward:/error";
  }

但是此时没有将自定义 code message传过去!

第三种,注册MyErrorAttributes继承自DefaultErrorAttributes(推荐)

从第【2】部分(默认错误处理原理)中知道错误数据都是通过DefaultErrorAttributes.getErrorAttributes()方法获取,如下所示:

  @Override
  public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
      boolean includeStackTrace) {
    Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
    errorAttributes.put("timestamp", new Date());
    addStatus(errorAttributes, requestAttributes);
    addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
    addPath(errorAttributes, requestAttributes);
    return errorAttributes;
  }

我们可以编写一个MyErrorAttributes继承自DefaultErrorAttributes重写其getErrorAttributes方法将我们的错误数据添加进去。

示例如下:

//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

  //返回值的map就是页面和json能获取的所有字段
  @Override
  public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    //DefaultErrorAttributes的错误数据
    Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
    map.put("company","SpringBoot");
    //我们的异常处理器携带的数据
    Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
    map.put("ext",ext);
    return map;
  }
}

异常处理器修改如下:

@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
   Map<String,Object> map = new HashMap<>();
   //传入我们自己的错误状态码 4xx 5xx
   /**
   * Integer statusCode = (Integer) request
   .getAttribute("javax.servlet.error.status_code");
   */
   request.setAttribute("javax.servlet.error.status_code",500);
   map.put("code","user.notexist");
   map.put("message","用户出错啦");
  //将自定义错误数据放入request中
   request.setAttribute("ext",map);
   //转发到/error
   return "forward:/error";
 }

5xx.html页面代码如下:

//...
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
  <h1>status:[[${status}]]</h1>
  <h2>timestamp:[[${timestamp}]]</h2>
  <h2>exception:[[${exception}]]</h2>
  <h2>message:[[${message}]]</h2>
  <h2>ext:[[${ext.code}]]</h2>
  <h2>ext:[[${ext.message}]]</h2>
</main>
//...

浏览器测试效果如下:

Postman测试效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot错误处理机制以及自定义异常处理详解

    上篇文章我们讲解了使用Hibernate Validation来校验数据,当校验完数据后,如果发生错误我们需要给客户返回一个错误信息,因此这节我们来讲解一下SpringBoot默认的错误处理机制以及如何自定义异常来处理请求错误. 一.SpringBoot默认的错误处理机制 我们在发送一个请求的时候,如果发生404 SpringBoot会怎么处理呢?我们来发送一个不存在的请求来验证一下看看页面结果.如下所示: 当服务器内部发生错误的时候,页面会返回什么呢? @GetMapping("/user/{

  • SpringBoot2.X Kotlin系列之数据校验和异常处理详解

    在开发项目时,我们经常需要在前后端都校验用户提交的数据,判断提交的数据是否符合我们的标准,包括字符串长度,是否为数字,或者是否为手机号码等:这样做的目的主要是为了减少SQL注入攻击的风险以及脏数据的插入.提到数据校验我们通常还会提到异常处理,因为为了安全起见,后端出现的异常我们通常不希望直接抛到客户端,而是经过我们的处理之后再返回给客户端,这样做主要是提升系统安全性,另外就是给予用户友好的提示. 定义实体并加上校验注解 class StudentForm() { @NotBank(message

  • 详解Springboot自定义异常处理

    背景 Springboot 默认把异常的处理集中到一个ModelAndView中了,但项目的实际过程中,这样做,并不能满足我们的要求.具体的自定义异常的处理,参看以下 具体实现 如果仔细看完spring boot的异常处理详解,并且研究过源码后,我觉得具体的实现可以不用看了... 重写定义错误页面的url,默认只有一个/error @Bean public EmbeddedServletContainerCustomizer containerCustomizer(){ return new E

  • SpringBoot使用统一异常处理详解

    场景:针对异常处理,我们原来的做法是一般在最外层捕获异常即可,例如在Controller中 @Controller public class HelloController { private static final Logger logger = LoggerFactory.getLogger(HelloController.class); @GetMapping(value = "/hello") @ResponseBody public Result hello() { try

  • SpringBoot学习之全局异常处理设置(返回JSON)

    SpringBoot学习--全局异常处理设置(返回JSON) 需求 现在习惯使用ajax的方式发起请求,所以经常需要服务端返回一个json或者字符串. 控制全局的异常处理. 如果在单个方法中使用try,catch把方法包裹起来,工作量大,而且会异常的抛出而导致@Transactional注解的方法事务不会回滚. 说明 使用@ControllerAdvice注解 使用@ExceptionHandler注解 @ControllerAdvice 该注解是spring2.3以后新增的一个注解,主要是用来

  • SpringBoot初始教程之统一异常处理详解

    1.介绍 在日常开发中发生了异常,往往是需要通过一个统一的异常处理处理所有异常,来保证客户端能够收到友好的提示.SpringBoot在页面发生异常的时候会自动把请求转到/error,SpringBoot内置了一个BasicErrorController对异常进行统一的处理,当然也可以自定义这个路径 application.yaml server: port: 8080 error: path: /custom/error BasicErrorController提供两种返回错误一种是页面返回.当

  • springboot全局异常处理详解

    一.单个controller范围的异常处理 package com.xxx.secondboot.web; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import

  • 浅谈SpringBoot 中关于自定义异常处理的套路

    在 Spring Boot 项目中 ,异常统一处理,可以使用 Spring 中 @ControllerAdvice 来统一处理,也可以自己来定义异常处理方案.Spring Boot 中,对异常的处理有一些默认的策略,我们分别来看. 默认情况下,Spring Boot 中的异常页面 是这样的: 我们从这个异常提示中,也能看出来,之所以用户看到这个页面,是因为开发者没有明确提供一个 /error 路径,如果开发者提供了 /error 路径 ,这个页面就不会展示出来,不过在 Spring Boot 中

  • springboot 错误处理小结

    在 java web开发过程中,难免会有一些系统异常或人为产生一些异常.在 RESTful springboot 项目中如何优雅的处理? 分析:在RESTful 风格的springboot 项目中,返回的都是 body 对象,所以定义一个结果基类,其中包含 status,message,data(请求方法的返回结果),是比较合适的. 如果定义多个异常类进行处理,会比较麻烦.比如StudentNotExistsException.StudentExistsException...等,并且不能指定错

  • SpringBoot 错误处理机制与自定义错误处理实现详解

    [1]SpringBoot的默认错误处理 ① 浏览器访问 请求头如下: ② 使用"PostMan"访问 { "timestamp": 1529479254647, "status": 404, "error": "Not Found", "message": "No message available", "path": "/aaa1&q

  • Java事件处理机制(自定义事件)实例详解

    Java事件处理机制 java中的事件机制的参与者有3种角色: 1.event object:事件状态对象,用于listener的相应的方法之中,作为参数,一般存在与listerner的方法之中 2.event source:具体的事件源,比如说,你点击一个button,那么button就是event source,要想使button对某些事件进行响应,你就需要注册特定的listener. 3.event listener:对每个明确的事件的发生,都相应地定义一个明确的Java方法.这些方法都集

  • SpringBoot自定义Starter实现流程详解

    目录 starter起步依赖 starter命名规则 自定义starter new module 添加依赖 simplebean 自动配置类 META-INF\spring.factories 在spring-boot-mytest中引入mystarter-spring-boot-starter 添加配置 通过@Autowired引用 启动访问 starter起步依赖 starter起步依赖是springboot一种非常重要的机制, 它打包了某些场景下需要用到依赖,将其统一集成到starter,

  • SpringBoot Jpa 自定义查询实现代码详解

    这篇文章主要介绍了SpringBoot Jpa 自定义查询实现代码详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 持久层Domain public interface BaomingDao extends JpaRepository<BaomingBean,Integer> { @Query(value = "select distinct t.actid from BaomingBean t where t.belongs=?

  • SpringBoot实现自定义事件的方法详解

    目录 简介 步骤1:自定义事件 步骤2:自定义监听器 方案1:ApplicationListener 方案2:SmartApplicationListener 步骤3:注册监听器 法1:@Component(适用于所有监听器) 法2:application.yml中添加配置 法3:启动类中注册 步骤4:发布事件 法1:注入ApplicationContext,调用其publishEvent方法 法2:启动类中发布 简介 说明 本文用实例来介绍如何在SpringBoot中自定义事件来使用观察者模式

  • SpringBoot Starter机制及整合tomcat的实现详解

    目录 Starter机制和springboot整合tomcat Starter机制 springboot整合tomcat 总结 Starter机制和springboot整合tomcat Starter机制 先解释一下什么是Starter机制.Starter机制就是maven工程中pom文件引入了某个Starter依赖,就能使用对应的功能 例如 引入web的starter依赖 ,就可以使用有关于web方面的功能. <dependency> <groupId>org.springfra

  • SpringBoot自定义启动器Starter流程详解

    目录 一.背景 二.自定义启动器 1.创建一个启动器的自动配置模块 2.创建一个启动器模块 3.在业务模块中引入启动器 一.背景 虽然Spring官方给我们提供了很多的启动器供我们使用 但有时候我们也会遇到某些特殊场景,这些启动器满足不了 这个时候就需要自定义一个启动器供我们使用 二.自定义启动器 在之前学习Spring Boot的过程中,我们已经对启动器有了一个大致的了解 Spring Boot实现某个功能,一般是引入对应场景的启动器(一般不写代码,只是声明这个启动器需要引用哪些依赖),然后这

  • springboot多数据源配置及切换的示例代码详解

    注:本文的多数据源配置及切换的实现方法是,在框架中封装,具体项目中配置及使用,也适用于多模块项目 配置文件数据源读取 通过springboot的Envioment和Binder对象进行读取,无需手动声明DataSource的Bean yml数据源配置格式如下: spring: datasource: master: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver url:

  • Springboot集成Spring Security实现JWT认证的步骤详解

    1 简介 Spring Security作为成熟且强大的安全框架,得到许多大厂的青睐.而作为前后端分离的SSO方案,JWT也在许多项目中应用.本文将介绍如何通过Spring Security实现JWT认证. 用户与服务器交互大概如下: 客户端获取JWT,一般通过POST方法把用户名/密码传给server: 服务端接收到客户端的请求后,会检验用户名/密码是否正确,如果正确则生成JWT并返回:不正确则返回错误: 客户端拿到JWT后,在有效期内都可以通过JWT来访问资源了,一般把JWT放在请求头:一次

  • flask路由分模块管理及自定义restful响应格式详解

    目录 一.flask路由分模块管理 1.1.使用蓝图 1.2.使用flask_restful 二.自定义flask_restful响应格式 一.flask路由分模块管理 1.1.使用蓝图 在flask中可以使用蓝图Blueprint来进行创建路由进行分模块. 具体操作,我们可以在项目根目录下创建一个controller文件夹来存储分模块的路由. 在controller文件夹里创建product_controller.py,在里面如下写法引入蓝图,并且注册蓝图: from flask import

随机推荐