我有一个Dog类,它有名字,年龄和身高。我想用这些值创建一个JSON对象。然后,我想创建方法CreateJsonServlet
,ModifyJsonServlet
和DeleteJsonServlet
。我需要生成一个JSON对象,然后传递它来创建,更新和删除JSON方法。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CreateServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
Dog dog = new Dog();
dog.setName(req.getParameter("name"));
dog.setHeight(Integer.parseInt(req.getParameter("height")));
dog.setAge(Integer.parseInt(req.getParameter("age")));
String name = dog.getName();
int age = dog.getAge();
int height = dog.getHeight();
resp.getWriter().write(dog.toString());
resp.getWriter().flush();
resp.getWriter().close();
}
}
这是狗类:
package com.Google;
public class Dog {
private String name;
private int age;
private int height;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
}