【问题标题】:I'm looking for the way to handle pre & post processing of Controller in Spring Boot + thymeleaf我正在寻找在 Spring Boot + thymeleaf 中处理控制器前后处理的方法
【发布时间】:2015-08-13 09:51:24
【问题描述】:

我一直在寻找处理控制器前后处理的方法。

我想为每个请求和响应添加一个过程。 例如: 检查每个请求的标头或添加隐藏字段,在我们响应的每个表单标签中都包含哈希码。

如果有样品,或者任何想法,请给我。

【问题讨论】:

  • 阅读 Spring 文档中的面向方面编程 (AOP)。
  • 也许实现一个自定义过滤器,您可以在其中获取 HttpRequest 和/或 HttpResponse 对象并对其进行修改。

标签: spring-boot thymeleaf


【解决方案1】:

感谢您的建议。

我能够从这个页面找到结果。

http://www.concretepage.com/spring/spring-mvc/spring-handlerinterceptor-annotation-example-webmvcconfigureradapter

public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void addInterceptors(InterceptorRegistry registry) {
    super.addInterceptors(registry);
    registry.addInterceptor(new ControllerHandler());

    TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
}
}

public class ControllerHandler implements HandlerInterceptor  {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    System.out.println("---Before Method Execution---");
    return true;
}
@Override
public void postHandle( HttpServletRequest request, HttpServletResponse response,
        Object handler, ModelAndView modelAndView) throws Exception {
    System.out.println("---method executed---");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) throws Exception {
    System.out.println("---Request Completed---");
}
}

【讨论】:

    【解决方案2】:

    我找到了另一种方法,使用@ControllerAdvice。 此注释似乎侧重于错误处理。

    http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html1

    @ControllerAdvice
    public class ExceptionControllerAdvice {
    
     @InitBinder
     public void initBinder(WebDataBinder binder) {
        System.out.println("controller advice: init binder");
    }
    
    
    @ExceptionHandler(Exception.class)
    public String exception(Exception e) {
        System.out.println("controller advice: exception Handler");
        System.out.println(e.getMessage());
        return "error";
    }
    
    @ModelAttribute
    public void modelAttribute(){
        System.out.println("controller advice:model Attribute");
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 1970-01-01
      • 2018-09-03
      • 2019-10-09
      • 2017-03-08
      • 2018-11-13
      • 2018-11-07
      • 2020-09-26
      • 2016-01-27
      相关资源
      最近更新 更多