Tuesday, January 28, 2020

Creating a Maven Project in Eclipse

This tutorial shows how to create a Maven project in Eclipse. Here I am using the maven Eclipse plugin. These days Eclipse comes pre-configured with maven plugin and you don't need to download and set up maven plugin yourself. To verify that you have maven plugin pre-configured in eclipse go to Windows - Preferences, there on the left side scrollable window search for Maven, if you have maven then it will look like this.

maven project in eclipse

Creating Maven project structure in Eclipse

In Eclipse select File - New - Maven Project

That will open a Wizard for creating “New Maven Project”, check “Create a simple project (skip archetype selection)”. Click Next.

Maven project eclipse

In the next window provide group ID and artifact ID and other details.

  • groupId- This element indicates the unique identifier of the organization or group that created the project. GroupId is typically based on the fully qualified domain name of your organization. For example com.companyName.finance is the designated groupId for all finanace related projects.
  • artifactId- This element indicates the unique base name of the primary artifact being generated by this project. The primary artifact for a project is typically a JAR file. A typical artifact produced by Maven would have the form -. (for example, myapp-1.0.jar).
  • packaging- This element indicates the package type to be used by this artifact (e.g. JAR, WAR, EAR, etc.). The default value for the packaging element is JAR so you do not have to specify this for most projects.
  • version- This element indicates the version of the artifact generated by the project.
  • name- This element indicates the display name used for the project. This is often used in Maven's generated documentation.
  • description- This element provides a basic description of your project. This is often used in Maven's generated documentation.
Maven project in Eclipse

Click Finish. You should get a project structure similar to as shown below.

By default JRE system library is Java 5 to change it to current Java version you can go to Java build path and change the JRE library.

That's all for this topic Creating a Maven Project in Eclipse. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Spring Example Program Using XML Configuration
  2. Spring Example Program Using JavaConfig And Annotations
  3. Spring Example Program Using Automatic Configuration
  4. Autowiring Using Annotations in Spring
  5. How to Pass Command Line Arguments in Eclipse

You may also like-

  1. Encapsulation in Java
  2. interface default methods in Java 8
  3. Difference between abstract class and interface
  4. How to sort an ArrayList in descending order
  5. CountDownLatch in Java concurrency
  6. Check if given strings are anagram or not
  7. How to add double quotes to a String
  8. Insert\Update Using NamedParameterJDBCTemplate in Spring Framework

Thursday, January 16, 2020

Named Tuple in Python

In this post we’ll see what are named tuples in Python and how to use them.

In a tuple you can store arbitrary elements and access them using index. Now, consider the scenario where tuple is storing a lots of fields, remembering field ordering and accessing them using index becomes quite a task and it is also less readable. In such scenarios named tuple is handy.


Python named tuple

A named tuple is a custom tuple data type which provides ability to refer the items in the tuple by both item names as well as by index position.

A named tuple is similar to plain tuple providing the same performance and the immutability feature.

Creating named tuple

To create a named tuple you need to import named tuple from the Collections module.

from collections import namedtuple

Here namedtuple() is a factory function that returns a tuple class.

Syntax for creating named tuple

namedtuple(typename, field_names)

Here typename is the name of the new tuple subclass which is used to create tuple-like objects.

field_names represent fields which are stored in the named tuple. They can be provied as a sequence of strings like ['field1', 'field2'] or as a single string with each fieldname separated by whitespace and/or commas, for example 'field1 field2' or 'field1', 'field2'.

For example-

Employee = namedtuple('Employee',['id', 'name','age'])

Here named tuple Employee is created which can store field id, name and age.

You can also provide fieldnames as a single string separated by white space.

Employee = namedtuple('Employee', 'id name age')

Python named tuple example

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
e2 = Employee('124', 'Lisa', '31')

# Access using index
print('Employee Age', e1[2])

# Access using field name
print('Employee Name', e2.name)

#iterating
for emp in [e1, e2]:
  print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Lisa
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

Use cases for named tuple usage

1. You have a list in Python that stores objects of same type. Rather than creating a class with the fields and then creating objects of that class and storing them in the list you can create a named tuple which is much easier to create.

Here is the same example as above but uses list to store named tuples.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')
#list
employees = []
# storing named tuples
employees.append(Employee('123', 'Joe', '28'))
employees.append(Employee('124', 'Lisa', '31'))

# Access using index
print('Employee Age', employees[0][2])

# Access using field name
print('Employee Name', employees[0].name)

# iterate list
for emp in employees:
    print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Joe
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

2. You have a CSV file with a record structure. You can create a similar record structure using named tuple and read records into named tuple directly.

import csv
from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

for emp in map(Employee._make, csv.reader(open("F:\\NETJS\\employee.csv", "r"))):
    print(emp.id, emp.name, emp.age)

Here note that _make method of the named tuple is used which is a class method that makes a new instance from an existing sequence or iterable.

Methods in named tuple

In addition to the methods inherited from tuples, named tuples support three additional methods.

