【问题标题】:values are not updating in table I get Field error in object 'employee' on field 'id': rejected value [{id} (id=1)];表中的值未更新我在字段 'id' 上的对象 'employee' 中出现字段错误:拒绝值 [{id} (id=1)];
【发布时间】:2021-09-21 09:27:01
【问题描述】:

在使用 Jsp 的 spring boot 中,我创建了一个员工管理系统,我可以在其中添加、更新和删除员工。但问题是当我尝试更新表中的值时,我得到 [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Long' for property 'id';嵌套异常是 java.lang.NumberFormatException: For input string: "{id}(id=1)"].

我确实添加和删除了员工价值观,但我无法更新员工价值观。我尝试了很多方法,但对我没有任何作用。所以,请给我一个解决这个问题的方法。

1.Employee实体类

package net.javaguides.ems.entity;

//import java.sql.Date;

import java.util.Date;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;



@Entity
@Table(name = "employee")
public class Employee 
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; //Here, The values of this id field will be automatically generated by database on browser.
    
    //@Column(name = "first_name", nullable = false)
    //@Size(min=3, max=50)
    //@NotNull
    //@NotEmpty(message = "Field can't be empty!")
    private String firstName;
    
    //@Column(name = "last_name")
    //@NotNull
    //@NotEmpty
    //@Size(min=2, max=50)
    private String lastName;
    
    //@Column(name = "email")
    //@NotNull
    //@NotBlank
    //@Email
    private String email;
    
    
    //@Column(name = "gender")
    //@NotBlank
    private String gender;
    
    //@Column(name = "marriage")
    //@NotNull
    //@NotBlank
    private String marriage;
    
    //@Column(name = "birthday")
    //@DateTimeFormat(pattern = "dd-mm-yyyy")
    //@NotNull(message = "Please give a date of birth.")
    //@Temporal(TemporalType.TIMESTAMP)
    //private Date birthday;
    private String birthday;
    
    //@Column(name = "workat")
    //@NotNull
    //@NotBlank
    private String workat;
    
    //@NotBlank
    private String department;


public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}


public String getGender() {
    return gender;
}
public void setGender(String gender) {
    this.gender = gender;
}
public String getMarriage() {
    return marriage;
}
public void setMarriage(String marriage) {
    this.marriage = marriage;
}
/*
public Date getBirthday() {
    return birthday;
}
public void setBirthday(Date birthday) {
    this.birthday = birthday;
}
*/

public String getWorkat() {
    return workat;
}
public String getBirthday() {
    return birthday;
}
public void setBirthday(String birthday) {
    this.birthday = birthday;
}
public void setWorkat(String workat) {
    this.workat = workat;
}
public String getDepartment() {
    return department;
}
public void setDepartment(String department) {
    this.department = department;
}

}

2.Employee控制器类

package net.javaguides.ems.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import net.javaguides.ems.entity.Employee;

@Controller // Controller Layer holds all Spring MVC Controllers
public class EmployeeController {
    
    @Autowired
    EmployeeDao employeeDao;
    

     @RequestMapping("/employees")    
        public String listEmployees(Model m){    
            List<Employee> list=employeeDao.getAllEmployees();   
            System.out.println("Size" + list.size());
            m.addAttribute("list",list);
            m.addAttribute("employees",list);
            
            return "employees";    
        }    
    
    
    
     @RequestMapping("/employees/new")    
        public String createEmployeeForm(Model m){    
            m.addAttribute("employee", new Employee());  
            return "create_employee";   
        }    
    
    
    
    @RequestMapping(value="/employees",method = RequestMethod.POST)    
    public String saveEmployee(@ModelAttribute("employee")  Employee employee){    
        employeeDao.saveEmployee(employee);    
        return "redirect:/employees";    
    }    
    
    
    
    @RequestMapping(value="/employees/edit/{id}")    
    public String editEmployeeForm(@PathVariable Long id, Model m){    
        Employee employee = employeeDao.getEmployeeById(id);   
       // m.addAttribute("command",employee);  
        m.addAttribute("employee",employee);  
        
        return "edit_employee";    
    }    
    
    
    
