Thursday, October 17, 2024

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

Wednesday, October 16, 2024

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 gender;
	
	public String getExercise() {
		return exercise;
	}
	public void setExercise(String exercise) {
		this.exercise = exercise;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
}

Spring MVC radiobutton example – View

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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  <title>Spring MVC tutorial - User</title>
</head>
<body>
<h3>Spring MVC radio button example</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Gender:</b></td>
        <td>
          <form:radiobutton path="gender" value="M"/>Male
          <form:radiobutton path="gender" value="F"/>Female
          <form:radiobutton path="gender" 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=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Preferences</title>
</head>
<body>
  <h3>Spring MVC radio button example</h3>
  Gender: ${preferences.gender}<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 = "/user", method = RequestMethod.GET)
	public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    // Setting default values
    pref.setGender("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/springwebproj/user (As per the web application name used in this example, please change as per your web application)

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 gender;
	
	public String getExercise() {
		return exercise;
	}
	public void setExercise(String exercise) {
		this.exercise = exercise;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
}

Spring MVC radiobuttons example – Views

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  <title>Spring MVC tutorial - User</title>
</head>
<body>
<h3>Spring MVC radio button example</h3>
  <form:form method="POST" action="showPreferences" modelAttribute="preferences">
    <table>
      <tr>
        <td><b>Gender:</b></td>
        <td><form:radiobuttons path="gender" items="${genderOptions}"/></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 genderOptions 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=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Preferences</title>
</head>
<body>
  <h3>Spring MVC radio button example</h3>
  Gender: ${preferences.gender}<br/>
  Favorite exercise: ${preferences.exercise}
</body>
</html>

Spring MVC radiobuttons example – Controller class

@Controller
public class UserController {
    
  @RequestMapping(value = "/user", method = RequestMethod.GET)
  public String showUser(Model model) throws Exception{
    UserPreferences pref = new UserPreferences();    
    // Default Values
    pref.setGender("F");
    pref.setExercise("Flexibility Trng");
    
    // Preparing values for "Sex Options" radio button
    Map<String, String> genderOptions = new HashMap<>();
    genderOptions.put("M", "Male");
    genderOptions.put("F", "Female");
    genderOptions.put("O", "Other");
    model.addAttribute("genderOptions", genderOptions);
    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 genderOptions 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/springwebproj/user

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

Tuesday, October 15, 2024

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 6.1.x Release (Spring core, spring web, spring webmvc).
  2. Java 21
  3. JSTL tag library
  4. Tomcat server V 10.x

Spring MVC Project structure using Maven

Maven Dependencies

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

<dependency>
  <groupId>jakarta.servlet.jsp.jstl</groupId>
  <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>org.glassfish.web</groupId>
  <artifactId>jakarta.servlet.jsp.jstl</artifactId>
  <version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<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 (preferences.jsp) shows all the approaches to the checkbox tag in Spring MVC.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <%@ 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>Raw Vegetables: <form:checkbox path="favouriteFood" value="Raw Vegetables"/></td>
      <td>Steamed Vegetables: <form:checkbox path="favouriteFood" value="Steamed Vegetables"/></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=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<title>User Preferences</title>
</head>
<body>

  <div>
    <span>Subscribe to newsletter?:</span>
    <span>${preferences.receiveNewsletter}</span>
  </div>
  <div>
    <span>Favorite cardio exercises:</span>
    <c:forEach items="${preferences.cardioExercises}" var="exercise" varStatus="counter">
      <span>${exercise}
        <c:if test="${not counter.last}">
          <c:out value="," ></c:out> 
        </c:if>
      </span>        
    </c:forEach>
  </div>
  <div>
    <span>Favourite Food:</span>
    <span>${preferences.favouriteFood}</span>
  </div>
</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.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.netjstech.springweb.model.UserPreferences;

@Controller
public class PreferenceController {
	@GetMapping("/preferences")
	public String showUserPreferences(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 "preferences";
	}
	 
	@RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
	public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
		//System.out.println("In ShowPreferences");
		model.addAttribute("preferences", preferences);
		return "showPreferences";
	}
}

In the Controller class, showUserPreferences() method is used to handle the /preferences request path. Method returns the view name as "preferences" which resolves to /WEB-INF/jsp/preferences.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 preferences.jsp.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/springwebproj/preferences (This is as per my project name- springwebproj)

Spring MVC checkbox example

In the above page it shows those check boxes as checked for which values are set in the handler method of the controller class. In the following 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

preferences.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <%@ 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>
  <div>
    <span>Subscribe to newsletter?:</span>
    <span>${preferences.receiveNewsletter}</span>
  </div>
  <div>
    <span>Favorite cardio exercises:</span>
    <c:forEach items="${preferences.cardioExercises}" var="exercise" varStatus="counter">
        <span>${exercise}
          <c:if test="${not counter.last}">
               <c:out value="," ></c:out> 
          </c:if>
        </span>   
    </c:forEach>
  </div>
  <div>
    <span>Favourite Food:</span>
    <c:forEach items="${preferences.favouriteFood}" var="food" varStatus="foodCounter">
        <span>${food}
        <c:if test="${not foodCounter.last}">
          <c:out value="," ></c:out> 
        </c:if>
        </span>           
    </c:forEach>
  </div>
</body>
</html>

Spring MVC checkboxes example – Controller class

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.netjstech.springweb.model.UserPreferences;

@Controller
public class PreferenceController {
  @GetMapping("/preferences")
  public String showUserPreferences(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 "preferences";
  }
  
  // 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/springwebproj/preferences

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. How to Sort an ArrayList in Descending Order in Java

Monday, October 14, 2024

Statement Interface in Java-JDBC

In the post Java JDBC Steps to Connect to DB we have already seen a complete example using the interfaces Driver, Connection, Statement and ResultSet provided by the JDBC API. In this post we’ll see Java Statement interface in detail.

Statement interface in JDBC

java.sql.Statement interface in JDBC API is used to execute a static SQL statement and returning the result of the executed query.

Statement interface has following two sub-interfaces

  1. PreparedStatement
  2. CallableStatement

PreparedStatement– PreparedStatement object stores the SQL statement in its pre-compiled state. That way it can efficiently execute the same SQL statement multiple times with different parameters.

CallableStatement- This interface is used to execute SQL stored procedures.

You can get a Statement object by calling the Connection.createStatement() method on the Connection object.

Frequently used methods of the Statement interface

Mostly you will use the execute methods of the Java Statement interface to execute queries.

  1. boolean execute(String sql)- Executes the given SQL statement (it can be any kind of SQL query), which may return multiple results.
    Returns a boolean which is true if the first result is a ResultSet object; false if it is an update count or there are no results.
  2. ResultSet executeQuery(String sql)- Executes the given SQL statement, which returns a single ResultSet object. If you want to execute a Select SQL query which returns results you should use this method.
  3. int executeUpdate(String sql)- Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
    Returns an int denoting either the row count for the rows that are inserted, deleted, updated or returns 0 if nothing is returned.
    Note:This method cannot be called on a PreparedStatement or CallableStatement.
  4. int[] executeBatch()- Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

Java Statement example

Let’s see an example where SQL statements are executed using execute(), executeUpdate and executeQuery methods. In the example-

Using execute() method a SQL statement is executed and then the boolean value is checked.

Using executeUpdate() method insert, update and delete statements are executed and row count of the affected rows is displayed.

Using executeQuery() method select statement is executed and the returned ResultSet is processed.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStmt {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
   
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", 
                   "root", "admin");
  
      // creating Statement
      Statement stmt = connection.createStatement();  
            
      /** execute method **/
      boolean flag = stmt.execute("Update Employee set age = 40 where id in (5, 6)");
      if(flag == false){
        System.out.println("Updated rows " + stmt.getUpdateCount() );
      }
            
      /** executeUpdate method **/
      // Insert
      int count = stmt.executeUpdate("Insert into employee(name, age) values('Kim', 23)");
      System.out.println("Rows Inserted " + count);
            
      // update
      count = stmt.executeUpdate("Update Employee set age = 35 where id = 17");
      System.out.println("Rows Updated " + count);
            
      //delete
      count = stmt.executeUpdate("Delete from Employee where id = 5");
      System.out.println("Rows Deleted " + count);
            
      /** executeQuery method **/
      // Executing Query
      ResultSet rs = stmt.executeQuery("Select * from Employee");

      // Processing Resultset
      while(rs.next()){
        System.out.println("id : " + rs.getInt("id") + " Name : " 
          + rs.getString("name") + " Age : " + rs.getInt("age")); 
      }    
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } // if condition
    }// finally
  }
}