1. _make(iterable)- Class method that makes a new instance from an existing sequence or iterable. We have already seen an example of this method.

2. _asdict()- Return a new dict which maps field names to their corresponding values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
print(e1._asdict())

Output

OrderedDict([('id', '123'), ('name', 'Joe'), ('age', '28')])

3. _replace(**kwargs)- Return a new instance of the named tuple replacing specified fields with new values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', 28)
print(e1)
print(e1._replace(age=30))

Output

Employee(id='123', name='Joe', age=28)
Employee(id='123', name='Joe', age=30)

That's all for this topic Named Tuple in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Concatenating Lists in Python
  2. List Comprehension in Python With Examples
  3. Class And Object in Python
  4. Passing Object of The Class as Parameter in Python
  5. Abstraction in Python

You may also like-

  1. Ternary Operator in Python
  2. Check if String Present in Another String in Python
  3. User-defined Exceptions in Python
  4. Convert String to int in Python
  5. ReentrantLock in Java Concurrency
  6. How HashMap Works Internally in Java
  7. Generics in Java
  8. Array in Java With Examples

Monday, January 6, 2020

Spring MVC Configuring Multiple View Resolvers Example

In this post we’ll see how to configure multiple view resolvers with in Spring MVC application. In Spring MVC view resolver is used to resolve the view name without actually hardcoding the view file. That way you are not tightly coupled with a specific view technology.

Spring MVC framework also provides the flexibility to configure more than one view resolver.

Technologies used

Following is the list of tools used for this Spring MVC configuring multiple view resolvers example.

  • Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  • Java 10
  • Tomcat server V 9.0.10
  • Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)

Spring MVC Project structure using Maven


Spring MVC configuring multiple view resolvers example

In this example we’ll configure three different view resolvers in our Spring MVC application to show multiple view resolvers in action. We’ll show both ways of configuration – XML configuration and Java Config.

Three View resolvers that are configured in the Spring MVC application are the following ones-

  • BeanNameViewResolver- A simple implementation of ViewResolver that interprets a view name as a bean name in the current application context.
  • ResourceBundleViewResolver- Implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified by the bundle base name, and for each view it is supposed to resolve, it uses the value of the property [viewname].(class) as the view class and the value of the property [viewname].url as the view url.
  • InternalResourceViewResolver- A subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and TilesView.

Spring MVC configuring multiple view resolvers – XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
        
     <mvc:annotation-driven />
     <!-- <mvc:annotation-driven validator="validator"/> -->
     <context:component-scan base-package="org.netjs.controller" />
     <bean id="BeanViewResolver" class=
        "org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="0"/>
     </bean>
     <bean id="ResourceResolver" class=
        "org.springframework.web.servlet.view.ResourceBundleViewResolver">
         <property name="order" value="1"/>
        <property name="basename" value="views"/>
    </bean>
     <bean id="JSPViewResolver" class=
        "org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2"/>
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean name="beanView" class="org.netjs.config.CustomView" />
</beans>

BeanNameViewResolver Spring configuration

Since BeanNameViewResolver interprets a view name as a bean name in the application context that is why there is this bean definition-

<bean name="beanView" class="org.netjs.config.CustomView" />

Corresponding handler method in the Controller class is as follows-

 @RequestMapping(value = "/showMsg", method = RequestMethod.GET)
 public String showMessage(Model model) throws Exception{
  model.addAttribute("msg", "Configuring multiple view resolver example");
  return "beanView";
 }

From the handler method view name is returned as “beanView” which means View for this handler method resolves to CustomView class.

CustomView class

CustomView class implements View interface and provides implementation of the render() method which is used to render view.

public class CustomView implements View {
    
  @Override
  public void render(Map<String, ?> model, HttpServletRequest request, 
          HttpServletResponse response) throws Exception {
    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.println("This is a custom view for BeanNameViewResolver <br />");
    writer.print("<b>Message- </b>" + model.get("msg"));
  }
}

ResourceBundleViewResolver Spring configuration

For ResourceBundleViewResolver bean “basename” property has the value views which means properties file is named views.properties file.

views.properties

msg.(class)=org.springframework.web.servlet.view.JstlView
msg.url=/WEB-INF/jsp/message.jsp

Here view URL is “/WEB-INF/jsp/message.jsp” so a JSP with the same name should be present at that location.

Corresponding handler method in the Controller class is as follows-

 @RequestMapping(value = "/showResource", method = RequestMethod.GET)
 public String showResource(Model model) throws Exception{
  model.addAttribute("msg", "Configuring ResourceBundleViewResolver example");
  return "msg";
 }

From the handler method, view name is returned as “msg” which is found in the views.properties file.

message.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC ResourceBundle view</title>
</head>
<body>
<h3>Spring MVC configuring multiple resolvers example</h3>
<b>Message</b> - <span>${msg}</span>
</body>
</html>

InternalResourceViewResolver Spring configuration

Another view resolver InternalResourceViewResolver is used to resolve the view name to JSPs.

