我试图使用此dropwizard example并构建它。我尝试将userName
列添加到Person.java中的people
表中,如下所示
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "fullName", nullable = false)
private String fullName;
@Column(name = "jobTitle", nullable = false)
private String jobTitle;
@Column(name = "userName", nullable = false)
private String userName;
public Person() {
}
public Person(String fullName, String jobTitle, String userName) {
this.fullName = fullName;
this.jobTitle = jobTitle;
this.userName = userName;
}
我添加了适当的getter和setter,以及equals方法。
但是我在此块中从输入流中读取实体时出错。
@Test
public void testPostPerson() throws Exception {
final Person person = new Person("Dr. IntegrationTest", "Chief Wizard", "Dr. Wizard");
final Person newPerson = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/people")
.request()
.post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE))
--> .readEntity(Person.class);
assertThat(newPerson.getId()).isNotNull();
assertThat(newPerson.getFullName()).isEqualTo(person.getFullName());
assertThat(newPerson.getJobTitle()).isEqualTo(person.getJobTitle());
assertThat(newPerson.getUserName()).isEqualTo(person.getUserName());
}
输入流错误由以下
引起 Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "code" (class com.example.helloworld.core.Person), not marked as ignorable (4 known properties: "fullName", "id", "userName", "jobTitle"])
类@JsonIgnoreProperties
注释会解决这个问题吗?这是安全的做法吗?
编辑:PersonResource.java
@Path("/people/{personId}")
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
private final PersonDAO peopleDAO;
public PersonResource(PersonDAO peopleDAO) {
this.peopleDAO = peopleDAO;
}
@GET
@UnitOfWork
public Person getPerson(@PathParam("personId") LongParam personId) {
return findSafely(personId.get());
}
@GET
@Path("/view_freemarker")
@UnitOfWork
@Produces(MediaType.TEXT_HTML)
public PersonView getPersonViewFreemarker(@PathParam("personId") LongParam personId) {
return new PersonView(PersonView.Template.FREEMARKER, findSafely(personId.get()));
}
@GET
@Path("/view_mustache")
@UnitOfWork
@Produces(MediaType.TEXT_HTML)
public PersonView getPersonViewMustache(@PathParam("personId") LongParam personId) {
return new PersonView(PersonView.Template.MUSTACHE, findSafely(personId.get()));
}
private Person findSafely(long personId) {
return peopleDAO.findById(personId).orElseThrow(() -> new NotFoundException("No such user."));
}
答案 0 :(得分:1)
我认为这是因为资源失败并引发了Web应用程序异常,代码实际上是http状态代码。
试试这样:
Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/people")
.request()
.post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE));
assertEquals(200, response.getStatus());
Person newPerson = response.readEntity(Person.class);
....
你也可以这样调试:
String responseString = response.readEntity(String.class);
哪会将你的反应主体抛弃。