Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I use spring3 @Controller like this:

@RequestMapping("/userCenter")

@Controller
public class LoginCtrl {
    @RequestMapping("/loginPage")
    public String login(HttpServletRequest request,HttpServletResponse response,Model model) throws Exception { 
        return "userCenter/loginPage";
    }
}

It is ok, I get the the loginPage.jsp right content in browser.

but when I change @Controller to @RestController

the localhost:8080//userCenter/loginPage return a page with the string "userCenter/loginPage"

So,how could I use @RestController to get jsp pages like @Controller?

like image 746
blackcatIan Avatar asked Sep 25 '14 05:09

blackcatIan


People also ask

How do I return a JSP page?

If you want to return a view, configure another class with @Controller and return that view accordingly. Show activity on this post. @RestController actually returns the HTTP response as JSON or XML only. @RestController is internally annotated with @ResponseBody.

How do I return a view from RestController?

@RestController is not meant to be used to return views to be resolved. It is supposed to return data which will be written to the body of the response, hence the inclusion of @ResponseBody .

What is the return type of RestController?

As name suggest, it shall be used in case of REST style controllers i.e. handler methods shall return the JSON/XML response directly to client rather using view resolvers. It is a convenience annotation that is itself annotated with @Controller and @ResponseBody .


2 Answers

Actually, a @RestController can also return view:

  1. Set the controller method's return type to be ModelAndView

  2. Set your view path like this:

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

  3. return mav;

You get the correct JSO page view content.

like image 120
blackcatIan Avatar answered Oct 23 '22 15:10

blackcatIan


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.

like image 43
Sotirios Delimanolis Avatar answered Oct 23 '22 15:10

Sotirios Delimanolis