Corresponding handler method in the Controller class is as follows-

 @RequestMapping(value = "/showUser", method = RequestMethod.GET)
 public String showUser(Model model) throws Exception{
  User user = new User("Leonard", "Nemoy", "ln@st.com");
  model.addAttribute("user", user);
  return "user";
 }

From the handler method, view name is returned as “user” which resolves to the JSP /WEB-INF/jsp/user.jsp

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - User</title>
</head>
<body>
  <table>
    <tr>
      <td><b>First Name</b> - <span>${user.firstName}</span></td>
    </tr>
    <tr>
      <td><b>Last Name</b> - <span>${user.lastName}</span></td>
    </tr>
    <tr>
      <td><b>Email</b> - <span>${user.email}</span></td>    
    </tr>
  </table>
</body>
</html>

Model class – User.java

public class User {

 private String firstName;
 private String lastName;
 private String email;

 public User() {
  
 }
 public User(String firstName, String lastName, String email) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
 }
 
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
}

Spring MVC configuring multiple view resolvers – Controller class

Here is the full controller class.

@Controller
public class MultiViewController {
 @RequestMapping(value = "/showMsg", method = RequestMethod.GET)
 public String showMessage(Model model) throws Exception{
  model.addAttribute("msg", "Configuring multiple view resolver example");
  return "beanView";
 }
 
 @RequestMapping(value = "/showUser", method = RequestMethod.GET)
 public String showUser(Model model) throws Exception{
  User user = new User("Leonard", "Nemoy", "ln@st.com");
  model.addAttribute("user", user);
  return "user";
 }
 
 @RequestMapping(value = "/showResource", method = RequestMethod.GET)
 public String showResource(Model model) throws Exception{
  model.addAttribute("msg", "Configuring ResourceBundleViewResolver example");
  return "msg";
 }
}

Spring MVC configuring multiple view resolvers – Java configuration

If you are using Java configuration then same configuration as seen above using XML configuration can be written as following-

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="org.netjs.controller")
public class WebConfig implements WebMvcConfigurer {
 
 @Bean
 public ViewResolver viewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/jsp/");
  resolver.setSuffix(".jsp");
  resolver.setOrder(3);
  return resolver;
 }
 @Bean
 public ViewResolver resourceResolver() {
  ResourceBundleViewResolver resourceResolver = new ResourceBundleViewResolver();
  resourceResolver.setBasename("views");
  resourceResolver.setOrder(2);
  return resourceResolver;
 }
 
 @Bean
 public ViewResolver beanViewResolver() {
  BeanNameViewResolver beanResolver = new BeanNameViewResolver();
  beanResolver.setOrder(1);
  return beanResolver;
 }
 @Bean("beanView")
 public View customView() {
  return new CustomView();
 }
 /**
  * Configure a handler to delegate unhandled requests by forwarding to the
  * Servlet container's "default" servlet. A common use case for this is when
  * the {@link DispatcherServlet} is mapped to "/" thus overriding the
  * Servlet container's default handling of static resources.
  */
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  configurer.enable();
 }
 
}

Setting order property for resolvers

Here note that the Resolvers have a property order set too which decides the priority. Lower order value means higher priority. Here BeanNameViewResolver has order property set as 0 which means Spring framework will first try to resolve view using this class.

As a rule InternalResourceViewResolver should always have higher order among all view resolvers value because it will always be resolved to view irrespective of value returned giving no chance to any other Resolver class.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed as shown below-

