Restlet2.0学习——简单WebApp多Application与表单提交
之前我们提到过简单的WebApp实现,使用的是一个application,而这一次,就是在web.xml中放入多个application。其实这里的application就是一个servlet,只是这些servlet下调用的各种resource是线程安全的。有兴趣的同学可以对resource进行多线程访问测试。
这次我们项目名仍然使用RestLetServlet。其他的jar也同webapp,保持不变。
多application的web.xml配置如下:
<servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class> <init-param> <param-name>org.restlet.application</param-name> <param-value>com.restlet.application.HelloApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping> <servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class> <init-param> <param-name>org.restlet.application</param-name> <param-value>com.restlet.application.UserApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/users/*</url-pattern> </servlet-mapping>
public class HelloApplication extends Application {@Overridepublic Restlet createInboundRoot() {Router router = new Router(getContext());router.attach("/getHello", HelloResource.class);return router; }}
public class UserApplication extends Application {@Overridepublic Restlet createInboundRoot() {Router router = new Router(getContext());router.attach("", UsersResource.class);router.attach("/{userId}", UserResource.class);return router; }}
public class UserResource extends ServerResource {private Logger logger = Logger.getLogger(this.getClass());@Getpublic String getUser() {String userId = (String)getRequest().getAttributes().get("userId");logger.debug("this is getUser");return "this is getUser"+userId;}}
public class UsersResource extends ServerResource {private Logger logger = Logger.getLogger(this.getClass());@Postpublic Representation addUser(Representation entity) {Form form = new Form(entity);String username = form.getFirstValue("username");String password = form.getFirstValue("password");logger.debug("username="+username+"\t password="+password);return null;}@Getpublic String getUsers() {logger.debug("this is getUsers");return "this is getUsers";}}
<?xml version="1.0" encoding="UTF-8" ?><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><base href="<%=basePath%>"/><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>user form</title></head><body><form action="users" method="post">用户名:<input type="text" name="username" /><br/>密码:<input type="password" name="password" /><br/><input type="submit" value="提交" /></form></body></html>