Vasanth
Vasanth

Reputation: 494

Spring REST to handle all Content-Type message

Can you please suggest me how to write the Spring REST webservice which is handle the different kind of "ContentType" messages?

1.application/json 
2.application/xml 
3.application/x-www-form-urlencoded

with the help of org.springframework.web.servlet.view.ContentNegotiatingViewResolver API ?

Regards Vasanth D

Upvotes: 1

Views: 1530

Answers (1)

jax
jax

Reputation: 38623

Say you have a Pizza object, you might do it like this.

@Controller
@RequestMapping(value = "pizzas")
public class PizzaController {

    private final PizzaService service;

    @Autowired
    public PizzaController(final PizzaService pizzaService) {
        this.service = pizzaService;
    }


    @RequestMapping(
            method = RequestMethod.POST,
            consumes = {
                MediaType.APPLICATION_JSON_VALUE,
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_FORM_URLENCODED_VALUE
            }
    )
    @ResponseBody
    @ResponseStatus(value = HttpStatus.CREATED)
    public Pizza create(@RequestBody Pizza pizza) {
        return service.create(pizza); 
    }

    @RequestMapping(
            value = "{id}",
            method = RequestMethod.PUT,
            consumes = {
                MediaType.APPLICATION_JSON_VALUE,
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_FORM_URLENCODED_VALUE
            }
    )
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public Pizza update(@RequestBody Pizza pizza) {
        return service.update(pizza); 
    }

    @RequestMapping(
            value = "{id}",
            method = RequestMethod.GET,
            consumes = {
                MediaType.APPLICATION_JSON_VALUE,
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_FORM_URLENCODED_VALUE
            }
    )
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public Pizza read(@RequestParam("id") Long id) {
        return service.get(id);
    }

    @RequestMapping(
            value = "{id}",
            method = RequestMethod.DELETE,
            consumes = {
                MediaType.APPLICATION_JSON_VALUE,
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_FORM_URLENCODED_VALUE
            }
    )
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public Pizza delete(@RequestParam("id") Long id) {
        return service.delete(id);
    }
}

If you are using Spring 4 you can remove all the @ResponseBody annotations and replace @Controller with @RestController.

Upvotes: 1

Related Questions