For BeanNameViewResolver (http://localhost:8080/spring-mvc/showMsg)

Spring MVC Configuring Multiple View Resolvers

For ResourceBundleViewResolver (http://localhost:8080/spring-mvc/showResource)

Configuring Multiple View Resolvers

For InternalResourceViewResolver (http://localhost:8080/spring-mvc/showUser)

Configuring Multiple View Resolvers in Spring MVC

That's all for this topic Spring MVC Configuring Multiple View Resolvers Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC PDF Generation Example
  2. Spring MVC Generate Response as JSON Example
  3. Spring MVC Form Example With Bean Validation
  4. Difference Between @Controller And @RestController Annotations in Spring
  5. Spring Batch Processing With List of Objects in batchUpdate() Method

You may also like-

  1. Select Query Using NamedParameterJDBCTemplate in Spring Framework
  2. Wiring Collections in Spring
  3. How to Inject Null And Empty String Values in Spring
  4. Bean Definition Inheritance in Spring
  5. Difference Between ArrayList And CopyOnWriteArrayList in Java
  6. Phaser in Java Concurrency
  7. Difference Between Encapsulation And Abstraction in Java
  8. Java Lambda Expression Comparator Example

Sunday, January 5, 2020

Spring MVC Dropdown Example Using Select, Option And Options Tag

In this post we’ll see how to show dropdown box in a Spring MVC application using select, option and options tag provided by the form tag library in the Spring MVC framework.

Spring MVC Project structure using Maven


<form:select> tag in Spring MVC

This tag renders an HTML 'select' element. It supports data binding using the "items" property. Select tag also supports use of nested option and options tag.

The items attribute is typically populated with a collection or array of item objects. If itemValue and itemLabel attributes are specified then these attributes refer to the bean properties of those item objects otherwise the item objects value itself is used. You can also specify a Map of items, in which case the map keys are interpreted as option values and the map values correspond to option labels. If itemValue and/or itemLabel happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value.

One advantage of using select tag is that it has an attribute multiple when set to true you can select multiple values from the list box. One drawback of using only select tag is that you can’t give any display only value like “-please select-” for that you’ll have to use option tag.

Spring MVC dropdown example using select tag

For the Spring MVC form dropwdown example let’s assume there is a class UserPreferences that stores the selected value of the dropdowns. There are two set of dropdowns in the JSP and there are two properties in the UserPreferences bean class to store the selected options.

Spring MVC dropdown example – Model Class

public class UserPreferences {

 private String exercise;
 private String country;
 public String getExercise() {
  return exercise;
 }
 public void setExercise(String exercise) {
  this.exercise = exercise;
 }
 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }
}

Spring MVC dropdown example using select tag – View

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC dropdown example using select tag</title>
</head>
<body>
  <h3>Spring MVC dropdown example using select tag</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Country:</b></td>      
        <td><form:select path="country" items="${countryOptions}"/></td>
      </tr>
      <tr>
        <td><b>Favorite Exercise:</b></td>        
        <td><form:select path="exercise" items="${exerciseList}" multiple="true"/></td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

As you can see <form:select> tag is used with the items property. The values used with the items property in the JSP countryOptions and exerciseList should be available as a model attribute containing String of values to be shown in the dropdown.

With one of the <form:select> tag multiple attribute set as true is also used. This will enable multiple selections.

There is another JSP that is used to display the values selected in the dropdown and listbox.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>User Preferences</title>
</head>
<body>
<h3>Spring MVC dropdown example using select tag</h3>
Country: ${preferences.country}<br/>
Favorite exercise: ${preferences.exercise}

</body>
</html>

Spring MVC dropdown example – Controller class

public class UserController {
    
  @RequestMapping(value = "/showUser", method = RequestMethod.GET)
  public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    // Default Value for country dropdown
    pref.setCountry("IN");
  
    // Preparing values for "Country" Dropdown
    Map<String, String> countryMap = new HashMap<>();
    countryMap.put("AR", "Argentina");
    countryMap.put("IN", "India");
    countryMap.put("JP", "Japan");
    countryMap.put("US", "United States");
    countryMap.put("SG", "Singapore");
    model.addAttribute("countryOptions", countryMap);
    model.addAttribute("preferences", pref);
    return "user";
  }
    
  @RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
  public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
    model.addAttribute("preferences", preferences);
    return "showPreferences";
  }
    
  // List for "Favorite Exercise" dropdown
  @ModelAttribute("exerciseList")
  public List<String> getExerciseList(){
    List<String> exerciseList = new ArrayList<>();
    exerciseList.add("Aerobic");
    exerciseList.add("Anaerobic");
    exerciseList.add("Flexibility Trng");
    return exerciseList;
  }
}

In the Controller class, showUser() method is used to handle the /showUser request path. Method returns the view name as “user” which resolves to /WEB-INF/jsp/user.jsp JSP.

As you can see exerciseList and countryOptions which are used in the JSP to show dropdown options are set here as model attribute. Default value is also set for one of the dropdown so that the value is pre-selected in the JSP.

Another handler method showPreferences() handles the request when submit button is clicked in the user.jsp.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC dropdown using select tag

As you can see India is already selected as the property was set in the bean object. Since multiple attribute is set as true for the other select tag so multiple values can be selected. Clicking the submit button displays the selected values.

Spring MVC dropdown example

<form:option> tag in Spring MVC

This tag renders an HTML 'option'. If you want to hardcode dropdown values with in the JSP itself then you can use option tag.

Spring MVC dropdown example using option tag

If we have to create the same view using option tag as created above using the select tag where there are two drop downs and one of them is rendered as a listbox by using multiple=”true” attribute. In this case dropdown options are hardcoded with in the JSP itself.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC dropdown example using option tag</title>
</head>
<body>
  <h3>Spring MVC dropdown example using option tag</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Country:</b></td>      
        <td>
            <form:select path="country">
              <form:option value="AR" label="Argentina"/>
              <form:option value="IN" label="India"/>
              <form:option value="JP" label="Japan"/>
              <form:option value="US" label="United States"/>
              <form:option value="SG" label="Singapore"/>
            </form:select>
        </td>
      </tr>
      <tr>
        <td><b>Favorite Exercise:</b></td>
        <td>
          <form:select path="exercise" multiple="true">
            <form:option value="Aerobic"/>
            <form:option value="Anaerobic"/>
            <form:option value="Flexibility Trng"/>
          </form:select>
        </td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

<form:options> tag in Spring MVC

