我正在學習如何使用RESTful Web服務寫入的JSONObject,我真的不知道,如果我的做法是很好的或完全錯誤的,所以我承擔通過RESTful Web服務
我有一個項目結構,看起來就像這樣:
我想通過調用正確的URL,因此保存在字符串中Datum.Json
這裏是WebService的我的Java類:
package Rest;
@Path("/calendar")
public class CalendarTest {
public List<Date> dates;
@GET
@Path("/dates/get/")
@Produces(MediaType.APPLICATION_XML)
public List<Date> getUsers(){
return dates;
}
@PUT
@Path("/dates/put/{param1}+{param2}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void updateDate(@PathParam("param1") String city, @PathParam("param2") String date) throws IOException {
JSONObject obj = new JSONObject();
obj.put("City", city);
obj.put("Date", date);
try (FileWriter file = new FileWriter("/RestTest/Datum.json")) {
file.write(obj.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj);
}
}
}
我測試本地主機,它工作正常(我可以用我的本地打開form.html) 我web.xml
文件:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>Rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<security-constraint>
</security-constraint>
</web-app>
但是當我試圖在URL http://localhost:8080/RestTest/rest/calendar/dates/put/Berlin+20-12-2019
它說方法不允許。
任何人都可以向我解釋爲什麼?
所以我怎麼能訪問Put方法?謝謝! –
@TuấnPhạm一個選項是jQuery,還有AngularJS框架。如果您使用POST而不是PUT,則可以使用HTML表單來提交請求 – tima