1、连接访问,即资源访问,只要给定参数就可以定位到需要的资源。
2、resteasy方式:@PUT,@GET,@DELETE,@POST
3、导入下载的resteasy的包如:resteasy-jaxrs-2.1.0.GA-all(可到resteasy官方下载,实例采用此版本)。
4、解压zip包,将lib包中的jar包copy到WEB-INF下的lib目录下,加入到编译路径。
5、编写Java资源定位代码:如下所示
@Path("/bookservice") public class BookService { @GET @Path("/books") public String getBooks() { System.out.println("get books"); return "get books"; } @GET @Path("/book/{isbn}") public String getBook(@PathParam("isbn") String id) { // search my database and get a string representation and return it System.out.println("get book"+id); return "get book"+id; } @PUT @Path("/book/{isbn}") public void addBook(@PathParam("isbn") String id, @QueryParam("name") String name) { System.out.println("put add book id:"+id+",name:"+name); } @DELETE @Path("/book/{id}") public void removeBook(@PathParam("id") String id ){ System.out.println("delete book where id is "+id); } }
6、配置web.xml
<context-param> <param-name>resteasy.resources</param-name> <param-value>com.rest.annotation.services.BookService</param-value> </context-param> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/services</param-value> </context-param> <listener> <listener-class> org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap </listener-class> </listener> <servlet> <servlet-name>Resteasy</servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> </servlet> <servlet-mapping> <servlet-name>Resteasy</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping>
7、部署到Tomcat下运行
直接访问路径,如:http://localhost:8080/demo/services/bookservice/books
此时,后台打印“get books”,浏览器页面显示“get books”。