Supporting multiple content types in a Spring-MVC controller

前端 未结 2 1468
栀梦
栀梦 2020-12-16 03:53

A Rails controller makes it very easy to support multiple content types.

respond_to do |format|
  format.js { render :json => @obj }
  format.xml
  format         


        
2条回答
  •  春和景丽
    2020-12-16 04:39

    In Spring 3, you want to use the org.springframework.web.servlet.view.ContentNegotiatingViewResolver.

    It takes a list of media type and ViewResolvers. From the Spring docs:

    
      
        
          
          
          
        
      
      
        
          
            
            
          
        
      
      
        
          
        
      
    
    
    

    The Controller:

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class BlogsController {
    
        @RequestMapping("/blogs")
        public String index(ModelMap model) {
            model.addAttribute("blog", new Blog("foobar"));
            return "blogs/index";
        }    
    }
    

    You'll also need to include the Jackson JSON jars.

提交回复
热议问题