转载请注明出处,谢谢 http://blog.csdn.net/exsuns
新建一个web工程:
新建类com.Hello.java ,内容如下
- @Path("hello")
- public class Hello {
- @GET
- @Path("doGet")
- public String doGet() {
- System.out.println("doGet");
- return "你好,doGet";
- }
- @POST
- @Path("doPost")
- public Object doPost() throws Exception {
- System.out.println("doPost");
- return "你好,doPost";
- }
- @DELETE
- @Path("doDelete")
- public String doDelete() {
- System.out.println("doDelete");
- return "你好,doDelete";
- }
- @PUT
- @Path("doPut")
- public String doPut() {
- System.out.println("doPut");
- return "你好,doPut";
- }
- @HEAD
- @Path("doHead")
- public String doHead() {
- System.out.println("doHead");
- return "你好,doHead";
- }
- }
- <!--web.xml里加入-->
- <servlet>
- <servlet-name>JAX-RS REST Servlet</servlet-name>
- <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>JAX-RS REST Servlet</servlet-name>
- <url-pattern>/services/*</url-pattern>
- </servlet-mapping>
最后部署到服务器,并启动
客户端:
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title></title>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <mce:script type="text/javascript"><!--
- var req;
- function creatReq(action,method) {
- var url = "http://localhost:8080/rest/services/hello/" + action;
- if (window.XMLHttpRequest) {
- req = new XMLHttpRequest();
- } else if (window.ActiveXObject) {
- req = new ActiveXObject("Microsoft.XMLHttp");
- }
- if (req) {
- req.open(method, url, true);
- req.onreadystatechange = callback;
- req.send(null);
- }
- }
- function callback() {
- alert("reponse头:" + req.getAllResponseHeaders());
- alert(req.responseText);
- }
- // --></mce:script>
- </head>
- <body>
- <a onclick="creatReq('doDelete','DELETE')">delete请求</a>
- <a onclick="creatReq('doPut','PUT')">put请求</a>
- <a onclick="creatReq('doGet','GET')">get请求</a>
- <a onclick="creatReq('doPost','POST')">post请求</a>
- <a onclick="creatReq('doHead','HEAD')">head请求</a>
- </body>
- </html>
打开客户端进行测试,就会在出现结果。
get/post/delete/put 都会出现结果
不过head有可能不会出现
关于head请求,sun有一句话
By default the JAX-RS runtime will automatically support the methods HEAD, if not explicitly implemented. For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set).
默认请况下 jax-rs运行时会自动支持head和options请求,如果没有明确实现,head运行时会调用get,同时会忽略response写出