Spring MVC Form Processing Examples The following example illustrates how to write a simple web-based application that utilizes HTML forms using Spring's Web MVC framework.
A test project construction
(1) Create a new Java Web project and introduce several jar packages required for SpringMVC projects. The project structure and jar packages required are as follows:
①web.xml:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
Here is a SpringMVC intercepting url suffix ending with .html and processing it
②springmvc-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="cn.zifangsky.* *.controller" /> <context:annotation-config /> <!-- Activate the annotation defined in the bean--> <mvc:annotation-driven /> <bean > <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean></beans>
In the above configuration file, <context:annotation-config /> activates some annotations defined in the Bean, while <mvc:annotation-driven /> activates some default configurations for SpringMVC. At the end of the configuration file, the correspondence between the logical view and the actual view is defined. In a word, the path prefix and suffix defined above are given to the returned logical view. This is the real path to the actual view.
2. Use SpringMVC to process Form forms
(1) Before officially starting, create a model and enumeration class:
① Entity User:
package cn.zifangsky.model;import java.time.LocalDate;import org.springframework.format.annotation.DateTimeFormat;public class User { private String name; private String password; private String job; @DateTimeFormat(pattern="yyyy-MM-dd") private LocalDate birthDate; private Gender gender; private String country; private boolean smoking; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public LocalDate getBirthDate() { return birthDate; } public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public boolean isSmoking() { return smoking; } public void setSmoking(boolean smoking) { this.smoking = smoking; } } ② Enumeration class Gender that represents "gender":
package cn.zifangsky.model; public enum Gender { MALE, FEMALE;} The following will briefly explain the Form form processing of SpringMVC according to the program execution process, namely the Foreground form filling>controller processing>processing result view page
(2) The homepage and form form page of the test project:
①Home page index.jsp:
<% response.sendRedirect("form.html"); %>It can be seen that our homepage here is very simple, which is to redirect to "form.html", but through our previous configuration in web.xml, SpringMVC will transfer this request to a specific controller for processing, of course, it is directly to the form form page. The specific processing logic in the controller will be discussed below
②form form page userForm.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Spring MVC Form Handling</title></head><body> <h2>User Registration</h2> <mvc:form modelAttribute="user" action="result.html"> <table> <tr> <td><mvc:label path="name">Name:</mvc:label></td> <td><mvc:input path="name" /></td> </tr> <tr> <td><mvc:label path="password">Password:</mvc:label></td> <td><mvc:password path="password" /></td> </tr> <tr> <td><mvc:label path="job">Work:</mvc:label></td> <td><mvc:textarea path="job" /></td> </tr> <tr> <td><mvc:label path="birthDate">Birthday:</mvc:label></td> <td><mvc:input path="birthDate" /></td> </tr> <tr> <td><mvc:label path="gender">Gender:</mvc:label></td> <td><mvc:radiobuttons path="gender" items="${genders}" /></td> </tr> <tr> <td><mvc:label path="country">Residence:</mvc:label></td> <td><mvc:select path="country" items="${countries}" /></td> </tr> <tr> <td><mvc:label path="smoking">Do you smoke?:</mvc:label></td> <td><mvc:checkbox path="smoking" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit" /></td> </tr> </tr> </table> </mvc:form></body></html> Since we put this page in the WEB-INF directory, we cannot access this file directly through the URL. The "form.html" defined above must be transferred to the controller for processing and displayed this view page. The purpose of this is to prevent some private pages from being accessed by others without authorization. In the above file, it is important to note:
(3) Controller class UserController.java for business logic processing:
package cn.zifangsky.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 cn.zifangsky.model.Gender;import cn.zifangsky.model.User;@Controllerpublic class UserController { private static final String[] countries = {"China","Japan","North Korea","United States"}; @RequestMapping(value="/form.html") public ModelAndView user(){ ModelAndView modelAndView = new ModelAndView("userForm"); modelAndView.addObject("user", new User()); modelAndView.addObject("genders",Gender.values()); modelAndView.addObject("countries", countries); return modelAndView; } @RequestMapping(value="/result.html") public ModelAndView processUser(@ModelAttribute(value="user") User u){ ModelAndView modelAndView = new ModelAndView("userResult"); modelAndView.addObject("u",u); return modelAndView; } } It can be seen that two methods are defined above, and their functions are to transfer to the real form form for the "form.html" request and to handle the form form. When processing the form, I received a User type "u" through the @ModelAttribute annotation, which is the form form filled in first, and the following is the display of the form, so I won't say much
(4) Test:
①Fill in the form:
②The results show:
userResult.jsp page:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%><!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=UTF-8"><title>Spring MVC Form Handling</title></head><body> <h2>Register Results</h2> <table> <ttr> <td>Name:</td> <td>${u.name}</td> </tr> <tr> <td>Password:</td> <td>${u.password}</td> </tr> <tr> <td>Work:</td> <td>${u.job}</td> </tr> <tr> <td>Birthday:</td> <td>${u.birthDate}</td> </tr> <tr> <td>Gender:</td> <td>${u.gender}</td> </tr> <tr> <td>Residence:</td> <td>${u.country}</td> </tr> <tr> <td>Smoking:</td> <td>${u.smoking}</td> </tr> </tr> </table></body></html>The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.