25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 12 ■ Exposing a REST API<br />

Listing 12-3 shows the DocumentRespository class, which implements the DocumentDAO interface. Before you<br />

had only three defined methods in the DocumentDAO interface, and its implementation had very specific properties<br />

to hold each SQL statement. Now you modified it by adding the removeById method, adding a map that will now hold<br />

the SQL statements. Also, you refined the save method because now you are taking care of some null values.<br />

Let’s see how the DocumentController will expose those resources over HTTP, as described in Table 12-2. Listing<br />

12-4 shows your DocumentController class.<br />

Listing 12-4. DocumentController.java<br />

package com.apress.isf.spring.web;<br />

import java.util.List;<br />

import org.springframework.beans.factory.annotation.Autowired;<br />

import org.springframework.stereotype.Controller;<br />

import org.springframework.web.bind.annotation.PathVariable;<br />

import org.springframework.web.bind.annotation.RequestBody;<br />

import org.springframework.web.bind.annotation.RequestMapping;<br />

import org.springframework.web.bind.annotation.RequestMethod;<br />

import org.springframework.web.bind.annotation.ResponseBody;<br />

import com.apress.isf.java.model.Document;<br />

import com.apress.isf.java.service.DocumentService;<br />

@Controller<br />

@RequestMapping("/documents")<br />

public class DocumentController {<br />

174<br />

@Autowired<br />

DocumentService documentFacade;<br />

@RequestMapping(method=RequestMethod.GET)<br />

public @ResponseBody List getDocuments(){<br />

return documentFacade.getAllDocuments();<br />

}<br />

@RequestMapping(value="/{id}",method=RequestMethod.GET)<br />

public @ResponseBody Document findDocument(@PathVariable String id){<br />

return documentFacade.findDocumentById(id);<br />

}<br />

@RequestMapping(method=RequestMethod.POST)<br />

public @ResponseBody Document addDocument(@RequestBody Document document){<br />

String id = document.getDocumentId();<br />

return documentFacade.saveDocument(id,document);<br />

}<br />

@RequestMapping(value="/{id}",method=RequestMethod.PUT)<br />

public @ResponseBody Document updateDocument(<br />

@RequestBody Document document, @PathVariable String id){<br />

return documentFacade.saveDocument(id,document);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!