我正在学习如何使用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