how to use spring4 @RestController to return a jsp page?

后端 未结 5 1535
野趣味
野趣味 2020-12-10 16:59

When I use spring3 @Controller like this:

@RequestMapping(\"/userCenter\")

@Controller
public class LoginCtrl {
    @RequestMapping(\"/loginPage\")
    publ         


        
相关标签:
5条回答
  • 2020-12-10 17:07

    @RestController configures @ResponseBody for every body automatically , it means it is designed to write everything on the output and not to return views. If in case you want to return a view configure another class with @Controller and return the view accordingly

    0 讨论(0)
  • 2020-12-10 17:09

    You shouldn't. A @RestController is not meant to return view names through a String return type/value. It's meant to return something that will be written to the response body directly.

    More concretely (in the general configuration case), Spring MVC configures its return value handlers in RequestMappingHandlerAdapter#getDefaultReturnValueHandlers(). If you look at that implementation, the handler for String view names, ViewNameMethodReturnValueHandler, is registered after the handler for @RestController (really @ResponseBody), RequestResponseBodyMethodProcessor.

    If you really have to, you can declare your method to have a return type of View or ModelAndView (the handlers for these, ViewMethodReturnValueHandler and ModelAndViewMethodReturnValueHandler, are registered before RequestResponseBodyMethodProcessor) and return the appropriate object, with an identifying view name.

    0 讨论(0)
  • 2020-12-10 17:14

    Check the API docs for @RestController it is annotated with @ResponseBody itself, which indicates that method return value should be bound to the web response body. The configured view objects will never come into play, so it cannot map to any view. My question is why you want to use the RestController anyway, its not meant to map to any views?

    0 讨论(0)
  • 2020-12-10 17:14

    Could still be useful with @RestController for creating redirect fallback to you REST Api

    @GetMapping("/**")
    public ModelAndView Default()
    {
        ModelAndView mav = new ModelAndView("redirect:/actuator/health");
        return mav;
    }
    
    0 讨论(0)
  • 2020-12-10 17:17

    Actually,@RestController could also return view...

    After one day research and read document,I got a solution

    Let me share the solution with everyone:

    First,set the controller method's return type to be "ModelAndView"

    Second,set your view path like this

    ModelAndView mav = new ModelAndView("userCenter/loginPage");
    

    Finally

    return mav;
    

    You would get the right jsp page view content

    0 讨论(0)
提交回复
热议问题