欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Restlet实战(六)-正确设计资源

程序员文章站 2022-07-03 21:04:13
...

在上篇文章的末尾,我提到资源的设计有一点问题,增加客户的功能应该放到Customers resource而不是Customer Resource。本文首先会改正这个问题。

 

首先把创建Customer的代码从Customer Resource移到Customers Resource,另外创建一个查询所有customer的get方法,代码如下:

 

public class CustomersResource extends Resource {
	private CustomerDAO customerDAO;
	
	@Override
	public void init(Context context, Request request, Response response) {
		super.init(context, request, response);
	}
	
	public CustomersResource(){
		getVariants().add(new Variant(MediaType.TEXT_PLAIN)); 
	}
	
	public CustomersResource(Context context, Request request, Response response) {
		super(context, request, response);
		
		getVariants().add(new Variant(MediaType.TEXT_PLAIN));
	}	
	

	@Override
	public Representation represent(Variant variant) {
		List<Customer> list = customerDAO.getAllCustomers();
		Representation representation = new StringRepresentation("", MediaType.TEXT_PLAIN);
		return representation;
	}
	
	@Override
	public boolean allowPut() {
		return true;
	}
	
	@Override
    public void storeRepresentation(Representation entity) throws ResourceException {
		Form form = new Form(entity);
		Customer customer = new Customer();
		customer.setName(form.getFirstValue("name"));
		customer.setAddress(form.getFirstValue("address"));
		customer.setRemarks("This is an example which receives request with put method and save data");
		
		customerDAO.saveCustomer(customer);
	}

	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}
	
}

 

 在Spring配置文件定义一个Customers resource bean,并修改URL映射部分:

	<bean id="restRoute" class="org.restlet.ext.spring.SpringRouter">
		<property name="attachments">
			<map>
				<entry key="/customers">
					<bean class="org.restlet.ext.spring.SpringFinder">
						<lookup-method name="createResource" bean="customersResource" />
					</bean>
				</entry>
				<entry key="/customers/{customerId}">
					<bean class="org.restlet.ext.spring.SpringFinder">
						<lookup-method name="createResource" bean="customerResource" />
					</bean>
				</entry>
			</map>
		</property>
	</bean>

 

	<bean id="customersResource" class="com.infosys.restlet.resource.CustomersResource" scope="prototype">
		<property name="customerDAO" ref="customerDAO" />
	</bean>

 

 在CustomerResourceTest中修改测试方法:

	public static void testStoreRepresentation(){
		Client client = new Client(Protocol.HTTP);
		Reference itemsUri = new Reference("http://localhost:8080/restlet/resources/customers");
		Form form = new Form();
		form.add("name", "Ajax");
		form.add("description", "test store presentation");
		Representation rep = form.getWebRepresentation();
		Response response = client.put(itemsUri, rep);
		assertTrue(response.getStatus().isSuccess());
	}