首页 > 解决方案 > 未从数据库中检索相关的下拉数据和图像

问题描述

使用带有thymeleaf属性的spring boot、java、html和mysql数据库来存储所有数据。我创建了一个员工管理系统,在其中我提供了员工形象、姓名、电子邮件……等等

我们可以添加、更新和删除每个员工,通过使用添加按钮,我已成功将所有员工详细信息保存到 mysql 数据库中,但问题是当我尝试更新员工时,所有内容都被检索到,但图像和相关下拉值未检索到。我在 mysql 数据库中将图像类型指定为 varchar。

我已经使用 javascript 创建了下拉列表和技能。我已经给出了 th:field 但没有检索到值。谁能给我一个解决这个问题的方法。

当我单击更新按钮时,我想从 mysql 数据库中检索所有数据。

    1.edit_employee.html
    
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <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>        
          
    </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" th:href = "@{/employees}">Employee Management</a> 
          </li>
        </ul>
      </div>
    
    
        <!-- Navbar links -->
      <div class="collapse navbar-collapse" id="collapsibleNavbar">
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" th:href="@{/employeesproject}">Employee Project</a>
          </li>
        </ul>
      </div>
     </nav>
    
    <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 th:action="@{/employees/{id} (id=${employee.id})}" th:object = "${employee}" method="POST"
                                    enctype="multipart/form-data"
                                    style="max-width: 400px; margin: 0 auto;">
                            
                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
                            <div class = "form-group">
                                <label> Employee Image </label> 
                                <input
                                type = "file"
                                name = "fileImage"
                                class = "form-control"
                                id = "fileImage"
                                accept="image/png, image/jpeg"
                                /> 
                                <p> 
                                <img id="thumbnail" alt="Logo Preview">
                                </p>
                            </div>  
                            <div>
                            <script type="text/javascript">
                                $(document).ready(function() {
                                    $('#fileImage').change(function() {
                                        showImageThumbnail(this);       
                                });
                                    
                                function showImageThumbnail(fileInput) {
                                    file = fileInput.files[0];
                                    reader = new FileReader();
                                    
                                    reader.onload = function(e) {
                                        $('#thumbnail').attr('src', e.target.result);
                                    };
                                    
                                    reader.readAsDataURL(file);
                                }
                                });
                                                    
                            </script>
                                
                            </div>
                        
                            <div class = "form-group">
                                <label> Employee First Name </label>    
                                <input
                                type = "text"
                                name = "firstName"
                                th:field = "*{firstName}"
                                class = "form-control"
                                placeholder = "Enter Employee First Name"
                                />  
                                <span th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">Name error</span>      
                            </div>  
                            
                            <div class = "form-group">
                                <label> Employee Last Name </label> 
                                <input
                                type = "text"
                                name = "lastName"
                                th:field = "*{lastName}"
                                class = "form-control"
                                placeholder = "Enter Employee Last Name"
                                />  
                                <span th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">Name error</span>                    
                            </div>  
                            
                            <div class = "form-group">
                                <label> Employee Email </label> 
                                <input
                                type = "text"
                                name = "email"
                                th:field = "*{email}"
                                class = "form-control"
                                placeholder = "Enter Employee Email"
                                />  
                                <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email error</span>                 
                            </div>  
                            
                            <div class = "form-group">
                                <label> Employee Skills </label>    <br>
                                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
                                <input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Java" />Java <br>
                                <input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Python" />Python <br>
                                <input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value=".Net" />.Net <br>
                                <input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Kotlin" />Kotlin <br>
                                <input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="C" />C <br>
                                <input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Ruby" />Ruby <br>
                                <script type="text/javascript">
                                var limit = 3;
                                var checked = 0;
                                $('.selectupto3').on('change', function() {
                                  if($(this).is(':checked'))
                                    checked = checked+1;
    
                                  if($(this).is(':checked') == false)
                                    checked = checked-1;
    
                                  if(checked > limit) {
                                    this.checked = false;
                                    checked = limit;
                                  }
                                });
                                </script>
                                
                                <span th:if="${#fields.hasErrors('skills')}" th:errors="*{skills}">skill error</span>   
                        
                            </div>  
                            
                        
                            
                            <div class = "form-group">
                                <label>  Employee Gender </label>
                                <input type="radio" th:field = "*{gender}" name = "gender" value="Male" />Male
                                <input type="radio" th:field = "*{gender}" name = "gender" value="Female" />Female
                                <span th:if="${#fields.hasErrors('gender')}" th:errors="*{gender}">gender error</span>  
                            </div>
                            
                            
                            
                            <div class = "form-group">
                                <label>  Employee Married? </label>
                                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
                                
                                <input type="checkbox" th:field = "*{marriage}" class = "selectOnly" name = "marriage" value="Married" />Married
                                <input type="checkbox" th:field = "*{marriage}" class = "selectOnly" name = "marriage" value="Un-Married" />Un-Married
                                <script type="text/javascript">
                                $('.selectOnly').on('change', function() {
                                    $('.selectOnly').not(this).prop('checked', false);
                                });
                                </script>
                                <span th:if="${#fields.hasErrors('marriage')}" th:errors="*{marriage}">Marriage status error</span> 
                            </div>
                            
                            
                            <div class = "form-group">
                                <label>  Employee Birthday </label>
                                <input type="date" th:field = "*{birthday}" name = "birthday" />
                                <span th:if="${#fields.hasErrors('birthday')}" th:errors="*{birthday}">Birthday error</span>
                            </div>
                            
                                                    <div class = "container">
                                <div class = "form-group">
                                    <label for="">  Employee Works at </label>
                                    <select th:field = "*{workat}" class = "form-control"  name="workat" id="select1" onchange="populate(this.id,'select2')">
                                    <option th:field = "*{workat}" value="">--SELECT COMAPNY--</option>
                                    <option th:field = "*{workat}" value="NIC-Hyderabad">NIC-Hyderabad</option>
                                    <option th:field = "*{workat}" value="NIC-Bangalore">NIC-Bangalore</option>
                                    </select>
                                    <span th:if="${#fields.hasErrors('workat')}" th:errors="*{workat}">Work at error</span>
                                    
                                <div class = "form-group">
                                    <label for="">Department</label>
                                    <select th:field = "*{workat}" class = "form-control" name="workat" id="select2"></select>
                                </div>
                                </div>
                                
                                
                            </div>
                            
                            <script type="text/javascript">
                            
                                function populate(s1,s2)
                                {
                                    var s1 = document.getElementById(s1);
                                    var s2 = document.getElementById(s2);
                                    
                                    s2.innerHTML = "";
                                    
                                    if(s1.value == "NIC-Hyderabad")
                                        {
                                            var optionArray = ['dep-01|Dep-01','dep-02|Dep-02','dep-03|Dep-03',
                                                'dep-04|Dep-04'];
                                        }
                                    else if(s1.value == "NIC-Bangalore")
                                        {
                                        var optionArray = ['dep-01|Dep-01','dep-02|Dep-02','dep-03|Dep-03'];
                                        }
                                    for(var option in optionArray)
                                        {
                                            var pair = optionArray[option].split("|");
                                            var newoption = document.createElement("option");
                                            
                                            newoption.value = pair[0];
                                            newoption.innerHTML=pair[1];
                                            s2.options.add(newoption);
                                        }
                                    
                                }
                            
                            </script>
       
                            
                            
                            <div class = "box-footer">
                                <button type="submit" class = "btn btn-primary">
                                    Submit
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    
    
    
    </body>
    </html>

