0

I have developed a Spring MVC - Hibernate application as told here.

Now I am trying to modify this code to create a REST application as told here.

I have added Jackson library to the classpath and added @XmlRootElement.

@XmlRootElement(name = "persons")
public class Person implements Serializable {

But if I do a application/json request then I still get the html code back.

What I am doing wrong / forgot to do?

My controller:

    @RequestMapping(value = "/persons", method = RequestMethod.GET)
    @ResponseBody
    public String getPersons(Model model) {

        logger.info("Received request to show all persons");

        // Retrieve all persons by delegating the call to PersonService
        List<Person> persons = personService.getAll();
        model.addAttribute("persons", persons);

        return "personspage";
    }

Changed the Controller, but get an error: t

ype Status report

message /Buddies/WEB-INF/jsp/main/persons/1.jsp

description The requested resource (/Buddies/WEB-INF/jsp/main/persons/1.jsp) is not available.
  • Show us your controller method. Are you returning `Person` object from your method and have `@ResponseBody` annotation over controller method as well? – Tomasz Nurkiewicz Aug 27 '12 at 19:20

2 Answers2

2

Your controller should look like this:

@RequestMapping(value = "/persons/{id}", method = RequestMethod.GET)
@ResponseBody
public Person getPerson(@PathVariable int id) {
    Person person = personService.getPersonById(id);
    return person;
}

If you want to return a list of Person objects, you need an extra wrapper object, see: Using JAXB to unmarshal/marshal a List<String>.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • I have added a @pathVariable, but get an error, that type Status report message /Buddies/WEB-INF/jsp/main/persons/1.jsp description The requested resource (/Buddies/WEB-INF/jsp/main/persons/1.jsp) is not available. –  Aug 27 '12 at 19:51
  • @Bob: in `web.xml`, which paths are mapped to `DispatcherServlet`? – Tomasz Nurkiewicz Aug 27 '12 at 19:57
  • One more question: application/xml request is success and I see all my data, but application/json fails. What can be the problem? –  Aug 27 '12 at 19:57
  • @Bob: should transparently work for both of them, providing you are sending `application/json` (?) and `jackson.jar` is on the CLASSPATH. – Tomasz Nurkiewicz Aug 27 '12 at 19:59
0

You are probably missing AnnotationMethodHandlerAdapter and messageConverter in your spring configuration.

ltfishie
  • 2,917
  • 6
  • 41
  • 68