从HttpServletRequest获取目标控制器

时间:2016-12-15 18:34:22

标签: java spring spring-security spring-security-oauth2

我已设置spring security来验证和授权进入我的应用程序的请求。我已按如此设置配置:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  skin = "blue",

  dashboardHeader(title = "Dynamic Menu"),
  dashboardSidebar(
    sidebarMenu(
      id = "sidebarMenu",
      menuItem("Home", tabName = "home", icon = icon("home")),
      menuItem("Item with subitems", tabName = "test",
               uiOutput("test_subitems"))
    )
  ),

  dashboardBody( id = "dashboardBody" )
)

server <- shinyServer(function(input, output, session) {
  observe(cat('1:', input$sidebarMenu, '\n'))

  output$test_subitems <- renderUI({
    print(input$sidebarMenu)
    tabs <- c("st1","st2")
    lapply(tabs, function(tab) {
      menuSubItem(icon = NULL, paste('Test:', tab), tabName = tab)
    })
  })

  session$onSessionEnded(stopApp)
})

shinyApp(ui, server)

我想获取有关此请求将要访问的目标控制器的一些信息。在这种情况下,控制器实际上不会受到影响,因为弹簧安全性已经启动并在响应到达控制器之前将其抛出。

任何提示? 谢谢!

2 个答案:

答案 0 :(得分:3)

假设OAuth2ServerConfiguration是一个Spring托管bean,这应该对你有用。

...

@Autowired
private List<HandlerMapping> handlerMappings;

for (HandlerMapping handlerMapping : handlerMappings) {
  HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request);
  if (handlerExecutionChain != null) {
     // handlerExecutionChain.getHandler() is your handler for this request
  }
}

如果无法自动装配HandlerMapping列表,请自动装配ApplicationContext并进行如下调整。

for (HandlerMapping handlerMapping : applicationContext.getBeansOfType(HandlerMapping.class).values()) {
  HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request);
  if (handlerExecutionChain != null) {
     // handlerExecutionChain.getHandler() is your handler for this request
  }
}

答案 1 :(得分:1)

你可以试试这个:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                // handler is the controller
                MyAnnotation annotation = ((HandlerMethod) handler).getMethod().getAnnotation(MyAnnotation.class)
                // do stuff with the annotation
            }
        });
    }
}