Spring MVC Controllers Return Type

后端 未结 6 1889
别跟我提以往
别跟我提以往 2020-12-23 11:39

I\'ve seen examples where a controller returns a String (which indicates the view)

@RequestMapping(value=\"/owners/{ownerId}\", method=RequestMethod.GET)
pub         


        
相关标签:
6条回答
  • 2020-12-23 12:24

    If we are talking about MVC 3, than, both are correct. But directly returning ModelAndView is the old way, and more verbal.

    If you are returning just a string (without @ResponseBody which is something else), this string is treated as view name, and spring pushes it to view resolvers - so, you dont have to worry (at least, while you are writing controllers), what type of view renderer you'll use (let it be jsp or velocity, it doesn't matter). You only propagate the Model instance, and returnes a hint what to do with it next. Proper ModelAndView object is made later internally by string.

    Generally, spring 3 gives you more flexibility with arguments and return types (see Defining @RequestMapping handler methods section in Spring documentaton).

    0 讨论(0)
  • 2020-12-23 12:34

    It's the same logic but it's not the same version of spring.

    The ModelAndView object is the spring 2.x way of handling model and views. In the example you gave, the modelandview object will load the "helloWorld" view (depending on your templating engine could be helloWorld.jsp, or helloWorld.html, ...) with one data "message" in the model.

    The other way is the spring 3.x way. You could have wrote exactly the same example as your helloworld.

    @RequestMapping(value="/helloWorld", method=RequestMethod.GET)
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "helloWorld";
    }
    

    The model is automaticly populated at request.

    And we can simplify this notation as the url mapping "helloWorld" is directly the view name.

    @RequestMapping(value="/helloWorld", method=RequestMethod.GET)
    public void helloWorld(Model model) {
         model.addAttribute("message", "Hello World!");
    }
    

    the helloWorld view will be automaticly loaded

    0 讨论(0)
  • 2020-12-23 12:34
    public String findOwner(@PathVariable String ownerId, Model model) {
      Owner owner = ownerService.findOwner(ownerId);  
      model.addAttribute("owner", owner);  
      return "displayOwner"
    }                       
    

    in this method the return type is String and we adding Model as a parameter so to add a value with model we will add like

     modelparam.addAttribute("obj",value);  
    

    and return to the displayowner to jsp as per view resolver

    public ModelAndView helloWorld() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("helloWorld");
        mav.addObject("message", "Hello World!");
        return mav;
    }
    

    in this method the return type is ModelAndView so we will return the model and here the mav is the object of ModelAndView so here we should add like

    model.addObject("object","value");
    

    here the viewname is returned to helloworld.jsp as per the viewResolver

    0 讨论(0)
  • 2020-12-23 12:35

    In Spring MVC, you should return ModelAndView if you want to render jsp page

    For example:

    @RequestMapping(value="/index.html", method=RequestMethod.GET)
        public ModelAndView indexView(){
            ModelAndView mv = new ModelAndView("index");
            return mv;
        }    
    

    this function will return index.jsp when you are hitting /index.html

    In addition you can return any JSON or XML object using @ResponseBody annotation and serializer.

    For example:

    @RequestMapping(value="/getStudent.do",method=RequestMethod.POST)
        @ResponseBody
        public List<Student> getStudent(@RequestParam("studentId") String id){
            List<Student> students = daoService.getStudent(id);
            return students;
        }
    

    In this example you will return List as JSON in case and you have enabled Jackson serializer. In order to enable that you need to add the following to your Spring XML:

    <context:annotation-config/> 
    

    And the Serializer itself:

    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <list>
        <ref bean="jacksonMessageConverter"/>
      </list>
    </property>
    </bean>
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-23 12:35

    Returning ModelAndView or a string does the same job. It resolves into a view (a jsp page) and giving a model object to be rendered in the view. If you return a string, spring internally resolves to a view using viewResolver, create a ModelAndView Object and return it. The returning of ModelAndView object is from the older version. You can do either of this based on your convenient.

    Have a look at this question

    Also bunch of answers are pointing out to @RequestBody. Its not exactly related to your question. But keep in mind that it will convert your object based on content-type using available converters and the resuly will be part of the document body.

    0 讨论(0)
  • 2020-12-23 12:43

    If you are using a template language like freemarker or velocity to create the response then you can return the ModelAndView.

    If you want to return a json/xml or some string as the response(ex: ajax requests) then you can use the first method. I think it should be public @ResponseBody String findOwner(@PathVariable String ownerId, Model model), you need to add a annotation called @ResponseBody to indicate that the returned value should be converted as the response text. Using @ResponseBody will enable you to use libraries like Jackson or JaxB to create json/xml responses respectively.

    These returned values will be converted using the messageConverters registered with AnnotationMethodHandlerAdapter.

    Ref: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

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