[JAVA] Super easy way to use enum with JSP

1.First of all

Unlike constants, Java enums are type-safe and are a convenient data type that can have multiple data. Therefore, you can define the code such as master and its meaning together. This time, I would like to explain how to easily display list boxes and checkboxes by using the enum in JSP. The web app is premised on spring-boot (spring mvc, TERASOLUNA 5.x).

2. Definition of enum

Define the enum used in this sample. I made an enum with the data of the code field of int and the label field to be displayed. If you do not use lombok, explicitly define the constructor and setter as well.


package com.example.demo;

import lombok.AllArgsConstructor;
import lombok.Getter;

public enum Status {

    APPROVAL(1, "Approval"),
    DENIAL(2, "Denial"),
    WITHDRAWAL(3, "Withdrawal");

    int code;
    String label;

    //★ Point 1
    public String getName() {
        return name();

** ★ Point 1 ** The enum has a method called name (), but we want to access it as a getter, so we define a wrapped getName () method. This is a measure to use enum in JSP.

3. Form class definition

Defines a Form class that stores the input data.


public class DemoForm implements Serializable {

    //★ Point 2
    Status status;

    // ommited

** ★ Point 2 ** Define the defined enum as a field as it is. You don't have to receive it as an int code or a String label. Since enum is a data type, this field will always be Status. Since I want to make it a required item, I added the @NotNull annotation of Bean Validation.

4. JSP that outputs a list box with enum

Create a JSP that outputs a list box with enum, which is the point of this article. Use the standard JSP function and spring function (<form: xxx /> is a spring tag).

JSP that outputs a list box with enum

<%--★ Point 3--%>
<%@ page import="com.example.demo.Status" %>


<%--★ Point 4--%>
<form:errors path="status"/>
<form:select path="status" items="${Status.values()}" itemLabel="label" itemValue="name" />

** ★ Point 3 ** Since I want to refer to Status in JSP, import the class with<% @ page import = "fqcn"%>. I often saw it in the days when JSP was written in scriptlets, but I don't see it much these days, but it is a standard function of JSP.

** ★ Point 4 ** Output the list box using the <form: select /> tag of spring. Since there are many attributes, each is explained below.

attribute Description
path Specify the corresponding field name of the Form class. This timestatusWill be.
items Specify the collection or array that stores the data to be displayed in the list box.
Here of enumvalue()The point is to call a static method. This method returns an array of enums.
Now you can display 3 items of enum.
★ At point 3StatusI imported this to call this static method.
itemLabel Specify the field to be used for the display item of the list box.
This time Statusoflabelフィールドを表示したいofでlabelIs specified.
itemValue Specify the field to be used for the value of the list box.
codeI want to, but herenameThe point is to specify.

Since the getter will be called when rendering, it was defined in ★ Point 1.getName()The method will be called.

5. HTML of the output list box

The HTML of the output list box is shown below. The value attribute of<option>is set to name of enum, and the display item is set to label. If value matches the name defined in the `Statusʻenum, it can be bound to the Form class without any special processing.

Output HTML (add line breaks for readability)

<select id="status" name="status">
  <option value="APPROVAL">Approval</option>
  <option value="DENIAL">Denial</option>
  <option value="WITHDRAWAL">Withdrawal</option>

If you set value to a value not defined in enum (here HOGE), a Type Mismatch error will occur as shown below. It occurs when the HTML form is tampered with and an invalid value is set for value, or when the code field is mistakenly set at ʻitemValue` at point 4.

When HTTP request is made with a value that cannot be converted

Failed to convert property value of type java.lang.String to required type com.example.demo.Status for property status; 
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] 
to type [com.example.demo.Status] for value HOGE; nested exception is java.lang.IllegalArgumentException: No enum constant com.example.demo.Status.HOGE

** As you can see from the explanation so far, by using enum in JSP, type safe of enum is applied when it is set in Form without preparing special input check. ** **

6. JSP that outputs a checkbox with enum

Change the Form class to an array so that you can select multiple forms.


public class DemoForm implements Serializable {

    @Size(min = 1, max = 3)
    Status[] status;
    // ommited

I used the <form: select /> tag when outputting the list box, but I used the <form: checkboxes /> tag for the checkbox. Please note that there is also a <form: checkbox /> tag that outputs one checkbox.

JSP that outputs a checkbox with enum

<%--★ Point 5--%>
<form:errors path="status"/>
  <form:checkboxes path="status" items="${Status.values()}" 
      itemLabel="label" itemValue="name" element="li" />

** ★ Point 5 ** Describes the ʻelementattribute, which is different from the list box. Set this if you want to specify the HTML element that wraps the output checkbox. This time, I setli to make it a list format using <ul> <li>.

7. HTML of the output checkbox

The HTML of the output checkbox is shown below. The checkbox input form is wrapped in a <li> tag.

Output HTML (add line breaks for readability)

  <li><input id="status1" name="status" type="checkbox" value="APPROVAL"/><label for="status1">Approval</label></li>
  <li><input id="status2" name="status" type="checkbox" value="DENIAL"/><label for="status2">Denial</label></li>
  <li><input id="status3" name="status" type="checkbox" value="WITHDRAWAL"/><label for="status3">Withdrawal</label></li>
  <input type="hidden" name="_status" value="on"/>

8. Finally

This time, I explained how to easily display list boxes and checkboxes by using the enum in JSP. With this method, even if you change the definition of enum, neither JSP nor Form need to be modified. It is necessary to take measures to define the getName () method when defining the enum, but I was able to easily bind the input value of the form to the enum without implementing any special processing. Please try using enum in JSP.

Recommended Posts

Super easy way to use enum with JSP
Easy way to create JSP custom tags
[Rails] How to use enum
[Rails] How to use enum
Easy to use array.map (&: method)
How to use scope (JSP & Servlet)
Function is very easy to use
[Swift] Another way to use Result?
[Rails] Easy way to check columns
How to use mssql-tools with alpine
Easy to use Cloud Firestore (Android)
How to use Java enum type
An easy way to cache method calls with Ruby's native extensions
Easy way to create an original logo for your application (easy with your smartphone)
Easy way to set iOS app icon
How to blur an image (super easy)
How to use BootStrap with Play Framework
[Rails] How to use rails console with docker
I want to use DBViewer with Eclipse 2018-12! !!
[Swift] Easy to implement modal with PanModal
Use Spring Security JSP tags with FreeMarker
[Rails] Enum is easier to use! Enumelize!
Easy to trip with Java regular expressions
How to use ToolBar with super margin Part1 Set characters and change colors
Make Firebase Analytics simple and easy to use with the Singleton and Builder patterns
How to use Swift's Codable Super personal memo
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
Easy way to create an implementation of java.util.stream.Stream
How to use built-in h2db with spring boot
You use context to use MDC with Spring WebFlux
How to use Java framework with AWS Lambda! ??
Note how to use Swift super basic TableView
I want to use java8 forEach with index
How to use Java API with lambda expression
One way to redirect_to with parameters in rails
How to use nfs protocol version 2 with ubuntu 18.04
How to use docker compose with NVIDIA Jetson
How to use nginx-ingress-controller with Docker for Mac
Easy to make LINE BOT with Java Servlet
[For super beginners] How to use autofocus: true
Easy to display hello world with Rails + Docker
When importing CSV with Rails, it was really easy to use the nkf command
How to use Oracle JDK 9 EA with Travis CI
Considering a property editor to use with SpringToolSuite (STS)
How to use Z3 library in Scala with Eclipse
If you want to use Mockito with Kotlin, use mockito-kotlin
How to use JDD library in Scala with Eclipse
How to use RealSense with ubuntu 20.04 and ROS Noetic
How to use GitHub for super beginners (team development)