rest入门实践之二:get/post/put/delete
rest入门实践之二:get/post/put/delete
第一步:同样创建相应webservice工程
第二步:代码:
package com.rest.hello; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; @Path("hello") public class Hello { @GET //查询 @Path("doGet") public String doGet(@QueryParam("id") String id) { System.out.println("doGet"); return id + "-doGet-" + "person"; } @POST //创建 @Path("doPost/{name}") public Object doPost(@PathParam("name") String name) { System.out.println("doPost"); return "doPost -" + "create "+ name + "person"; } @DELETE @Path("doDelete") public String doDelete(@QueryParam("id") String id) { System.out.println("doDelete"); return "doDelete - "+ "delete" + id + "person"; } @PUT @Path("doPut/{newName}") public String doPut(@PathParam("newName") String newName) { System.out.println("doPut"); return "doPut - " + "put" + "person name : " + newName; } }
第三:发布服务,启动tomcat
第四步:前台:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <script type="text/javascript"> var xmlhttp ; function createXMLHttp(){ if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.xmlhttp"); } }; function clickChange(action,method){ createXMLHttp(); if(action == "doGet"){ xmlhttp.open(method,"<%=basePath%>services/hello/"+action+"?id='mdj'",true); }else if(action == "doPost"){ xmlhttp.open(method,"<%=basePath%>services/hello/"+action+"/mdj",true); }else if(action == "doPut"){ xmlhttp.open(method,"<%=basePath%>services/hello/"+action+"/zyq",true); }else if(action == "doDelete"){ xmlhttp.open(method,"<%=basePath%>services/hello/"+action+"?id='zyq'",true); } xmlhttp.onreadystatechange = clickChangeCallBack; xmlhttp.send(null); } function clickChangeCallBack(){ if(xmlhttp.status == 200){ if(xmlhttp.readyState == 4){ alert(xmlhttp.responseText); } } } </script> </head> <body> <a onclick="clickChange('doGet','get')">get操作</a> <a onclick="clickChange('doPost','post')">post操作</a> <a onclick="clickChange('doPut','put')">put操作</a> <a onclick="clickChange('doDelete','delete')">delete操作</a> </body> </html>
第5步访问:http://localhost/RestPractice2/
第6步:结果如下:
TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST