如果用户在jsp中填写一个字段(同时使用springmvc和hibernate),我如何自动填写其他表单字段

How can i fill the other form fields automatically if user fill one field in jsp (while using spring mvc and hibernate)

本文关键字:字段 hibernate springmvc 表单 其他 何自动 jsp 用户 一个 如果      更新时间:2023-09-26

我使用的是springmvc和Hibernate。我有两个实体"项目"和员工,它们之间是双向的一对多映射。我能够将数据库中的现有员工添加到项目中。但我现在希望,当用户在jsp中填写员工的表单字段时,它会自动在下拉列表中显示所有员工的姓名,当选择一名员工时,它的其他字段也会自动设置。我怎么能那样做。我是springmvc和jquery的新手。

我的jsp将员工添加到项目

addEmployee.jsp

<form:form modelAttribute="employeeAttribute" method="POST" action="${Url}">
<table>
    <tr>
        <td>ProjectId:</td>
        <td><input type="text" value="${projectId}" />
    </tr>
    <tr>
        <td><form:label path="employeeId"></form:label></td>
        <td><form:input path="employeeId" type="hidden"/></td>
    </tr>
    <tr>
        <td><form:label path="employeeName">Employee Name:</form:label></td>
        <td><form:input path="employeeName"/></td>
    </tr>
    <tr>
        <td><form:label path="designation">designation:</form:label></td>
        <td><form:input path="designation"/></td>
    </tr>
    <tr>
        <td><form:label path="department">department:</form:label></td>
        <td><form:input path="department"/></td>
    </tr>
    <tr>
        <td><form:label path="password">password:</form:label></td>
        <td><form:input path="password"/></td>
    </tr>
    <tr>
</table>
<input type="submit" value="Save" />
</form:form>

表单填写后控制器中的相应操作

@RequestMapping(value="/add",method = RequestMethod.GET)
public String getAdd(@RequestParam("id")Integer projectId,Model model){
    Employee emp = new Employee();
    model.addAttribute("projectId",projectId);
    model.addAttribute("employeeAttribute",emp);
    return "addEmployee";
}
@RequestMapping(value="/add", method = RequestMethod.POST)
public String postAdd(@RequestParam("id")Integer projectId,@ModelAttribute("employeeAttribute")Employee employee) throws IOException{
    Employee emp = employeeService.getEmployeeByName(employee.getEmployeeName());
    if(emp==null){
        return "Error";
    }
    else{
        employeeService.add(projectId,emp);
        return "redirect:/project3/list";
    }
}

您可以使用javascript为包含user list的选择框编写onChange()的事件。使用ajax,您可以将用户ID发送到控制器

这样您就可以获取与用户相关联的属性,并将它们放在request中。ajax成功后,使用从数据库中获取的适当值填充字段。

这里和这里有一些很好的创业例子。

了解有关jquery ajax 的更多信息