REST 之 Spring 4 RESTful service

请参考阅读 http://www.ibm.com/developerworks/library/wa-restful/java

the article is good, but not refer to right links for converter download, append below:web

  1. Jason format converterspring

    Download jacson-all-1.9.11.jar json

    http://www.java2s.com/Code/Jar/j/Downloadjacksonall1911jar.htm安全

  2. XML format converter, 这个不用下载,已经包含在spring framework中.restful

    详细见spring-oxm-4.0.5.RELEASE.jar, 不过这个须要注册bean才能行, 其它两个须要注册的是BufferImageHttpMessageConverter, FormHttpMessageConverter, 其余的都是包含jar就能够自动注册,并使用了.网络

  3. atom format converter  rome-1.0.jarsession

    http://www.java2s.com/Code/Jar/r/Downloadrome10jar.htm
    mvc

  4. Message converter for XML, 其余的自动注册,不用写. 固然写也能够,看着明白点。app

    下面仅仅注册了jaxb库,其余的包含在lib就能够了。

        <bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
		<constructor-arg ref="jaxbMarshaller" />
	    <property name="supportedMediaTypes" value="application/xml"/>
	</bean>
	
	<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
		<property name="packagesToScan">
	    <list>
	        <value>com.company.product.entity.*</value>
	    </list>
		</property>
	</bean>

  • Controller and requestmapping,实现了CRUD (Post,Get,Put,Delete).

  • 能够实现Representational state transfer,标准工业格式json and XML

  • 还实现了mvc内建支持modelAndView.

/**
 * 
 */
package com.company.product.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.company.product.entity.Book;
import com.company.product.entity.BookList;
import com.company.product.interfaces.LibraryI;
import com.company.product.jms.MsgProducer;

/**
 * @author zhuji06
 *
 */
@Controller
public class LibraryController {
	

	private LibraryI library;
	public void setSender(MsgProducer sender){
		this.sender = sender;
	}
	
	private MsgProducer sender;
	public void setLibrary(LibraryI library){
		this.library = library;
	}
	
	//headers="Accept=application/json, application/xml"
	
	@RequestMapping(method=RequestMethod.GET,value="/")
	public @ResponseBody String welcome(){
		sender.send("Welcome,Spring REST with ActiveMQ JMS.");
		
		return "Welcome,Spring REST.";
	}
	
	@RequestMapping(method=RequestMethod.GET,value="/books/{bookId}")
	public @ResponseBody Book getBook(@PathVariable("bookId") Integer bookId){
		return library.getBook(bookId);
	}
	
	@RequestMapping(method=RequestMethod.GET,value="/books")
	public @ResponseBody BookList getBooks(){
		return new BookList(library.getBooks());
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/books")
	public @ResponseBody Book createBook(@RequestBody Book book, HttpServletResponse response){
		
		Integer id = library.addBook(book);
		response.setHeader("Location","/Books/"+id);
		return library.getBook(id);
	}
	
	@RequestMapping(method=RequestMethod.PUT,value="/books")
	public @ResponseBody Book updateBook(@RequestBody Book book, HttpServletResponse response){
		
		Integer id = library.putBook(book);
		response.setHeader("Location","/Books/"+id);
		return library.getBook(id);
	}
	
	@RequestMapping(method=RequestMethod.DELETE,value="/books/{bookId}")
	public @ResponseBody void deleteBook(@PathVariable("bookId") Integer bookId){
		library.deleteBook(bookId);
	}
}

  • Entity and its Wrappers (能够转化xml and Json)

/**
 * 
 */
package com.company.product.entity;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author zhuji06
 *
 */
@XmlRootElement
public class Book {
	/**
	 * 
	 */
	
	private Integer id;
	private String name;
	private String description;
	
	public Book(){
		super();
	}
	public Book(Integer id, String name,String description){
		this.setId(id);
		this.setName(name);
		this.setDescription(description);
	}

	@XmlElement(nillable=false,required=true)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@XmlElement
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}
	
	@XmlElement(name = "desc")
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	@Override
    public String toString() {
        String s = " id :" + id + "\n Name :" + name + "\n description :" + description;
        return s;
    }
}

    下面的BookList纯粹是为了妥协jaxb对List等的支持很差,因此对其进行了包装,这也能够更好的输出list.

package com.company.product.entity;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="books")
public class BookList {
	private int count;
	private List<Book> books;

	public BookList() {}
	
	public BookList(List<Book> books) {
		this.books = books;
		this.count = books.size();
	}

	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	
	@XmlElement(name="book")
	public List<Book> getBooks() {
		return books;
	}
	public void setBooks(List<Book> books) {
		this.books = books;
	}
}

  • 如何进行REST 测试呢?

目前商业的比较全的是ibm 的soapUI, 有15天适用版,还有开源的RestClient, java写的简单的测试工具,能够去sourceforge上去下载.其实有另外一个强大网络检测工具,能够试用,它就是Fiddler,本身百度去。

在右侧有Composer页面,能够指定Action, URL, Header, and Body等。

这里也须要提醒,若是测试Get方法,须要指定Header里:Accept: application/xml  或者Accept:application/json, 它们会被AnnotationMethodHandlerAdapter使用,先判断URL,后判断Accept, 而后检查produces,来匹配返回的类型。

因此能够两种方式测试

Get http://localhost:8080/SpringREST/service/books/1.xml

Get http://localhost:8080/SpringREST/service/books/1.json

或者 Get http://localhost:8080/SpringREST/service/books/1

Accept: application/xml  或者Accept:application/json


另外在POST类型,须要指定Content-Type:application/json,而后填充Body内容为json格式,如

{"id":0,"name":"Thinking in Java","description":"this is a base book."}


总结,REST service从风格角度是比较好理解和实现的,可是若是要实现一个彻底的,安全的服务,仍是须要ROD的思惟,而且实现authentication without session,这个下一个文章祥解.


Nice week nice day.

相关文章
相关标签/搜索