Thymeleaf Select Option(List) Example - Dropdown - Java Inspires



 Hi Guys,

Welcome to Java Inspires 😀

In this post, we will see how to create a dropdown with values in thymeleaf. Here we will create a employee form where the designation field is a dropdown(select option).

This example includes, how to populate values to dropdown and how to bind or select values to the form object(model object).

Lets start..

1, Create A Spring Boot Started project by adding web and thymeleaf starters.


2, Project Structure



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javainspires</groupId>
	<artifactId>thymeleaf-dropdown</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>thymeleaf-dropdown</name>
	<description>Demo project for Spring Boot + Thymeleaf + Dropdown </description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>



#Thymeleaf Configuration
spring.thymeleaf.prefix = classpath:/pages/
spring.thymeleaf.suffix = .html



package com.javainspires;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * 
 * @author #JavaInspires
 *
 */
@SpringBootApplication
public class ThymeleafDropdownApplication {

	public static void main(String[] args) {
		SpringApplication.run(ThymeleafDropdownApplication.class, args);
	}

}



package com.javainspires;

/**
 * 
 * @author #JavaInspires
 *
 */
public class EmployeeForm {

	private String id;
	private String name;
	private String designation;

	public EmployeeForm() {
		super();
		// TODO Auto-generated constructor stub
	}

	public EmployeeForm(String id, String name, String designation) {
		super();
		this.id = id;
		this.name = name;
		this.designation = designation;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	@Override
	public String toString() {
		return "EmployeeForm [id=" + id + ", name=" + name + ", designation=" + designation + "]";
	}

}




package com.javainspires;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 
 * @author #JavaInspires
 *
 */
@Controller
public class EmployeeController {
	private static List<String> designations;
	static {
		designations = new ArrayList<>();
		designations.add("Developer");
		designations.add("Consultant");
		designations.add("Manager");
		designations.add("Tester");
	}

	@GetMapping(path = "/employee")
	private String getEmployeeForm(Model model) {
		model.addAttribute("designations", designations);
		return "employee-form";
	}

	@PostMapping(path = "/employee")
	private String submitEmployee(@ModelAttribute("employeeForm") EmployeeForm employeeForm, Model model) {
		model.addAttribute("data", employeeForm.toString());

		return "success";
	}
}



<!-- #JavaInspires -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Java Inspires</title>
</head>
<body>
	<div align="center">
		<br>
		<h1>Employee Form</h1>
		<br>
		<form th:action="@{/employee}" th:object="${employeeForm}" method="POST">
			<table>
				<tr>
					<td>Emp ID</td>
					<td><input type="text" name="id" /></td>
				</tr>
				<tr>
					<td>Emp Name</td>
					<td><input type="text" name="name" /></td>
				</tr>
				<tr>
					<td>Emp Designation</td>
					<td><select name="designation">
							<option th:each="designation :${designations}"
								th:text="${designation}">
					</select></td>
				</tr>
			</table>
			<input type="submit" value="Save" />
		</form>
	</div>
</body>
</html>



<!-- #JavaInspires -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Java Inspires</title>
</head>
<body>
	<h1>Success...!</h1>
	<div th:text="${data}"></div>
</body>
</html>



  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)

2020-09-26 14:26:12.061  INFO 1096 --- [           main] c.j.ThymeleafDropdownApplication         : Starting ThymeleafDropdownApplication on DESKTOP-9LT6E5T with PID 1096 (C:\Users\#JavaInspires\Desktop\thymeleaf-dropdown\thymeleaf-dropdown\target\classes started by #JavaInspires in C:\Users\#JavaInspires\Desktop\thymeleaf-dropdown\thymeleaf-dropdown)
2020-09-26 14:26:12.065  INFO 1096 --- [           main] c.j.ThymeleafDropdownApplication         : No active profile set, falling back to default profiles: default
2020-09-26 14:26:13.050  INFO 1096 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-09-26 14:26:13.060  INFO 1096 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-09-26 14:26:13.060  INFO 1096 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.38]
2020-09-26 14:26:13.177  INFO 1096 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-09-26 14:26:13.177  INFO 1096 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1038 ms
2020-09-26 14:26:13.384  INFO 1096 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-26 14:26:13.622  INFO 1096 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-09-26 14:26:13.634  INFO 1096 --- [           main] c.j.ThymeleafDropdownApplication         : Started ThymeleafDropdownApplication in 2.042 seconds (JVM running for 3.181)





Screenshots:







😀 THANK YOU 😀


1 Comments

  1. Manny thanks for your tutorial. Some questions:
    1) Why in postMapping method submitEmployee when you are using employeeForm as @ModelAtrribute you invoce toString method on employeeForm object ?
    2) Is there a way to bind data to the EmployeeForm directly by th:field ?
    3)Is there a way to use Enum class instead of the list to fill the dropdown and after get the selection and pass it as enum value? If the answer is yes how should I do it?

    ReplyDelete
Previous Post Next Post