    @RequestMapping(value="/employees/{id}",method = RequestMethod.POST)    
    public String updateEmployee(@ModelAttribute("employee") Employee employee){    
        employeeDao.updateEmployee(employee);    
        return "redirect:/employees";    
    }    
    
    
    
    @RequestMapping(value="/employees/{id}",method = RequestMethod.GET)    
    public String deleteEmployee(@PathVariable Long id){    
        employeeDao.deleteEmployeeById(id);    
        return "redirect:/employees";    
    }     
    
    
}

3.Employee DAO 类

package net.javaguides.ems.controller;

import java.util.Date;
import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import net.javaguides.ems.entity.Employee;

@Service()
public class EmployeeDao 
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    

    /*
     * public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate =
     * jdbcTemplate; }
     */
     

    public List<Employee> getAllEmployees()
    {
        //List<Map<String,String>> data  = new ArrayList<Map<String, String>>();
        
        
        return jdbcTemplate.query("select * from employee", new RowMapper<Employee>()
                {
                    public Employee mapRow(ResultSet rs, int row) throws SQLException
                    {
                        Employee emp = new Employee();
                
                
                          emp.setId(rs.getLong("id"));
                          emp.setFirstName(rs.getString("first_name"));
                          emp.setLastName(rs.getString("last_name"));
                          emp.setEmail(rs.getString("email")); 
                          emp.setGender(rs.getString("gender"));
                          emp.setMarriage(rs.getString("marriage"));
                          emp.setBirthday(rs.getDate("birthday").toString());
                          emp.setWorkat(rs.getString("workat"));
                          emp.setDepartment(rs.getString("department"));
                  
                  
                  return emp;
                 
                    }
                });
    }
    
    public long saveEmployee(Employee p)
    {
        
        /*
         * SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy"); String dob =
         * format1.format(p.getBirthday()).toString();
         * System.out.println("DOB ::"+p.getBirthday()+"::"+dob);
         * 
         */
                //firstName,lastName,email,gender,marriage,birthday,workat,department
                  String sql="insert into employee(first_name,last_name,email,gender,marriage,birthday,workat,department) values "
                  +
                  "('"+p.getFirstName()+"','"+p.getLastName()+"','"+p.getEmail()+"','"+p.getGender()
                  +"','"+p.getMarriage()+"','"+p.getBirthday()+"','"+p.getWorkat()+"','"+p.
                  getDepartment()+"')"; 
                  //p.getBirthday()
                  System.out.println("SQL ::"+sql);
                  
                  return jdbcTemplate.update(sql);
                 
                
    }
    
    //@Deprecated
    public Employee getEmployeeById(Long id)
    {
        String sql="select * from employee where id=?";  
        
        //return jdbcTemplate.queryForObject("select * from employee where id=?",new BeanPropertyRowMapper<Employee>(Employee.class), new Object[]{id});    
        
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Employee>(Employee.class),new Object[]{id});    
    }
    
    public long updateEmployee(Employee p)
    {
        String sql="update employee set firstName='"+p.getFirstName()+"', lastName="+p.getLastName()+",email="+p.getEmail()+",gender="+p.getGender()+",marriage="+p.getMarriage()+",birthday="+p.getBirthday()+",workat="+p.getWorkat()+",department='"+p.getDepartment()+"' where id="+p.getId()+"";    
        return jdbcTemplate.update(sql); 
    }
    
    public long deleteEmployeeById(Long id)
    {
        String sql="delete from employee where id="+id+"";    
        return jdbcTemplate.update(sql);   
    }
    
}

4.错误

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Jul 12 12:46:18 IST 2021
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='employee'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'employee' on field 'id': rejected value [{id} (id=1)]; codes [typeMismatch.employee.id,typeMismatch.id,typeMismatch.java.lang.Long,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employee.id,id]; arguments []; default message [id]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Long' for property 'id'; nested exception is java.lang.NumberFormatException: For input string: "{id}(id=1)"]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:172)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:170)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:831)