This tag renders a list of HTML 'option' tags. Options tag also let you provide options at run time rather than hardcoding them. You pass in an Array, a List or a Map containing the available options in the "items" property.

Spring MVC dropdown example using options tag

In this example Model class and Controller class are the same as used above.

User.jsp with changes for options tag is as below.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC dropdown example using select tag</title>
</head>
<body>
  <h3>Spring MVC dropdown example using select tag</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Country:</b></td>
    
        <td>
          <form:select path="country">
            <form:option value="-" label="-Please Select-"/>
            <form:options items="${countryOptions}"/>            
          </form:select>
        </td>
      </tr>
      <tr>
        <td><b>Favorite Exercise:</b></td>
        <td>
          <form:select path="exercise" multiple="true">
            <form:options items="${exerciseList}"/>    
          </form:select>
        </td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC dropdown using options tag

Now no default value is set in the Controller class so first option “Please Select” is displayed. Since multiple is set as true for the other select tag so multiple values can be selected.

After selecting some values.

Showing the selected values once submit button is clicked.

Spring MVC dropdown

Reference- https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib

That's all for this topic Spring MVC Dropdown Example Using Select, Option And Options Tag. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Checkbox And Checkboxes Form Tag Example
  2. Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation
  3. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  4. Spring MVC Generate Response as JSON Example
  5. Spring Transaction Management JDBC Example Using @Transactional Annotation

You may also like-

  1. Difference Between @Controller And @RestController Annotations in Spring
  2. Insert\Update Using JDBCTemplate in Spring Framework
  3. Spring Bean Life Cycle
  4. How to Read Properties File in Spring Framework
  5. Java Collections Interview Questions
  6. How to Sort ArrayList in Java
  7. static Method Overloading or Overriding in Java
  8. How to Untar a File - Java Program

Saturday, January 4, 2020

Spring MVC Radiobutton And Radiobuttons Form Tag Example

In this post we’ll see how to use radiobutton and radiobuttons tag provided by the form tag library in the Spring MVC framework.

Spring MVC Project structure using Maven


<form:radiobutton> and <form:radiobuttons> tags in Spring MVC

  • <form:radiobutton>- This tag renders an HTML 'input' tag with type 'radio'. With this tag the values for the radio button are hardcoded with in the JSP page. You will have multiple radiobutton tag instances bound to the same property but with different values.
  • <form:radiobuttons>- If you don't want to harcode the values for the radiobutton in the JSP but want to pass available options at runtime then you can use radiobuttons tag.

In this post we’ll see example using both <form:radiobutton> and <form:radiobuttons> one by one.

Spring MVC radiobutton example

For the Spring MVC form radiobutton tag example let’s assume there is a class UserPreferences that stores the radio button value. There are two set of radiobuttons in the JSP and there are two properties in the UserPreferences bean class to store the selected option.

Spring MVC radiobutton example – Model Class

public class UserPreferences {

 private String exercise;
 private String sex;
 public String getExercise() {
  return exercise;
 }
 public void setExercise(String exercise) {
  this.exercise = exercise;
 }
 public String getSex() {
  return sex;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
}

Spring MVC radiobutton example – View

There is a JSP (user.jsp) that has two sets of radiobutton tag with options for user to select.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC radiobutton example in form tag</title>
</head>
<body>
<h3>Spring MVC radio button example</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Sex:</b></td>
        <td>
          <form:radiobutton path="sex" value="M"/>Male
          <form:radiobutton path="sex" value="F"/>Female
          <form:radiobutton path="sex" value="O"/>Other
        </td>
      </tr>
      <tr>
        <td><b>Favorite Exercise:</b></td>
        <td>
          <form:radiobutton path="exercise" value="Aerobic"/>Aerobic
          <form:radiobutton path="exercise" value="Anaerobic"/>Anaerobic
          <form:radiobutton path="exercise" value="Flexibility Trng"/>Flexibility Training
        </td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

The values for the properties are taken from an object of type UserPreferences bean which is bound using the attribute “modelAttribute” with in the form tag. The object is set with in the handler method of the Controller class.

There is another JSP that is used to display the selected radio button option.

showPreferences.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>User Preferences</title>
</head>
<body>
<h3>Spring MVC radio button example</h3>
Sex: ${preferences.sex}<br/>
Favorite exercise: ${preferences.exercise}
</body>
</html>

Spring MVC radiobutton example – Controller class

import org.netjs.model.UserPreferences;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {
    
  @RequestMapping(value = "/showUser", method = RequestMethod.GET)
  public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    // Setting default values
    pref.setSex("M");
    pref.setExercise("Anaerobic");
    model.addAttribute("preferences", pref);
    return "user";
  }
    
  @RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
  public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
    model.addAttribute("preferences", preferences);
    return "showPreferences";
  }
}

In the Controller class, showUser() method is used to handle the /showUser request path. Method returns the view name as “user” which resolves to /WEB-INF/jsp/user.jsp JSP.

