【问题标题】:How to exclude static resources from requestmapping如何从请求映射中排除静态资源
【发布时间】:2019-01-04 12:59:33
【问题描述】:

我正在尝试从 @RequestMapping 路径中​​排除静态资源以避免对方法的冗余调用。

我试图简单地检查 url,如果它是一个什么都不做的资源,但拦截器在之后没有找到该资源,它仍然运行了这些方法,因为它们是用 @ModelAttribute 注释的。

GlobalController.java

@RequestMapping(value = "/")
public class GlobalControllerAdvice {

    public static int k;

    @Autowired
    private UsersService usersService;

    @ModelAttribute("unread")
    public int unread(Principal principal) {

        int unread = 0;

        k++;
        System.err.println("Inside unread " + k);

        if (principal != null) {
            User user = usersService.getWithUser(principal.getName(), "notifications");
            for (Notification n : user.getNotifications())
                if (!n.isRead())
                    unread++;
        }

        return unread;
    }
}

资源处理程序

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("/resources/");
}

预期结果应该排除所有包含“静态”的 url,但现在它没有,并且我的 jsp 页面中的每个图像和脚本都会调用 unread()。

【问题讨论】:

    标签: spring spring-mvc controller


    【解决方案1】:

    如果你只想用 Spring 做这件事,有可能但有点混乱:

    1. 您需要使用SimpleUrlHandlerMapping 可以明确指定应该映射到的 URL 模式 控制器或扩展它以支持“忽略” URL,如“css/**”。
    2. 您需要编写自己的 HttpRequestHandler 实现 基本上包括 “getServletContext().getRequestDsipatcher().include()”调用 按原样返回请求的资源。
    3. 您必须将该处理程序注册为上述处理程序的默认处理程序 SimpleUrlHandlerMapping。

    完成所有操作后,所有无法映射到您的控制器的请求都将转发到您的 HttpRequestHandler 并“按原样”提供服务。

    【讨论】:

      【解决方案2】:
      @SuppressWarnings("deprecation")
      @Configuration
      public class DefaultView extends WebMvcConfigurerAdapter {
      
          @SuppressWarnings("SpringMVCViewInspection")
          @Override
          public void addViewControllers(ViewControllerRegistry registry) {
              registry.addViewController("/files/**").setViewName("forward:/index.html");
              registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
              super.addViewControllers(registry);
          }
      }
      

      screenshot of project structure

      【讨论】:

        猜你喜欢
        • 2017-02-21
        • 2014-04-13
        • 1970-01-01
        • 2018-12-08
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多