A Rails controller makes it very easy to support multiple content types.
respond_to do |format|
format.js { render :json => @obj }
format.xml
format
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;
}
}