In the handler method object of UserPreferences class is set to the Model which is used in the JSP to bind the bean properties with the radio button. If you want any radio button option to be selected by default in JSP then you can set the values for the properties in the UserPreferences object.

Another handler method showPreferences() handles the request when submit button is clicked in the user.jsp.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC radiobutton tag

Page which shows the selected options.

Spring form tag library radiobutton tag

Spring MVC radiobuttons tag example

If you want to provide the options for the radiobutton at runtime rather than hardcoding them then you can use radiobuttons tag in Spring MVC application. You pass in an Array, a List or a Map containing the available options in the "items" property.

Spring MVC radiobuttons tag example – Model Class

public class UserPreferences {

 private String exercise;
 private String sex;
 public String getExercise() {
  return exercise;
 }
 public void setExercise(String exercise) {
  this.exercise = exercise;
 }
 public String getSex() {
  return sex;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
}

Spring MVC radiobuttons example – Views

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC radiobuttons example in form tag</title>
</head>
<body>
<h3>Spring MVC radio buttons example</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Sex:</b></td>
        <td><form:radiobuttons path="sex" items="${sexOptions}"/></td>
      </tr>
      <tr>
        <td><b>Favorite Exercise:</b></td>
        <td><form:radiobuttons path="exercise" items="${exerciseList}"/></td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

As you can see now <form:radiobuttons> tag is used with the items property. The values used with the items property in the JSP sexOptions and exerciseList should be available as a model attribute containing String of values to be selected from. If a Map is used, the map entry key will be used as the value and the map entry’s value will be used as the label to be displayed.

There is another JSP that is used to display the selected radio button option.

showPreferences.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>User Preferences</title>
</head>
<body>
<h3>Spring MVC radio buttons example</h3>
Sex: ${preferences.sex}<br/>
Favorite exercise: ${preferences.exercise}

</body>
</html>

Spring MVC radiobuttons example – Controller class

@Controller
public class UserController {
    
  @RequestMapping(value = "/showUser", method = RequestMethod.GET)
  public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    // Default Values
    pref.setSex("F");
    pref.setExercise("Flexibility Trng");
    
    // Preparing values for "Sex Options" radio button
    Map<String, String> sexOptions = new HashMap<>();
    sexOptions.put("M", "Male");
    sexOptions.put("F", "Female");
    sexOptions.put("O", "Other");
    model.addAttribute("sexOptions", sexOptions);
    model.addAttribute("preferences", pref);
    return "user";
  }

  @RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
  public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
    model.addAttribute("preferences", preferences);
    return "showPreferences";
  }
    
  // List for "Favorite Exercise" radio button
  @ModelAttribute("exerciseList")
  public List<String> getExerciseList(){
    List<String> exerciseList = new ArrayList<>();
    exerciseList.add("Aerobic");
    exerciseList.add("Anaerobic");
    exerciseList.add("Flexibility Trng");
    return exerciseList;
  }
}

As you can see exerciseList and sexOptions which are used in the JSP to show radiobutton options are set here as model attribute. Default values for the radio buttons are also set here to be pre-selected.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC radiobuttons tag

Changed the default options before clicking on submit

Spring form tag library radiobuttons tag

Page which shows the selected radio button options.

Spring MVC radiobuttons example

Reference- https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib

That's all for this topic Spring MVC Radiobutton And Radiobuttons Form Tag Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Checkbox And Checkboxes Form Tag Example
  2. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  3. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  4. Spring MVC Excel Generation Example
  5. Spring Batch Processing Using JDBCTemplate batchUpdate() Method

You may also like-

  1. registerShutdownHook() Method in Spring Framework
  2. Bean Definition Inheritance in Spring
  3. Excluding Bean From Autowiring in Spring
  4. Using Conditional Annotation in Spring Framework
  5. How LinkedList Class Works Internally in Java
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. BigDecimal in Java
  8. Converting double to int - Java Program

Friday, January 3, 2020

Spring MVC Checkbox And Checkboxes Form Tag Example

In this post we’ll see how to use checkbox and checkboxes provided by the form tag in the Spring MVC framework.

Technologies used

Following is the list of tools used for the Spring MVC checkbox and checkboxes form tag example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. JSTL tag library
  4. Tomcat server V 9.0.10
  5. Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring dependencies following dependency is also needed in the pom.xml for JSTL tags.

<!-- For JSTL tags -->
<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

<form:checkbox> and <form:checkboxes> tags in Spring MVC

  • <form:checkbox>- This tag renders an HTML 'input' tag with type 'checkbox'. With this tag the value for the checkbox is hardcoded with in the JSP page.
  • <form:checkboxes>- This tag renders multiple HTML 'input' tags with type 'checkbox'. If you don't want to list the value for the checkbox with in the JSP but want to provide a list of available options at runtime and pass that in to the tag then you can use checkboxes tag. You pass in an Array, a List or a Map containing the available options in the "items" property.

Spring MVC checkbox example

For the Spring MVC form checkbox example let’s assume there is a class UserPreferences which is used to list out preferences as check boxes in the JSP page.

