Spring MVC Controllers Return Type

后端 未结 6 1939
别跟我提以往
别跟我提以往 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: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 getStudent(@RequestParam("studentId") String id){
            List 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:

     
    

    And the Serializer itself:

    
     
    
      
        
      
    
    
    

    Hope it helps.

提交回复
热议问题