5.Employees.jsp

<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" 
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
      crossorigin="anonymous">
<style type="text/css">
    /* a:active {
        color: white;
    }
    a:visited {
        color: blue;
    } */
    a {
        display: blue;
    }
</style>      
      

</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <!-- Brand -->
  <a class="navbar-brand" href="#">Employee Management System --></a>

  <!-- Toggler/collapsibe Button -->
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>

  <!-- Navbar links -->
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="changeable" href = "/employees">Employee Management</a> 
      </li>
    </ul>
  </div>
  </nav>
  



  
 <div class ="container">
        <div class = "row">
            <h1> List Employees </h1>
        </div>
        
        <div class = "row" >
            <div class = "col-lg-3">
                <a href = "/employees/new" class = "btn btn-primary btn-sm mb-3"> Add Employee</a>
            </div>
        </div>
    <div>   
        <table class = "table table-striped table-bordered" >
            <thead class = "table-dark">
                <tr>
                    <th> Employee ID </th>
                    <th> Employee First Name </th> 
                    <th> Employee Last Name </th>
                    <th> Employee Email </th>
                    <th> Employee Gender </th>
                    <th> Employee Marriage </th>
                    <th> Employee Birthday </th>
                    <th> Employee Work At </th>
                    <th> Employee Department </th>
                    <th> Actions </th>
                </tr>
            </thead>
            
            <tbody>
            
            
                <c:forEach var="employee" items="${employees}" >
                <tr>
                    <td> ${employee.id} </td>
                    <td> ${employee.firstName} </td> 
                    <td> ${employee.lastName} </td>
                    <td> ${employee.email} </td>
                    <td> ${employee.gender} </td>
                    <td> ${employee.marriage} </td>
                    <td> ${employee.birthday} </td>
                    <td> ${employee.workat} </td>
                    <td> ${employee.department} </td>
                    <td>
                        <a href = "/employees/edit/${employee.id}"
                        class = "btn btn-primary">Update</a>
                        
                        <a href = "/employees/${employee.id}"
                        class = "btn btn-danger">Delete</a>
                    </td>
                    <%-- <td>
                        <a href = "/employees/edit/{id} (id=${employee.id})"
                        class = "btn btn-primary">Update</a>
                        
                        <a href = "@{/employees/{id} (id=${employee.id})}"
                        class = "btn btn-danger">Delete</a>
                    </td> --%>
                </tr>
                </c:forEach>
                
                    
            </tbody> 
        </table>
    </div>  
</div>

</body>
</html>

6.create_employee.jsp

<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Employee Management System</title>
<link rel="stylesheet" 
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
      crossorigin="anonymous">

<style type="text/css">
    span {
        color: red;
        font-style: italic;
    }
    option {
  margin: 0.5em;
}
</style>

<style type="text/css">
    /* a:active {
        color: white;
    }
    a:visited {
        color: blue;
    } */
    a {
        display: blue;
    }
</style>

<style type="text/css">
    label {
        display: inline-block;
        width: 200px;
        margin: 5px;
        text-align: left;
    }
    
    button {
        padding: 10px;
        margin: 10px;
    }
</style>

</head>
<body>