2.EmployeeController.class

package net.javaguides.ems.controller;


import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.lowagie.text.DocumentException;

import net.javaguides.ems.entity.Employee;
import net.javaguides.ems.pdfexport.EmployeePDFExporter;
import net.javaguides.ems.pdfexport.EmployeesPDFExporter;
import net.javaguides.ems.service.EmployeeService;

@Controller // Controller Layer holds all Spring MVC Controllers
public class EmployeeController {
    
    private EmployeeService employeeService;

    public EmployeeController(EmployeeService employeeService) {
        super();
        this.employeeService = employeeService;
    }

    @GetMapping("/employees")
    public String listEmployees(Model model)
    {
        System.out.println("Test1");
        model.addAttribute("employees", employeeService.getAllEmployees());
        return "employees";
    }
    
    @GetMapping("/employees/new")
    public String createStudentForm(Model model)
    {
        //Create empty employee object to hold employee form data
        Employee employee = new Employee();
        model.addAttribute("employee", employee);
        return "create_employee";
    }
    
    @PostMapping("/employees")
    public String saveEmployee(@Valid @ModelAttribute("employee") Employee employee,
            BindingResult bindingResult, @RequestParam("fileImage") MultipartFile multipartFile) throws IOException
    {                                       
        //Here, we r using ModelAttribute to directly bind form data to the employee object.
        
        if (bindingResult.hasErrors())
        {
            return "create_employee";
        }
        else
        {
            String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
            employee.setImage(fileName);
            Employee savEmployee = employeeService.saveEmployee(employee);
            
            String uploadDir = "./employee-images/" + savEmployee.getId();
            Path uploadPath = Paths.get(uploadDir);
            
            if(!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            try (InputStream inputStream = multipartFile.getInputStream()) {
                Path filePath = uploadPath.resolve(fileName);
                System.out.println(filePath.toFile().getAbsolutePath());
                Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING); 
            } catch (IOException e) {
                throw new IOException("Could not save uploaded file: " + fileName);
            }
            
            
            employeeService.saveEmployee(employee);
            return "redirect:/employees";
        }
    }
    