Reference: https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/Statement.html

That's all for this topic Statement Interface in Java-JDBC. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Connection Interface in Java-JDBC
  2. Types of JDBC Drivers
  3. CallableStatement Interface in Java-JDBC
  4. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  5. Connection Pooling Using C3P0 in Java

You may also like-

  1. BigInteger in Java With Examples
  2. Nested class and Inner class in Java
  3. Serialization Proxy Pattern in Java
  4. How ArrayList Works Internally in Java
  5. CopyOnWriteArrayList in Java With Examples
  6. Volatile Keyword in Java With Examples
  7. Garbage Collection in Java
  8. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example

Sunday, October 13, 2024

Types of JDBC Drivers

JDBC API standardizes the way any Java application connects to DB. JDBC API is a collection of interfaces and JDBC drivers implement these interfaces in the JDBC API enabling a Java application to interact with a database.

The JDBC driver gives out the connection to the database and implements the protocol for transferring the query and result between client and database.

JDBC Driver Types

JDBC drivers can be categorized into four types.

Saturday, October 12, 2024

ResultSet Interface in Java-JDBC

java.sql.ResultSet interface in JDBC API represents the storage for the data you get by executing a SQL statement that queries the database.

A ResultSet object maintains a cursor pointing at the result data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, it returns false when there are no more rows in the ResultSet object.

