Spring MVC, forward

2020-02-10 03:00发布

Is there any difference between

public class Controller1 extends AbstractController {
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        return new AnotherController().handleRequest(request, response);
    }
}

and

@Controller
public class Controller1 {

    @RequestMapping ...
    public String handleRequest() {
        return "forward:/path_to_my_another_controller";
    }
}

2条回答
叼着烟拽天下
2楼-- · 2020-02-10 03:18

By creating controllers yourself, you will prevent Spring from injecting any dependencies into them. This may cause your self-created controllers to not work correctly.

If you really need to chain controllers like this, I would ask the Spring application context for an instance of the controller you want instead of creating one with the new operator.

查看更多
可以哭但决不认输i
3楼-- · 2020-02-10 03:25

They're similar, but not quite the same.

The second approach will create a new internal request to be forwarded on to the second controller, whereas the first one will re-use the same request object.

Whether or not that matters depends on what each of the controllers does to the request.

I've found that chaining controllers together using direct method calls is one of the more appealing aspects of Spring annotated controllers, it can make for a much more natural flow than chucking forwarded requests around.

As always, your mileage may vary.

查看更多
登录 后发表回答