gpt4 book ai didi

java - JSP 页面提交的输入路径 ID 总是被@ModelAttribute 解释为零,因此无法更新模型对象

转载 作者:行者123 更新时间:2023-11-29 08:35:24 25 4
gpt4 key购买 nike

我正在用 Spring 和 Hibernate 做一个 crud 操作项目。这是模型类。

员工.java

@Entity
@Table(name="employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String password;
private String gender;
private String city;

//getters and setters }

这是 EmployeeDaoImpl.java:

import com.anand.model.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
//implementation of Dao Layer
public class EmployeeDaoImpl implements EmployeeDao {
private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeDaoImpl.class);

private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public Session getSession() {
return getSessionFactory().openSession();
}

@Override
public void addEmployee(Employee employee) {
//Find out why the save is working but not persist
getSession().save(employee);
LOGGER.info("Employee " + employee + " added.");
}

@Override
public void updateEmployee(Employee employee) {
getSession().update(employee);
LOGGER.info("Employee " + employee + " updated.");
}

@Override
public Employee getEmployeeById(int id) {
Employee employee = (Employee) getSession().load(Employee.class, id);
LOGGER.info("Got Employee " + employee);
return employee;
}

@SuppressWarnings({"unchecked", "JpaQlInspection"})
@Override
public List<Employee> listEmployees() {
List<Employee> employeeList = getSession().createQuery("from Employee").list();
for (Employee employee : employeeList) {
LOGGER.info("Employee list " + employee);
}
return employeeList;
}

@Override
public void deleteEmployeeById(int id) {
Employee employee = (Employee) getSession().load(Employee.class, id);
if (employee != null) {
getSession().delete(employee);
}
LOGGER.info("deleted " + employee);
}
}

这是 EmployeeServiceImpl.java:

package com.anand.service;

import java.util.List;

import com.anand.dao.EmployeeDao;
import com.anand.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;

public EmployeeDao getEmployeeDao() {
return employeeDao;
}

public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}

@Override
@Transactional
public void addEmployee(Employee employee) {
getEmployeeDao().addEmployee(employee);
}

@Override
@Transactional
public void updateEmployee(Employee employee) {
getEmployeeDao().updateEmployee(employee);
}

@Override
@Transactional
public Employee getEmployeeById(int id) {
return getEmployeeDao().getEmployeeById(id);
}

@Override
@Transactional
public List<Employee> listEmployees() {
return getEmployeeDao().listEmployees();
}

@Override
@Transactional
public void deleteEmployeeById(int id) {
getEmployeeDao().deleteEmployeeById(id);
}
}

这是通过依赖注入(inject)注入(inject) employeeService 的 Controller 类方法。

@RequestMapping(value = {"/","/home"})
public ModelAndView homePage() {
return new ModelAndView("home");
}

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerEmployeePost(@ModelAttribute("employee") Employee employee, ModelMap modelMap) {
System.out.println(employee);
if (employee.getId() == 0) {
System.out.println("adding employee");
getEmployeeService().addEmployee(employee);
} else {
System.out.println("updating employee");
getEmployeeService().updateEmployee(employee);
}
return "redirect:/register";
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String registerEmployeeGet(@ModelAttribute("employee") Employee employee, ModelMap modelMap) {
modelMap.addAttribute("employeesList", getEmployeeService().listEmployees());
return "result";
}

@RequestMapping(value = "/edit/{id}")
public String editEmployee(@PathVariable("id") int id, Model model) {
Employee employee = getEmployeeService().getEmployeeById(id);
if (employee != null) {
model.addAttribute("employee", employee);
} else {
System.out.println("####employee by this id not found####");
}
return "home";
}

下面是 JSP 文件主页:

<c:url var="addAction" value="/register"/>
<form:form action="${addAction}" commandName="employee" method="post" cssClass="form-horizontal">
<label for="id" class="col-sm-2 control-label">ID: </label>
<form:input path="id" readonly="true" cssClass="form-control" disabled="true"/>
<label for="name" class="col-sm-2 control-label">Name: </label>
<form:input path="name" cssClass="form-control"/>
<label for="password" class="col-sm-2 control-label">Password: </label>
<form:input path="password" cssClass="form-control"/>
<label for="gender" class="col-sm-2 control-label">Gender: </label>
<form:input path="gender" cssClass="form-control"/>
<label for="city" class="col-sm-2 control-label">City: </label>
<form:input path="city" cssClass="form-control"/>
<input type="submit" value="Submit" class="btn btn-lg btn-primary"/>
</form:form>

最后,spring-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<mvc:annotation-driven/>
<context:annotation-config/>

<context:component-scan base-package="com.anand"/>

<bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/test"/>
<property name="username" value="postgres"/>
<property name="password" value="abc@1234"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.anand.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>

<bean class="com.anand.dao.EmployeeDaoImpl" id="employeeDao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

<bean class="com.anand.service.EmployeeServiceImpl" id="employeeService">
<property name="employeeDao" ref="employeeDao"/>
</bean>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

<!--For @Transactional-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

我有两个问题,首先,当我使用 persist() 而不是 save() 时,对象没有被保存。其次,当我尝试通过点击/edit/{id} url 并传递它的 id( Controller 通过它获取 employeeById)来更新模型时,表单由正确的条目填充,提交后,一个新条目是添加到具有新 ID 的员工列表中。我查看了日志,发现 /register 中的 id 始终为 0。我不明白为什么!请协助。

编辑:现在,id 正确,但即使在我收到成功的 LOGGER 消息后,对象仍未更新。

最佳答案

您将您的 ID 输入设置为 disabled="true",因此您可以看到 here , 如果 input 元素被禁用,它就不能接收用户输入并且它的值将不会与表单一起提交。

我建议您尝试包含一个隐藏 css 类而不是禁用属性。这应该可以解决您的问题,因为 id 将被发送到服务器端,它会更新元素而不是创建新元素。

希望对你有帮助

关于java - JSP 页面提交的输入路径 ID 总是被@ModelAttribute 解释为零,因此无法更新模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44453231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com