<br>
<br>

    <div class = "container">
        <div class = "row">
            <div class = "col-lg-6 col-md-6 col-sm-6 container justify-content-center-center card">
                <h1 class = "text-center"> Create New Employee </h1>
                <div class = "card-body" >
                    <form:form action="/employees" method="POST" modelAttribute="employee">
                        
                        <form:label path="firstName">Employee First Name</form:label>
                        <form:input path="firstName" type="text" field="*{firstName}" placeholder = "Enter Employee First Name"/> <br>
                    
                        <form:label path="lastName">Employee Last Name</form:label>
                        <form:input path="lastName" type="text" field="*{lastName}" placeholder = "Enter Employee Last Name"/> <br>
                    
                        <form:label path="email">Employee Email</form:label>
                        <form:input path="email" type="text" field="*{email}" placeholder = "Enter Employee Email"/> <br>
                        
                        <form:label path="gender">Employee Gender</form:label>
                        <form:radiobutton path="gender"  field="*{gender}" value="Male"/>Male
                        <form:radiobutton path="gender"  field="*{gender}" value="Female"/>Female <br>
                        
                        <form:label path="marriage">Employee Married?</form:label>
                        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
                        <form:checkbox path="marriage" class="selectOnly" field="*{marriage}" value="Married"/>Married
                        <form:checkbox path="marriage" class="selectOnly" field="*{marriage}" value="Un-Married"/>Un-Married
                        <script type="text/javascript">
                            $('.selectOnly').on('change', function() {
                                $('.selectOnly').not(this).prop('checked', false);
                            });
                            </script> <br>
                            
                        <form:label path="birthday">Employee birthday</form:label>
                        <form:input path="birthday" type="date" field="*{birthday}"/> <br>
                        
                        
                        <form:label path="workat">Employee Company</form:label>
                        <form:select path="workat">
                        <form:option value="">--SELECT COMPANY--</form:option>
                        <form:option field = "*{workat}" value="NIC-Hyderabad">NIC-Hyderabad</form:option>
                        <form:option field = "*{workat}" value="NIC-Bangalore">NIC-Bangalore</form:option>
                        </form:select>
                        
                        <form:label path="department">Employee Department</form:label>
                        <form:select path="department">
                        <form:option value="">--SELECT DEPARTMENT--</form:option>
                        <form:option field = "*{department}" value="Dep-01">Dep-01</form:option>
                        <form:option field = "*{department}" value="Dep-02">Dep-02</form:option>
                        <form:option field = "*{department}" value="Dep-03">Dep-03</form:option>
                        </form:select>
                    
                    
                        <div class = "box-footer">
                            <form:button type="submit" class = "btn btn-primary">Submit</form:button>
                        </div>
                    </form:form>
                    
                </div>
            </div>
        </div>
    </div>
    

</body>
</html>

7.edit_employee.jsp

<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" 
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
      crossorigin="anonymous">

<style type="text/css">
    span {
        color: red;
        font-style: italic;
    }
    option {
  margin: 0.5em;
}
</style>

<style type="text/css">
    /* a:active {
        color: white;
    }
    a:visited {
        color: blue;
    } */
    a {
        display: blue;
    }
</style>

<style type="text/css">
    label {
        display: inline-block;
        width: 200px;
        margin: 5px;
        text-align: left;
    }
    
    button {
        padding: 10px;
        margin: 10px;
    }
</style>
</head>
<body>
</head>
<body>


  
 <br>