    @GetMapping("/employees/edit/{id}")
    public String editEmployeeForm(@PathVariable long id, Model model) //PathVariable Annotation is to get the id.
    {
        model.addAttribute("employee", employeeService.getEmployeeById(id));
        return "edit_employee";
    }
    
    @PostMapping("/employees/{id}")
    public String updateEmployee(@PathVariable long id, @Valid
            @ModelAttribute("employee") Employee employee, BindingResult bindingResult, 
            @RequestParam("fileImage") MultipartFile multipartFile) throws IOException
    
    {
        
        
        // save updated employee object
        if (bindingResult.hasErrors())
        {
            return "create_employee";
        }
        else
        {
            String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
            employee.setImage(fileName);
            Employee savEmployee = employeeService.saveEmployee(employee);
            
            String uploadDir = "./employee-images/" + savEmployee.getId();
            Path uploadPath = Paths.get(uploadDir);
            
            if(!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            try (InputStream inputStream = multipartFile.getInputStream()) {
                Path filePath = uploadPath.resolve(fileName);
                System.out.println(filePath.toFile().getAbsolutePath());
                Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING); 
            } catch (IOException e) {
                throw new IOException("Could not save uploaded file: " + fileName);
            }
            
            // get employee from database by id
            Employee existingEmployee = employeeService.getEmployeeById(id);
            existingEmployee.setId(id);
            existingEmployee.setImage(employee.getImage());
            existingEmployee.setFirstName(employee.getFirstName());
            existingEmployee.setLastName(employee.getLastName());
            existingEmployee.setEmail(employee.getEmail());
            existingEmployee.setSkills(employee.getSkills());
            existingEmployee.setGender(employee.getGender());
            existingEmployee.setMarriage(employee.getMarriage());
            existingEmployee.setBirthday(employee.getBirthday());
            existingEmployee.setWorkat(employee.getWorkat());
            
            employeeService.updateEmployee(existingEmployee);
            return "redirect:/employees";
        }
        
    }
    
    // handler method to handle delete employee request
    
    @GetMapping("/employees/delete/{id}")
    public String deleteEmployee(@PathVariable long id)
    {
        employeeService.deleteEmployeeById(id);
        return "redirect:/employees";
    }

    
    @GetMapping("/employees/exportpdf")
    public String exportToPDF(HttpServletResponse response) // throws DocumentException, IOException
    {
        System.out.println("Testing");
        
        
          response.setContentType("application/pdf");
          
          DateFormat dateFormatter = new SimpleDateFormat("yyyy-mm-dd_HH:mm:ss");
          String currentDateTime = dateFormatter.format(new Date());
          
          String headerKey = "Content-Disposition"; 
          String headerValue = "attachment; filename=employees_" + currentDateTime + ".pdf";
          
          response.setHeader(headerKey, headerValue);
         
        
        List<Employee> listEmployees = employeeService.getAllEmployees();
        System.out.println("T"+listEmployees.size()+"::");
        EmployeesPDFExporter exporter = new EmployeesPDFExporter(listEmployees);
        try {
            exporter.employeesexport(response);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        return "redirect:/employees";
    }

    
    
      @GetMapping("/employee/export/{id}") 
      public void exportemployeeToPDF(@PathVariable(name = "id") long id,HttpServletResponse response) throws DocumentException, IOException
      { 
          response.setContentType("application/pdf");
      
          DateFormat dateFormatter = new SimpleDateFormat("yyyy-mm-dd_HH:mm:ss");
          String currentDateTime = dateFormatter.format(new Date());
      
          String headerKey = "Content-Disposition"; 
          String headerValue = "attachment; filename=employees_" + currentDateTime + ".pdf";
      
          response.setHeader(headerKey, headerValue);
      
          Employee employee = employeeService.getEmployeeById(id);
      
          EmployeePDFExporter exporter = new EmployeePDFExporter(employee);
          exporter.export(response); 
      }


}

3.edit form image

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/pYFRo.png

标签: javahtmlspring-boot

解决方案


推荐阅读