JSP页面提交的输入路径ID始终由@ModelAttribute解释为零,因此无法更新模型对象

时间:2017-06-09 08:43:41

标签: java spring hibernate jsp

我正在使用Spring和Hibernate进行crud操作项目。这是模型类。

Employee.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:

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:

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);
   }
}

这是控制器类方法,其中employeeService通过依赖注入注入。

@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(控制器通过其获取employeeById)来更新模型时,表单将被正确的条目填充并在之后提交时,新条目将添加到具有新ID的员工列表中。 我查看了日志,发现ID始终以/register为0,我无法弄明白为什么!请协助。

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

2 个答案:

答案 0 :(得分:2)

您已将您的ID输入设置为disabled="true",因此您可以看到here,如果输入元素被禁用,则无法接收用户输入,并且其值不会随着形式。

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

希望它有所帮助,

答案 1 :(得分:1)

事实证明,我打电话给sessionFactory().openSession()我从未关闭过。相反,我应该调用sessionFactory().getCurrentSession()来获取当前会话。

请看这里。 Difference between openSession() and getCurrentSession()