我会试一试。
这是我在Configuration
课堂上的内容:
@Bean(name = "viewResolver")
public ContentNegotiatingViewResolver viewResolver() {
final ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
contentNegotiatingViewResolver.setOrder(1);
contentNegotiatingViewResolver.setFavorPathExtension(true);
contentNegotiatingViewResolver.setFavorParameter(true);
contentNegotiatingViewResolver.setIgnoreAcceptHeader(false);
final Map<String, String> mediaTypes = new HashMap<String, String>();
mediaTypes.put("json", "application/x-json");
mediaTypes.put("json", "text/json");
mediaTypes.put("json", "text/x-json");
mediaTypes.put("json", "application/json");
mediaTypes.put("xml", "text/xml");
mediaTypes.put("xml", "application/xml");
contentNegotiatingViewResolver.setMediaTypes(mediaTypes);
final List<View> defaultViews = new ArrayList<View>();
defaultViews.add(jsonView());
defaultViews.add(xmlView());
contentNegotiatingViewResolver.setDefaultViews(defaultViews);
return contentNegotiatingViewResolver;
}
@Bean(name = "xStreamMarshaller")
public XStreamMarshaller xStreamMarshaller() {
return new XStreamMarshaller();
}
@Bean(name = "xmlView")
public MarshallingView xmlView() {
final MarshallingView marshallingView = new MarshallingView(xStreamMarshaller());
marshallingView.setContentType("application/xml");
return marshallingView;
}
@Bean(name = "jsonView")
public MappingJacksonJsonView jsonView() {
return new MappingJacksonJsonView();
}
这就是Controller
.
@RequestMapping(value = { "/pets" }, method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("pets", petRepository.findAll());
return "pets/list";
}
@RequestMapping(value = { "/pets" }, method = RequestMethod.POST)
public String create(@Valid @RequestBody Pet pet, Model model) {
petRepository.save(pet);
return "redirect:pets/read/" + pet.getId();
}
@RequestMapping(value = { "/pets/{petId}" }, method = RequestMethod.GET)
public String read(@PathVariable Integer petId, Model model) {
model.addAttribute("pet", petRepository.findOne(petId));
return "pets/read";
}
@RequestMapping(value = { "/pets" }, method = RequestMethod.PUT)
public String update(@Valid @RequestBody Pet pet, Model model) {
petRepository.save(pet);
return "redirect:pets/read/" + pet.getId();
}
@RequestMapping(value = { "/pets/{orderId}" }, method = RequestMethod.DELETE)
public void delete(@PathVariable Integer petId, Model model) {
petRepository.delete(petId);
}
根据我的经验,您可以将 HTML 表单或 JSON 对象作为@RequestBody
. 试试看。