<br>
    
    <div class = "container">
        <div class = "row">
            <div class = "col-lg-6 col-md-6 col-sm-6 container justify-content-center-center card">
                <h1 class = "text-center"> Update Employee </h1>
                <div class = "card-body" >
                    <form:form action="/employees/{id} (id=${employee.id})" method="POST" modelAttribute="employee">
                        
                        <form:label path="firstName">Employee First Name</form:label>
                        <form:input path="firstName" type="text" field="*{firstName}" placeholder = "Enter Employee First Name"/> <br>
                    
                        <form:label path="lastName">Employee Last Name</form:label>
                        <form:input path="lastName" type="text" field="*{lastName}" placeholder = "Enter Employee Last Name"/> <br>
                    
                        <form:label path="email">Employee Email</form:label>
                        <form:input path="email" type="text" field="*{email}" placeholder = "Enter Employee Email"/> <br>
                        
                        <form:label path="gender">Employee Gender</form:label>
                        <form:radiobutton path="gender"  field="*{gender}" value="Male"/>Male
                        <form:radiobutton path="gender"  field="*{gender}" value="Female"/>Female <br>
                        
                        <form:label path="marriage">Employee Married?</form:label>
                        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
                        <form:checkbox path="marriage" class="selectOnly" field="*{marriage}" value="Married"/>Married
                        <form:checkbox path="marriage" class="selectOnly" field="*{marriage}" value="Un-Married"/>Un-Married
                        <script type="text/javascript">
                            $('.selectOnly').on('change', function() {
                                $('.selectOnly').not(this).prop('checked', false);
                            });
                            </script> <br>
                            
                        <form:label path="birthday">Employee birthday</form:label>
                        <form:input path="birthday" type="date" field="*{birthday.id}" /> <br>
                        
                        
                        <form:label path="workat">Employee Company</form:label>
                        <form:select path="workat">
                        <form:option value="">--SELECT COMPANY--</form:option>
                        <form:option field = "*{workat}" value="NIC-Hyderabad">NIC-Hyderabad</form:option>
                        <form:option field = "*{workat}" value="NIC-Bangalore">NIC-Bangalore</form:option>
                        </form:select>
                        
                        <form:label path="department">Employee Department</form:label>
                        <form:select path="department">
                        <form:option value="">--SELECT DEPARTMENT--</form:option>
                        <form:option field = "*{department}" value="Dep-01">Dep-01</form:option>
                        <form:option field = "*{department}" value="Dep-02">Dep-02</form:option>
                        <form:option field = "*{department}" value="Dep-03">Dep-03</form:option>
                        </form:select>
                    
                    
                        <div class = "box-footer">
                            <form:button type="submit" class = "btn btn-primary">Submit</form:button>
                        </div>
                    </form:form>
                </div>
            </div>
        </div>
    </div>
 



</body>
</html>

8.获取url的请求是

http://localhost:8086/employees/edit/1

url 请求失败 - http://localhost:8086/employees/%7Bid%7D%20(id=1)

【问题讨论】:

  • 问题可能出在您的 JSP 中,请将其添加到您的问题中,以及失败请求的内容(URL 和正文)
  • 您是否只在调用更新时遇到问题?
  • @tgdavies 再次检查代码,我已经添加了jsp文件和url
  • @VeKe 当我点击更新按钮时,表单显示但值没有更新
  • 你尝试过卷曲还是邮递员打电话?

标签: java spring-boot jsp


【解决方案1】:

将添加控制器级别作为错误请求引发错误。 您传递了错误的值 (1) 而不是 1

将值作为一些数字传递,而不是像 () 这样的附加内容。

@RequestMapping(value="/employees/edit/{id}")    
public String editEmployeeForm(@PathVariable Long id, Model 
m){


}

【讨论】:

  • Spring 会将路径变量转换为 int 或 long 格式。但在你的事业中它没有发生。
  • 这两种方法我都试过了,但对我没有用
  • 获取重复的局部变量 id Long 类型的方法 parseLong(String) 不适用于 Long 参数
  • 您在路径变量中传递了一些错误的值
  • 不适用,因为您传递为 (1)
【解决方案2】:

在 Controller 类和 Dao 类中对坏 sql 查询进行了一些更改后 成功了。

1.In Controller Class

@RequestMapping(value="/employees/{id}",method = RequestMethod.POST)    
    public String updateEmployee(@PathVariable("id") Long id, @ModelAttribute("employee") Employee employee)
            
    { 
      employee.setId(id);
      employeeDao.updateEmployee(employee); 
      return "redirect:/employees"; 
    }

2.In Dao Class

public long updateEmployee(Employee p)
    {
        String sql="update employee set first_name='"+p.getFirstName()+"', last_name='"+p.getLastName()+"'"
                + ",email='"+p.getEmail()+"',gender='"+p.getGender()+"',marriage='"+p.getMarriage()+"',"
                        + "birthday='"+p.getBirthday()+"',workat='"+p.getWorkat()+"',department='"+p.getDepartment()+"'"
                                + " where id='"+p.getId().toString()+"'";    
        System.out.println("Query::"+sql);
        return jdbcTemplate.update(sql); 
    }

3.finally in edit_employee.jsp

<form:form action="/employees/${employee.id}" method="POST" modelAttribute="employee">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多