当我尝试通过运行我的应用程序来测试它时,导航到 admin.html 页面。我在表格中填写了名字、姓氏和电子邮件的值。单击提交按钮时,会出现“列电子邮件不能为空”的错误。为简洁起见,我排除了 getter、setter、contructors 等代码。这是我的 admin.html 页面,其中有一个表单,用于将值发布到我的 api,其中的值用于创建员工对象
<form role="form" action="api/employees/create" method="post">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" class="form-control" id="firstName" placeholder="Enter first name">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" placeholder="Enter last name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-success btn-block">Create</button>
</form>
这是我在 EmployeeAPI.java 类中的 POST 方法,我在其中处理帖子并使用从表单传入的值创建一个对象,并尝试保留这个新对象
@POST
@Path("create")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Response createEmployee(@FormParam(value = "firstName") String firstName,
@FormParam(value = "lastName") String lastName,
@FormParam(value = "email") String email) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.getCurrentSession();
URI location;
try{
session.getTransaction().begin();
Employee newEmployee = new Employee();
newEmployee.setFirstName(firstName);
newEmployee.setLastName(lastName);
newEmployee.setEmail(email);
session.persist(newEmployee);
session.getTransaction().commit();
session.close();
location = new URI("http://localhost:8080/index.html");
return Response.temporaryRedirect(location).build();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
}
return null;
}
翻过高山走不出你
相关分类