我正在構建一個簡單的web應用程序,在java中使用rest
服務。我想更新Person
類型的對象列表。這是我到目前爲止的代碼:未使用java web服務更新的對象列表
public class Provider {
private final PersonList pl = new PersonList();
public Provider() {
final List<Person> personList = new ArrayList<Person>();
PersonList.add(new Person("1", "firstName1", "secondName1", "age1"));
PersonList.add(new Person("2", "firstName2", "secondName2", "age2"));
PersonList.add(new Person("3", "firstName3", "secondName3", "age3"));
PersonList.add(new Person("4", "firstName4", "secondName4", "age4"));
PersonList.add(new Person("5", "firstName5", "secondName5", "age5"));
this.pl.setPersonList(PersonList);
}
public PersonList getPersons() {
return this.pl;
}
public Person getPerson(final String id) {
return this.pl.getPerson(id);
}
public List<Person> updatePerson(final String id, final Person Person) {
return this.pl.updatePerson(id, Person);
}
}
public class PersonList {
private List<Person> personList = new ArrayList<Person>();
public List<Person> getPersonList() {
return this.personList;
}
public void setPersonList(List<Person> PersonList) {
this.personList = personList;
}
public int getPersonIndex(Person person) {
int index = -1;
for (int i = 0; i < this.PersonList.size(); i++) {
if (this.personList.get(i).getId().equals(person.getId()))
index = i;
}
return index;
}
public Person getPerson(String id)
{
Person person = new Person();
for (Person p : this.personList) {
if (p.getId().equals(id))
return p;
}
return person;
}
public List<Person> updatePerson(String id, Person p) {
final Person person = this.getPerson(id);
final int personIndex = this.getPersonIndex(person);
person.setFirstName(p.getFirstName());
person.setSecondName(p.getSecondName());
person.setAge(p.getAge());
this.personList.set(personIndex, person);
return this.personList;
}
}
而且在服務的請求:
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("/update/{id}")
public Response updatePerson(@PathParam("id") String id, Person p) {
Person p = this.provider.getPerson(id);
if (p.getd() != null) {
Person person = new Person(id, p.getFirstName(), f.getSecondName(), p.getAge());
return Response.ok(this.provider.updatePerson(id, person), MediaType.APPLICATION_JSON).build();
}
return Response.ok("Person doesn't exist", MediaType.APPLICATION_JSON).build();
}
我的問題是,當我做了更新,它返回與新值更新的列表中,但是當我再次爲列表getAll回到舊列表。
任何想法,我做錯了?