Creating and iterating a ResultSet Example

ResultSet rs = stmt.executeQuery("Select * from Employee");
   
// Processing Resultset
while(rs.next()){
 System.out.println("id : " + rs.getInt("id") + " Name : " +  rs.getString("name") + " Age : " + rs.getInt("age")); 
}

By default, ResultSet object is not updatable and has a forward moving cursor only. Thus, you can iterate through it only once and only from the first row to the last row. But ResultSet interface provides parameters that can produce ResultSet objects that are scrollable and/or updatable.

Fields for scrollable ResultSet

ResultSet interface in Java has fields that determine whether ResultSet object will be scrollable or not and will it be sensitive to the changes to the data that is represented by ResultSet or not.

  • TYPE_FORWARD_ONLY- The constant indicating the type for a ResultSet object whose cursor may move only forward.
  • TYPE_SCROLL_INSENSITIVE- The constant indicating the type for a ResultSet object that is scrollable but generally not sensitive to changes to the data that underlies the ResultSet. Which means you can move the cursor to an absolute position or relative to the current cursor position. If the data in the DB is changed by another thread/process that change won’t be reflected in the data stored in the ResultSet.
  • TYPE_SCROLL_SENSITIVE- The constant indicating the type for a ResultSet object that is scrollable and generally sensitive to changes to the data that underlies the ResultSet. Which means you can move the cursor to an absolute position or relative to the current cursor position. If the data in the DB is changed by another thread/process that change is reflected in the data stored in the ResultSet.

Fields for updatable ResultSet

  • CONCUR_READ_ONLY- The constant indicating the concurrency mode for a ResultSet object that may NOT be updated.
  • CONCUR_UPDATABLE- The constant indicating the concurrency mode for a ResultSet object that may be updated.

Java ResultSet interface example