Spring MVC checkbox example – Model Class

public class UserPreferences {
 private boolean receiveNewsletter;
 private String[] cardioExercises;
 private String favouriteFood;
 public boolean isReceiveNewsletter() {
  return receiveNewsletter;
 }
 public void setReceiveNewsletter(boolean receiveNewsletter) {
  this.receiveNewsletter = receiveNewsletter;
 }
 public String[] getCardioExercises() {
  return cardioExercises;
 }
 public void setCardioExercises(String[] cardioExercises) {
  this.cardioExercises = cardioExercises;
 }
 public String getFavouriteFood() {
  return favouriteFood;
 }
 public void setFavouriteFood(String favouriteFood) {
  this.favouriteFood = favouriteFood;
 }
}

Spring MVC checkbox example – View

Following JSP (user.jsp) shows all the approaches to the checkbox tag in Spring MVC.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC checkbox example in form tag</title>
</head>
<body>
<form:form method="POST" action="showPreferences" modelAttribute="preferences">
<table>
  <tr>
    <td>Subscribe to newsletter?:</td>
    <!--  Property is of type java.lang.Boolean-->
    <td><form:checkbox path="receiveNewsletter"/></td>
  </tr>
  <tr>
    <td>Favorite cardio exercises:</td>
    <!--  Property is of an array or of type java.util.Collection -->
    <td>Running: <form:checkbox path="cardioExercises" value="Running"/>
    <td>Skipping: <form:checkbox path="cardioExercises" value="Skipping"/>
    <td>Cycling: <form:checkbox path="cardioExercises" value="Cycling"/>
    <td>Burpee: <form:checkbox path="cardioExercises" value="Burpee"/>
  </tr>
  <tr>
    <td>Favourite Food:</td>
    <%-- Property is of type java.lang.Object --%>
    <td>Vegetables: <form:checkbox path="favouriteFood" value="Burger"/></td>
  </tr>
  <tr>
    <td><input type="submit" value="Submit"></td>
  </tr>
</table>
</form:form>
</body>
</html>

The check boxes with in the JSP are checked or left unchecked based on the following-

  • When the bound value is of type java.lang.Boolean, the input(checkbox) is marked as 'checked' if the bound value is true.
  • When the bound value is of type array or java.util.Collection, the input(checkbox) is marked as 'checked' if the configured value is present in the bound Collection.
  • For any other bound value type, the input(checkbox) is marked as 'checked' if the configured setValue(Object) is equal to the bound value.

The values for the properties are taken from an object of type UserPreferences bean which is bound using the attribute “modelAttribute” with in the form tag. The object is set with in the handler method of the Controller class.

There is another JSP that is used to display the values selected by checking the check boxes.

showPreferences.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>User Preferences</title>
</head>
<body>
<table>
  <tr>
    <td>Subscribe to newsletter?:</td>
    <td>${preferences.receiveNewsletter}</td>
  </tr>
  <tr>
    <td>Favorite cardio exercises:</td>
    <c:forEach items="${preferences.cardioExercises}" var="exercise" varStatus="counter">
      <td>${exercise}
        <c:if test="${not counter.last}">
          <c:out value="," ></c:out> 
        </c:if>
      </td>        
    </c:forEach>
  </tr>
  <tr>
    <td>Favourite Food:</td>
    <td>${preferences.favouriteFood}</td>
  </tr>
</table>
</body>
</html>

Spring MVC checkbox example – Configuration changes

Since JSTL tags are also used so you need to configure InternalResourceViewResolver to resolve a JstlView for that following configuration has to be added in the configuration file.

<bean id="JSPViewResolver" class=
    "org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

Spring MVC checkbox example – Controller class

import org.netjs.model.UserPreferences;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {
 
 @RequestMapping(value = "/showUser", method = RequestMethod.GET)
 public String showUser(Model model) throws Exception{
  UserPreferences pref = new UserPreferences(); 
  pref.setReceiveNewsletter(true);
  pref.setCardioExercises(new String[]{"Running", "Burpee"});
  pref.setFavouriteFood("Steamed Vegetables");
  model.addAttribute("preferences", pref);
  return "user";
 }
 
 @RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
 public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
  model.addAttribute("preferences", preferences);
  return "showPreferences";
 }
}

In the Controller class, showUser() method is used to handle the /showUser request path. Method returns the view name as “user” which resolves to /WEB-INF/jsp/user.jsp JSP.

In the handler method object of UserPreferences class is set to the Model which is used in the JSP to mark the check box as checked or leave it unchecked. If you want some of the check boxes to be checked in the JSP by default then you can set the values for the properties in the UserPreferences object.

Another handler method showPreferences() handles the request when submit button is clicked in the user.jsp.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC checkbox example

This is the page with the check boxes marked as checked for the properties set in the handler method of the controller class. In the page some more boxes are checked before clicking on submit button.

Spring MVC form checkbox tag

Page which shows all the values that are checked.

Spring MVC checkboxes tag example

