Form – Java and Spring Examples http://localhost/wordpress Wed, 26 Jun 2019 15:04:13 +0000 fr-FR hourly 1 https://wordpress.org/?v=5.0.4 Example Spring 4 MVC – Form http://localhost/wordpress/2019/03/19/529/ Tue, 19 Mar 2019 15:59:32 +0000 http://localhost/wordpress/?p=529 This example presents the basic concept of using forms in Spring MVC.

The technologies used are :

    – Spring 4.3.18
    – JDK 1.80
    – Maven 3.3.9

You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :

mvn eclipse:eclipse

Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).

package javaspringexamples.spring.mvcform.domain;

import java.time.LocalDate;

import javax.validation.constraints.Size;

import org.springframework.format.annotation.DateTimeFormat;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class User {

	@Size(min = 3, max = 14)
	private String name;
	@Size(min = 3, max = 14)
	private String lastname;
	private String password;
	private String detail;
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private LocalDate birthDate;
	private Gender gender;
	private String country;
	private boolean nonSmoking;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDetail() {
		return detail;
	}

	public void setDetail(String detail) {
		this.detail = detail;
	}

	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 isNonSmoking() {
		return nonSmoking;
	}

	public void setNonSmoking(boolean nonSmoking) {
		this.nonSmoking = nonSmoking;
	}
}
package javaspringexamples.spring.mvcform.domain;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public enum Gender {
	MALE,
	FEMALE;
}
package javaspringexamples.spring.mvcform.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javaspringexamples.spring.mvcform.domain.Gender;
import javaspringexamples.spring.mvcform.domain.User;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Controller
public class UserController {

	private static final String[] countries = { "Morocco", "United States", "France" };

	@RequestMapping(value = "/form")
	public ModelAndView user() {
		ModelAndView modelAndView = new ModelAndView("userForm", "user", new User());
		modelAndView.addObject("genders", Gender.values());
		modelAndView.addObject("countries", countries);

		return modelAndView;
	}

	@RequestMapping(value = "/result")
	public ModelAndView processUser(@Valid User user, BindingResult result) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("user", user);

		if (result.hasErrors()) {
			modelAndView.addObject("genders", Gender.values());
			modelAndView.addObject("countries", countries);
			modelAndView.setViewName("userForm");
		} else {
			modelAndView.setViewName("userResult");
		}

		return modelAndView;
	}
}
Size.user.name=Error format: at least 3, max 14.
Size.user.lastname=Error format: at least 3, max 14.
Pattern.user.password=Error format: at least 4 letters, max 15.
<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-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>

</web-app>
<?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="javaspringexamples.spring.mvcform" />
	<context:annotation-config />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>
<% response.sendRedirect("form.mvc"); %>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Spring MVC Form</title>
</head>
<body>

	<h2>Form</h2>
	<mvc:form modelAttribute="user" action="result.mvc">
		<table>
			<tr>
				<td><mvc:label path="name">Name</mvc:label></td>
				<td><mvc:input path="name" /></td>
				<td><mvc:errors path="name" /></td>
			</tr>
			<tr>
				<td><mvc:label path="lastname">Last Name</mvc:label></td>
				<td><mvc:input path="lastname" /></td>
				<td><mvc:errors path="lastname" /></td>
			</tr>
			<tr>
				<td><mvc:label path="password">Password</mvc:label></td>
				<td><mvc:password path="password" /></td>
				<td><mvc:errors path="password" /></td>
			</tr>
			<tr>
				<td><mvc:label path="detail">Detail</mvc:label></td>
				<td><mvc:textarea path="detail" /></td>
			</tr>
			<tr>
				<td><mvc:label path="birthDate">Birth Date</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">Country</mvc:label></td>
				<td><mvc:select path="country" items="${countries}" /></td>
			</tr>
			<tr>
				<td><mvc:label path="nonSmoking">Non Smoking</mvc:label></td>
				<td><mvc:checkbox path="nonSmoking" /></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</mvc:form>
</body>
</html>
<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<title>JavaSpringExamples Spring MVC Form</title>
</head>
<body>
	<h2>Result</h2>
	<table>
		<tr>
			<td>Name</td>
			<td>${user.name}</td>
		</tr>
		<tr>
			<td>Last name</td>
			<td>${user.lastname}</td>
		</tr>
		<tr>
			<td>Password</td>
			<td>${user.password}</td>
		</tr>
		<tr>
			<td>Detail</td>
			<td>${user.detail}</td>
		</tr>
		<tr>
			<td>Birth Date</td>
			<td>${user.birthDate}</td>
		</tr>
		<tr>
			<td>Gender</td>
			<td>${user.gender}</td>
		</tr>
		<tr>
			<td>Country</td>
			<td>${user.country}</td>
		</tr>
		<tr>
			<td>Non-Smoking</td>
			<td>${user.nonSmoking}</td>
		</tr>
	</table>
</body>
</html>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>