Let’s see an example with scrollable resultset, DB used here is MySql, schema is netjs and table is Employee.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCResultSet {

 public static void main(String[] args) {
  try(Connection connection = DriverManager.getConnection(
      "jdbc:mysql://localhost:3306/netjs", "root", "admin")){
   // creating Statement
   Statement stmt = connection.createStatement(
                           ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);  
   
   // Executing Query
   ResultSet rs = stmt.executeQuery("Select * from Employee");
   System.out.println("Displaying all rows");
   // Processing Resultset
   while(rs.next()){
       System.out.println("id : " + rs.getInt("id") + " Name : " 
        + rs.getString("name") + " Age : " + rs.getInt("age")); 
   }
   // moving to 3rd row
   rs.absolute(3);
   System.out.println("Displaying 3rd row");
   System.out.println("id : " + rs.getInt("id") + " Name : " 
                          + rs.getString("name") + " Age : " + rs.getInt("age")); 
  }catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Displaying all rows
id : 5 Name : Tom Age : 35
id : 6 Name : Tim Age : 20
id : 7 Name : John Age : 25
id : 8 Name : Johnny Age : 35
id : 17 Name : Johnny Age : 65
Displaying 3rd row
id : 7 Name : John Age : 25

Getter Methods in ResultSet

You would have noticed in the examples how appropriate data type getter method is used (i.e. getInt, getString) for retrieving column values from the current row. You can retrieve value using either the index number of the column or the name of the column.

In general, using the column index will be more efficient. Columns are numbered from 1. Drawback is, any alteration in the table structure will mean change in the indexes in the Java code.

Updater methods in ResultSet

There are also updater methods corresponding to the data types which are used when your ResultSet is updatable. Using updater methods you can update the column values then update the row in the DB. Updater methods are used in conjunction with updateRow and insertRow methods.

Let’s see an example to update a row and insert a row using ResultSet methods.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCResultSetUpdate {

 public static void main(String[] args) {
  try(Connection connection = DriverManager.getConnection(
                   "jdbc:mysql://localhost:3306/netjs", "root", "admin")){
   // creating Statement
   Statement stmt = connection.createStatement(
                          ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);  
   
   // Executing Query
   ResultSet rs = stmt.executeQuery("Select * from Employee");
   System.out.println("Displaying all rows");
   // Processing Resultset
   while(rs.next()){
       System.out.println("id : " + rs.getInt("id") + " Name : " 
                               + rs.getString("name") + " Age : " + rs.getInt("age")); 
   }
   // moving to 3rd row
   rs.absolute(3);
   // updating age column for 3rd row
   rs.updateInt("age", 28);
   rs.updateRow();
   System.out.println("Displaying 3rd row");
   System.out.println("id : " + rs.getInt("id") + " Name : " 
                            + rs.getString("name") + " Age : " + rs.getInt("age"));
   
   /*** Inserting row  ***/
   // moves cursor to the insert row
   rs.moveToInsertRow(); 
     
   //rs.updateInt("id",18); //updates the first column using column name
   rs.updateString(2, "Bob"); //updates the second column using column index
   rs.updateInt("age",45);
   rs.insertRow();
   rs.moveToCurrentRow();
   
  }catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Other fields of ResultSet interface

Some of the fields are already mentioned with examples, ResultSet in Java has some other fields which are as follows-

  • CLOSE_CURSORS_AT_COMMIT- This constant indicates that open ResultSet will be closed when the current transaction is commited.
  • HOLD_CURSORS_OVER_COMMIT- This constant indicates that open ResultSet will remain open when the current transaction is commited.
  • FETCH_FORWARD- The constant indicating that the rows in a result set will be processed in a forward direction; first-to-last.
  • FETCH_REVERSE- The constant indicating that the rows in a result set will be processed in a reverse direction; last-to-first.
  • FETCH_UNKNOWN- The constant indicating that the order in which rows in a result set will be processed is unknown.

Methods of the ResultSet

Most of the often used methods of the ResultSet are already covered with the examples. Some of the other methods which are used for moving the cursor are as follows-

  • afterLast()- Moves the cursor to the end of this ResultSet object, just after the last row.
  • beforeFirst()- Moves the cursor to the front of this ResultSet object, just before the first row.
  • first()- Moves the cursor to the first row in this ResultSet object.
  • last()- Moves the cursor to the last row in this ResultSet object.
  • moveToCurrentRow()- Moves the cursor to the remembered cursor position, usually the current row.
  • moveToInsertRow()- Moves the cursor to the insert row. The insert row is a special row associated with an updatable result set. It is essentially a buffer where a new row may be constructed by calling the updater methods prior to inserting the row into the result set.
  • next()- Moves the cursor froward one row from its current position.
  • previous()- Moves the cursor to the previous row in this ResultSet object.
  • relative(int rows)- Moves the cursor a relative number of rows, either positive or negative.

Reference: https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/ResultSet.html

That's all for this topic ResultSet Interface in Java-JDBC. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Connection Interface in Java-JDBC
  2. Statement Interface in Java-JDBC
  3. DatabaseMetaData Interface in Java-JDBC
  4. Types of JDBC Drivers
  5. Configuring DataSource in Spring Framework

You may also like-

  1. Difference Between Abstract Class And Interface in Java
  2. super Keyword in Java With Examples
  3. Try-With-Resources in Java With Examples
  4. How HashMap Works Internally in Java
  5. Difference Between CountDownLatch And CyclicBarrier in Java
  6. Java Stream API Examples
  7. Java Object Cloning - clone() Method
  8. Spring NamedParameterJdbcTemplate Select Query Example

Friday, October 11, 2024

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 6.1.x Release (Spring core, spring web, spring webmvc).
  • Java 21
  • Tomcat server V 10.x

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. Note that ResourceBundleViewResolver class is deprecated Spring 5.3 onward.
  • 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="com.netjstech.springweb" />
     <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="com.netjstech.springweb.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="com.netjstech.springweb.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.

import java.io.PrintWriter;
import java.util.Map;
import org.springframework.web.servlet.View;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

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. This properties file is created in \src\main\resources directory.

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=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<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=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <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 (Java class configuring DispatcherServlet is not shown here. Refer Spring Web MVC Java Configuration Example for that.)-

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="com.netjstech.springweb")
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 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