If you want to provide the list of options for the checkbox at runtime rather than hardcoding them then you can add checkboxes tag in Spring MVC application. You pass in an Array, a List or a Map containing the available options in the "items" property.

Spring MVC checkboxes example – Model Class

public class UserPreferences {
  private boolean receiveNewsletter;
  private String[] cardioExercises;
  private List<String> favouriteFood;
  public boolean isReceiveNewsletter() {
    return receiveNewsletter;
  }
  public void setReceiveNewsletter(boolean receiveNewsletter) {
    this.receiveNewsletter = receiveNewsletter;
  }
  public String[] getCardioExercises() {
    return cardioExercises;
  }
  public void setCardioExercises(String[] cardioExercises) {
    this.cardioExercises = cardioExercises;
  }
  public List<String> getFavouriteFood() {
    return favouriteFood;
  }
  public void setFavouriteFood(List<String> favouriteFood) {
    this.favouriteFood = favouriteFood;
  }
}

Spring MVC checkboxes example – Views

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC checkbox example in form tag</title>
</head>
<body>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td>Subscribe to newsletter?:</td>
        <!--  Property is of type java.lang.Boolean-->
        <td><form:checkbox path="receiveNewsletter"/></td>
      </tr>
      <tr>
        <td>Favorite cardio exercises:</td>
        <td><form:checkboxes path="cardioExercises" items="${prefMap}"/></td>
      </tr>
      <tr>
        <td>Favourite Food:</td>
        <td><form:checkboxes path="favouriteFood" items="${foodList}"/></td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

As you can see now <form:checkboxes> tag is used with the items property. The values used with the items property in the JSP prefMap and foodList should be available as a model attribute containing String of values to be selected from. If a Map is used, the map entry key will be used as the value and the map entry’s value will be used as the label to be displayed.

There is another JSP that is used to display the values selected by checking the check boxes.

showPreferences.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>User Preferences</title>
</head>
<body>
Subscribe to newsletter?: ${preferences.receiveNewsletter}
<br/>
Favorite cardio exercises:
<c:forEach items="${preferences.cardioExercises}" var="exercise" varStatus="counter">
    ${exercise}
  <c:if test="${not counter.last}">
         <c:out value="," ></c:out> 
  </c:if>      
</c:forEach>
<br/>
Favourite Food:
<c:forEach items="${preferences.favouriteFood}" var="food" varStatus="foodCounter">
    ${food}
  <c:if test="${not foodCounter.last}">
    <c:out value="," ></c:out> 
  </c:if>         
</c:forEach>
</body>
</html>

Spring MVC checkboxes example – Controller class

@Controller
public class UserController {
    
  @RequestMapping(value = "/showUser", method = RequestMethod.GET)
  public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    //default check values
    pref.setReceiveNewsletter(true);
    pref.setCardioExercises(new String[]{"Running", "Burpee"});
    pref.setFavouriteFood(Arrays.asList("Boiled legumes", "Steamed Vegetables"));
    // Preparing values for "Favorite cardio exercises" check box
    Map<String, String> prefMap = new HashMap<>();
    prefMap.put("Running", "Running");
    prefMap.put("Burpee", "Burpee");
    prefMap.put("Skipping", "Skipping");
    prefMap.put("Cycling", "Cycling");    
    model.addAttribute("prefMap", prefMap);
    model.addAttribute("preferences", pref);
    return "user";
  }
    
  // List for "Favourite Food" check box
  @ModelAttribute("foodList")
  public List<String> getFoodList(){
    List<String> foodList = new ArrayList<>();
    foodList.add("Steamed Vegetables");
    foodList.add("Boiled legumes");
    foodList.add("Pizza");
    foodList.add("Burger");
    return foodList;
  }
        
  @RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
  public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
    model.addAttribute("preferences", preferences);
    return "showPreferences";
  }
}

As you can see prefMap and foodList which are used in the JSP to show options for checkboxes in the JSP are set here as model attribute. If you want some of the check boxes to be checked in the JSP then you can set the values for the properties in the UserPreferences object.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC checkboxes example

This is the page with the check boxes marked as checked for the properties set in the handler method of the controller class.

Page which shows all the values that are checked.

Spring MVC form checkboxes tag

Reference- https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib

That's all for this topic Spring MVC Checkbox And Checkboxes Form Tag Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Web MVC Tutorial
  2. Spring MVC Radiobutton And Radiobuttons Form Tag Example
  3. Spring MVC PDF Generation Example
  4. Spring MVC Generate Response as JSON Example
  5. Spring MVC Form Example With Bean Validation

You may also like-

  1. Connection Pooling With Apache DBCP Spring Example
  2. BeanFactoryAware Interface in Spring Framework
  3. Autodiscovery of Bean Using componenent-scan in Spring
  4. How to Inject Prototype Scoped Bean in Singleton Bean
  5. Volatile in Java
  6. Type Erasure in Java Generics
  7. Searching Within a String Using indexOf(), lastIndexOf() And contains() Methods
  8. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode