Página de índice de tutoriales de primavera
Anterior – Inyección de dependencia
Siguiente – Validación de formulario
Este artículo muestra cómo procesar formularios en Spring. En este programa, se agregará un módulo de envío de formularios. Específicamente, usaremos el formulario web para agregar un nuevo empleado y mostrar la lista de nuevos empleados.
Paso 1: Prepare las clases requeridas
Agregar addEmployee
método a EmployeeManager.java. Este método se utilizará para agregar nuevos empleados a la lista.
EmployeeManager.java
package com.programcreek.helloworld.service; import java.util.ArrayList; import java.util.List; import com.programcreek.helloworld.model.Employee; public class EmployeeManager { private static List<Employee> employeeList; public EmployeeManager(){ employeeList = new ArrayList<Employee>(); employeeList.add(new Employee(1, "Mike", "Smith")); employeeList.add(new Employee(2, "John", "Taylor")); employeeList.add(new Employee(3, "Dave", "Wilson")); } public List<Employee> getEmployeeList(){ return employeeList; } public Employee addEmployee(Employee e){ Employee employee = new Employee(); employee.setId(employeeList.size()+1); employee.setFirstName(e.getFirstName()); employee.setLastName(e.getLastName()); employeeList.add(employee); return employee; } } |
Employee.java
package com.programcreek.helloworld.model; public class Employee { private int id; private String lastName; private String firstName; public Employee(){ } public Employee(int id, String lastName, String firstName) { this.id = id; this.lastName = lastName; this.firstName = firstName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } } |
Paso 2: crear controlador
Cree un nuevo controlador para manejar el envío de formularios.
EmployeeAddController.java
package com.programcreek.helloworld.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.programcreek.helloworld.model.Employee; import com.programcreek.helloworld.service.EmployeeManager; @Controller public class EmployeeAddController { @RequestMapping("/showEmployeeForm") public ModelAndView getEmployeeForm(){ ModelAndView mv = new ModelAndView("employeeAdd"); mv.addObject("employeeEntity", new Employee()); return mv; } @RequestMapping("/addEmployee") public ModelAndView addEmployee(@ModelAttribute Employee e){ ModelAndView mv = new ModelAndView("employeeList"); EmployeeManager employeeManager = new EmployeeManager(); employeeManager.addEmployee(e); mv.addObject("employeeList", employeeManager.getEmployeeList()); return mv; } } |
El controlador procesa dos solicitudes aquí: una lleva la página web al formulario y la otra procesa el envío del formulario. Nota @ModelAttribute
asigna los atributos de los formularios a un empleado.
Paso 3: crear vistas
employeeAdd.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <body> <h1>Add Employee</h1> <form:form method="post" modelAttribute="employeeEntity" action="addEmployee"> First Name:<form:input path="firstName"></form:input><br/> Last Name: <form:input path="lastName"></form:input><br/> <input type="submit" value="Submit"> </form:form> </body> </html> |
Agregar empleado
Apellido:
form: form>
Agregue un nuevo enlace que lleve a agregar formulario de empleado.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring 4 MVC - HelloWorld Index Page</title> </head> <body> <center> <h3> <a href="hello">Hello World</a> </h3> <h3> <a href="employee">Employee List</a> </h3> <h3> <a href="showEmployeeForm">Add Employee</a> </h3> </center> </body> </html> |
Hola mundo
Lista de empleados
Agregar empleado
Resultado
Jerarquía de archivos final en la vista del navegador.
Ejecute el proyecto ahora y las páginas web son las siguientes:
Página de inicio
Página de formulario de empleado
Página de lista de empleados
Descargar
Descarga de código fuente