Spring控制器调用其他控制器

时间:2012-02-17 02:26:55

标签: spring

我正在尝试提供一个主控制器,它将根据需要负责调用多个控制器(一个或多个),合并数据,过滤数据并将其返回。 消费者无需担心系统中的这些多个端点。他们只是跟这个主端点说话。

这是正确的做法吗?请建议

ModelAndView handle(HttpServletRequest request, HttpServletResponse response)  throws Exception {

    final HandlerMapping handlerMapping = applicationContext.getBean(HandlerMapping.class);
    final HandlerExecutionChain handler = handlerMapping.getHandler(request);
    assertNotNull("No handler found for request, check you request mapping", handler);

    final Object controller = handler.getHandler();
    // if you want to override any injected attributes do it here

    final HandlerInterceptor[] interceptors =
        handlerMapping.getHandler(request).getInterceptors();
    for (HandlerInterceptor interceptor : interceptors) {
        final boolean carryOn = interceptor.preHandle(request, response, controller);
        if (!carryOn) {
            return null;
        }
    }

    final ModelAndView mav = handlerAdapter.handle(request, response, controller);
    return mav;
}

@RequestMapping(value = "/query", method = RequestMethod.POST) 
public ModelAndView execute() throws Exception {
    request.setRequestURI("/test.html");
    request.setMethod("GET");
    return handle(request, response);
}

2 个答案:

答案 0 :(得分:1)

spring MVC框架已经是这个主控制器了。

子控制器是用@Controller注释的类,过滤器名为Handler Interceptor,必须实现HandlerInterceptor接口(或扩展HandlerInterceptorAdapter

所以为了回到你的问题:“这是正确的方法吗?” - 不,不是,因为它已经存在。

答案 1 :(得分:0)

为什么不创建1个控制器(主控制器),然后自动装配您需要的控制器并调用这些控制器的方法。

例如

@Controller
public class MasterController {
   @Autowired
   private Controller1 controller1;
   @Autowired
   private Controller1 controller2;

   @RequestMapping("/master/sample")
   public Sample getSample() {
        Sample sample1 = controller1.getSample():
        Sample sample2 = controller2.getSample():
        // additional processing
   }
}

@Controller
public class Controller1 {
   @RequestMapping("/controller1/sample")
   public Sample getSample() {
        return something;
   }
}