Supporting multiple content types in a Spring-MVC controller

前端 未结 2 1459
栀梦
栀梦 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:29

    Here goes the working example controller, that renders JSON and HTML both based on request Header "Content-Type".

    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.util.MimeTypeUtils;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestHeader;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class PersonService {
        @RequestMapping(value = "/persons/{userId}", method = RequestMethod.GET)
        public ResponseEntity getPersonByName(@RequestHeader("Content-Type") String contentMediaType,
                @PathVariable("userId") String userId,@RequestParam("anyParam") boolean isAscending) throws IOException {
    
            Person person = getPersonById(userId);
            if (isJSON(contentMediaType)) {
                return new ResponseEntity(person, HttpStatus.OK);
            }
    
            return new ResponseEntity("Your HTML Goes Here", HttpStatus.OK);
            //Note: Above you could use any HTML builder framework, like HandleBar/Moustache/JSP/Plain HTML Template etc.
        }
    
    
        private static final boolean isJSON(String contentMediaType) {
            if ("application/json".equalsIgnoreCase(contentMediaType)) {
                return true;
            }
    
            return false;
        }
    
    }
    

提交回复
热议问题