Restlet - 基于Spring的Restlet开发实例

本文介绍了如何使用Restlet框架结合Spring进行Web应用开发,重点讲解了web.xml的配置以及Resource代码的实现,包括StudentResource类中针对单个实例的 Retrieve、Update 和 Delete 操作。同时,还提到了BusinessObject的相关代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、相关说明
    version:文中示例使用的Spring版本为3.0.3,Restlet版本为2.1.0。
    entity:Student

二、创建Java Web工程,添加相关Jar。文中示例工程名为SpringRestlet。
    
    说明:动态代理的cglib-nodep.jar不可缺少。

三、web.xml配置

<servlet>
	<servlet-name>dispatcherServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:/applicationContext.xml</param-value>
	</init-param>
</servlet>
<!--Spring ApplicationContext load -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring,avoid leaking memory -->
<listener>
	<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<filter>
	<filter-name>encodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
	<init-param>
		<param-name>forceEncoding</param-name>
		<param-value>true</param-value>
	</init-param>
</filter>
<!-- restlet servlet -->
<servlet>
	<servlet-name>restlet</servlet-name>
	<servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class>
	<init-param>
		<param-name>org.restlet.application</param-name>
		<param-value>application</param-value>
	</init-param>
</servlet>
<servlet-mapping>
	<servlet-name>restlet</servlet-name>
	<url-pattern>/*</url-pattern>
</servlet-mapping>
四、Model实体类代码

@JsonSerialize(include = Inclusion.NON_NULL)
public class Student {
	private Integer id;
	private String name;
	private Integer sex;
	private Integer age;

	public Student() {
	}
	/** setter/getter **/
}
    说明:@JsonSerialize(include = Inclusion.NON_NULL)为JackSon的注解,作用是返回JSON格式的实体时不返回该实体类值为Null的Field,如: {"id" : 1,"name" : null,"sex" : 1,"age" : 20} 。


五、Resource代码
    1、StudentResource:示例中主要针对单个实例的Retrieve、Update和Delete。

@Controller
@Scope("prototype")
public class StudentResource extends ServerResource {
	private Integer id;
	@Autowired
	private StudentBO studentBO;

	public void setStudentBO(StudentBO studentBO) {
		this.studentBO = studentBO;
	}

	@Override
	protected void doInit() throws ResourceException {
		id = Integer.valueOf((String) getRequestAttributes().get("studentId"));
	}

	@Get("json")
	public Student findStudentById() {
		Student s = this.studentBO.getStudent(id);
		return s;
	}

	@Delete("json")
	public Integer deleteStudentById() {
		return this.studentBO.removeStudent(id);
	}

	@Put("json")
	public Integer updateStudent(Student student) {
		student.setId(id);
		return this.studentBO.saveOrUpdateStudent(student);
	}
}
    2、StudentListResource:示例中主要针对单个实例的Create和多个实例的Retrieve。

@Controller
@Scope("prototype")
public class StudentListResource extends ServerResource {
	@Autowired
	private StudentBO studentBO;

	@Post
	public Integer saveStudent(Student student) {
		return studentBO.saveOrUpdateStudent(student);
	}

	@Get("json")
	public List<Student> findStudentAll() {
		return studentBO.getStudentAll();
	}

	public void setStudentBO(StudentBO studentBO) {
		this.studentBO = studentBO;
	}
}
    说明:接受Spring管理的Bean,@Scope("prototype")的annotation必须要有,否则会出现正确调用指定方法的问题,用xml配置Bean时也必须要Attribute:scope。


六、BusinessObject代码

@Service
@Scope("prototype")
public class StudentBO {
	private static Map<Integer, Student> students = new HashMap<Integer, Student>();
	// next Id
	private static int nextId = 5;
	static {
		students.put(1, new Student(1, "Michael", 1, 18));
		students.put(2, new Student(2, "Anthony", 1, 22));
		students.put(3, new Student(3, "Isabella", 0, 19));
		students.put(4, new Student(4, "Aiden", 1, 20));
	}

	public Student getStudent(Integer id) {
		return students.get(id);
	}

	public List<Student> getStudentAll() {
		return new ArrayList<Student>(students.values());
	}

	public Integer saveOrUpdateStudent(Student student) {
		if (student.getId() == null) {
			student.setId(nextId++);
		}
		students.put(student.getId(), student);
		return student.getId();
	}

	public Integer removeStudent(Integer id) {
		students.remove(id);
		return id;
	}
}
七、Spring applictionContext.xml配置

<!-- 该application在web.xml中引用  -->
<bean name="application" class="org.restlet.Application">
	<property name="inboundRoot">
		<bean class="org.restlet.ext.spring.SpringRouter">
			<constructor-arg ref="application"/>
			<property name="attachments">
				<map>
					<entry key="/student/{studentId}">
						<bean class="org.restlet.ext.spring.SpringFinder">
							<lookup-method name="create" bean="studentResource"/>
						</bean>
					</entry>
					<entry key="/student">
						<bean class="org.restlet.ext.spring.SpringFinder">
							<lookup-method name="create" bean="studentsResource"/>
						</bean>
					</entry>
				</map>
			</property>
		</bean>
	</property>
</bean>
<!-- spring annotation -->
<context:component-scan base-package="com.xl.sr"/>
八、Client代码

public class StudentClient {
	public void student_get() {
		try {
			ClientResource client = new ClientResource("http://127.0.0.1:8080/SpringRestlet/student/1");
			Representation representation = client.get();
			System.out.println(representation.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void student_delete() {
		try {
			ClientResource client = new ClientResource("http://127.0.0.1:8080/SpringRestlet/student/1");
			Representation representation = client.delete();
			System.out.println(representation.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void student_put() {
		try {
			ClientResource client = new ClientResource("http://127.0.0.1:8080/SpringRestlet/student/1");
			Student student = new Student("Test_Put", 1, 18);
			Representation representation = client.put(student, MediaType.APPLICATION_JAVA_OBJECT);
			System.out.println(representation.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void student_post() {
		try {
			ClientResource client = new ClientResource("http://127.0.0.1:8080/SpringRestlet/student");
			Student student = new Student("Test_Post", 1, 18);
			Representation representation = client.post(student, MediaType.APPLICATION_JAVA_OBJECT);
			System.out.println(representation.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void student_findAll() {
		try {
			ClientResource client = new ClientResource("http://127.0.0.1:8080/SpringRestlet/student");
			Representation representation = client.get();
			System.out.println(representation.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		StudentClient client = new StudentClient();
		client.student_get();
	}
}
九、补充
    (1)、请求参数问题:客户端发送形如/student/{studentId}的URI请求时,可能是还需要携带其他parameter的,参数携带形式可如/student/{studentId}?name=John&sex=23;Server端获取参数时,针对在URI{}内的参数使用getRequest().getAttributes().get("studentId");方式获取,针对附加参数可以通过Form form = getRequest().getResourceRef().getQueryAsForm(); String name = form.getValues("name");方式获取。
    (2)、客户端工具:测试Server端时,如果不想写Client端code,可以是WizTools.org的RestClient-ui.jar的小工具,Post和Put请求时的对象可以以JSON格式添加到Http body中即可。
    (3)、相关资源:文中工程以上传至51cto下载中心,含代码和Jar包。链接地址:http://download.youkuaiyun.com/detail/u013379717/7127389
 
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值