Quantcast
Channel: Tech Tutorials
Viewing all 862 articles
Browse latest View live

Spring MVC Redirect Example

$
0
0

In this post we’ll see a Spring MVC example with redirect to URL with parameters.

Spring MVC Project structure using Maven

Spring MVC page redirect example

In this example there is a form where user data is entered. On submitting the form the form data is saved and then using the user ID there is a redirect to a URL where userId is passed as parameter- “/showUser/" +userId where using that userId a User object is created.

This is the handler method in the controller class, where redirect is used to transfer to another page.


@RequestMapping(value = "/saveUser", method = RequestMethod.GET)
public String saveUser(@ModelAttribute("user") User user, Model model) {
String userId = saveUser(user);
// redirecting
return "redirect:/showUser/" +userId;
}

This is the handler method which handles the request path which is created using the Spring MVC redirect.


@RequestMapping(value = "/showUser/{userId}", method = RequestMethod.GET)
public String showUser(@PathVariable("userId") String userId, Model model) {
model.addAttribute("User", findUserById(userId));
return "user";
}

home.jsp

This is the JSP page with a link to registration form page.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - Home JSP</title>
</head>
<body>
<div>${message}</div>
<a href='<s:url value="/registerUser"></s:url>'>Register User</a>
</body>
</html>

userRegister.jsp

This is the registration form page which is opened after clicking the “Register User” link. Once this page is submitted the user data is saved and then the page is redirected to show the user details for the saved User. Note that in the handler method @PathVariable annotationis used to retrieve the parameter from the request path.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Registration</title>
</head>
<body>
<form:form action="saveUser" modelAttribute="user" method="GET">
<table>
<tr>
<td>
<form:label path="firstName">First Name</form:label>
</td>
<td>
<form:input path="firstName" id="firstname" />
</td>
</tr>
<tr>
<td>
<form:label path="lastName">Last Name</form:label>
</td>
<td>
<form:input path="lastName" id="lastname" />
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>

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>

<h4>User ID</h4><span>${User.userId}</span>
<h4>First Name</h4><span>${User.firstName}</span>
<h4>Last Name</h4><span>${User.lastName}</span>
</body>
</html>

Controller class

Here is the complete Controller class.


@Controller
public class MessageController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
model.addAttribute(new User());
model.addAttribute("message", "Spring MVC redirect example");
return "home";
}

@RequestMapping(value = "/registerUser", method = RequestMethod.GET)
public String showUserRegForm(@ModelAttribute("user") User user, Model model) {
model.addAttribute("User", user);
return "userRegister";
}

@RequestMapping(value = "/saveUser", method = RequestMethod.GET)
public String saveUser(@ModelAttribute("user") User user, Model model) {
String userId = saveUser(user);
// redirecting
return "redirect:/showUser/" +userId;
}

@RequestMapping(value = "/showUser/{userId}", method = RequestMethod.GET)
public String showUser(@PathVariable("userId") String userId, Model model) {
model.addAttribute("User", findUserById(userId));
return "user";
}

// Dummy method to save user
private String saveUser(User user) {
System.out.println("Saving User");
return "101";
}
// Dummy method to find user
private User findUserById(String userId) {
System.out.println("User ID " + userId);
User user = new User();
user.setUserId(userId);
user.setFirstName("Leonard");
user.setLastName("Nimoy");
return user;
}
}

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


Related Topics

  1. Spring MVC Example With @RequestParam Annotation
  2. Spring MVC Form Example With Bean Validation
  3. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  4. Select Query Using JDBCTemplate in Spring Framework
  5. @Resource Annotation in Spring Autowiring

You may also like -

>>>Go to Spring Tutorial Page


Difference Between @Controller And @RestController Annotations in Spring

$
0
0

In this post we’ll see the difference between @Controller and @RestController annotations in Spring framework.

@Controller annotation in Spring

In a Spring web MVC project generally a view technology like JSP, Freemarker, Thymeleaf is used to render the view. In that case from a Controller method, model is created and a logical view name is returned which is mapped to a view using the configured ViewResolver.

You may also return the object itself from the Controller method, in that case object data is written to the HTTP response body as JSON/XML. For that you need to use the annotation @ResponseBody explicitly which indicates a method return value should be bound to the web response body.

@RestController annotation in Spring

With RESTful web services interchange of data happens mostly as JSON or XML. In case you are writing a Spring REST service you will have to use @ResponseBody annotation along with the @Controller annotation to indicate that the returned object has to be serialized to the response body.

Unlike Spring Web MVC where mostly controller methods return ModelAndView with Spring REST services it is the object itself which is returned. So Spring framework from version 4 has introduced a convenience annotation @RestController which combines both @Controller and @ResponseBody annotations. In a controller class annotated with @RestController all the @RequestMapping methods assume @ResponseBody semantics by default.

Following two types are same in Spring MVC.


@Controller
@ResponseBody
public class MessageController {
..
..
}

@RestController
public class MessageController {
..
..
}

Note that when @ResponseBody annotation is used on a method, return is serialized to the response body through an HttpMessageConverter.

Concrete implementations of the HttpMessageConverter for the main media (mime) types are provided in the Spring framework and are registered by default with the RestTemplate on the client-side and with RequestMethodHandlerAdapter on the server-side. Appropriate implementation of the HttpMessageConverter based on the mime type is chosen for converting the object.

@Controller Vs @RestController in Spring

1- @Controller annotation is used in Spring Web MVC project where model data is rendered using a view.
@RestController is used in RESTful web services where return value (which is mostly an object) is bound to the response body.

2- With classes annotated with @Controller annotation if you want return value to be converted through HttpMessageConverters and written to the response you will have to annotate the class with an extra annotation @ResponseBody or you can annotate individual handler methods with in the controller class with @ResponseBody annotation.
@RestController annotation is the combination of @Controller + @ResponseBody. With @RestController annotation it is the default behavior that the result will be written to the response body.

3- With @Controller annotation you still have that control that you can annotate individual methods with @ResponseBody annotation.
With @RestController annotation all the handler methods of the class write their result to the response body.

@Controller with @ResponseBody Spring MVC example


@Controller
public class MessageController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
model.addAttribute(new User());
model.addAttribute("message", "Spring MVC example");
return "home";
}

@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public User getUser(@PathVariable("userId") String userId) {
return findUserById(userId);
}

// Dummy method to find user
private User findUserById(String userId) {
System.out.println("User ID " + userId);
User user = new User();
user.setUserId(userId);
user.setFirstName("Leonard");
user.setLastName("Nimoy");
return user;
}
}

As you can see in this controller class first method showHome() is a typical Spring web MVC handler method that returns a logical view name which resolves to home.jsp because of the following configuration.


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

Second method getUser() is annotated with @ResponseBody annotation. Note that using the produces attribute it is also indicated that the media type is JSON.

You will need to add the following Maven dependency for JSON conversion-


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>

which adds the following jars.


jackson-databind-2.9.6.jar
jackson-annotations-2.9.0.jar
jackson-core-2.9.6.jar

Running it using the URL- http://localhost:8080/springmvc-config/getUser/101 after deployment gives the following result.

@Controller Vs @RestController Spring

@RestController annotation - Spring example

If we have to write the same controller class as a Rest service using @RestController annotation then there is no need to annotate the getUser() method explicitly with the @ResponseBody annotation.


@RestController
public class MessageController {
@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET, produces="application/json")
public User getUser(@PathVariable("userId") String userId) {
return findUserById(userId);
}

// Dummy method to find user
private User findUserById(String userId) {
System.out.println("User ID " + userId);
User user = new User();
user.setUserId(userId);
user.setFirstName("Leonard");
user.setLastName("Nimoy");
return user;
}
}

That's all for this topic Difference Between @Controller And @RestController Annotations in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC Redirect Example
  2. Spring Transaction Management JDBC Example Using @Transactional Annotation
  3. Spring Batch Processing With List of Objects in batchUpdate() Method
  4. Select Query Using NamedParameterJDBCTemplate in Spring Framework
  5. Spring Example Program Using JavaConfig And Annotations

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Exception Handling Overview

$
0
0

Exception handling is an important part of any application and Spring MVC applications are no exception. Spring MVC exception handling set up is important so that the user doesn’t suddenly see an exception trace from the server side. By using Spring MVC exception handling you can configure error pages that are displayed with the proper information to the user in case any exception occurs.

HandlerExceptionResolver in Spring MVC exception handling

HandlerExceptionResolver is an interface in Spring framework which is to be implemented by objects that can resolve exceptions thrown during handler mapping or execution.

Spring framework delegates the exception handling to a chain of HandlerExceptionResolver beans where you can try to resolve the exception, prepare and error response (HTML error page, error status).

HandlerExceptionResolver implementations in Spring

The available HandlerExceptionResolver implementations in Spring framework are as follows.

HandlerExceptionResolverDescription
SimpleMappingExceptionResolverYou can configure this resolver or extend it and configure your implementation as a bean. This resolver provides a mapping between exception class names and error view names. Using it you can render error pages in a browser application.
DefaultHandlerExceptionResolverResolves exceptions raised by Spring MVC and maps them to HTTP status codes.
ResponseStatusExceptionResolverResolves exceptions with the @ResponseStatus annotation and maps them to HTTP status codes based on the value provided in the @ResponseStatus annotation.
ExceptionHandlerExceptionResolverResolves exceptions by invoking an @ExceptionHandler method in an @Controller or an @ControllerAdvice class.

Spring MVC exception handling configuration

In your Spring MVC application you can chain exception resolvers by declaring more than one exception resolver beans. You can also set the order property to specify ordering. Higher the order property, the later the exception resolver is positioned in the chain.

If you are using <mvc:annotation-driven> in your XML configuration or @EnableWebMvc in your Java config then Spring framework automatically declares built-in resolvers for default Spring MVC exceptions, for @ResponseStatus annotated exceptions, and for support of @ExceptionHandler methods.

Here is a sample configuration for SimpleMappingExceptionResolver, if MyException, a custom exception, is thrown then the view name returned is error, default error view is defaulterror.


<bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.netjs.MyException">error</prop>
</props>
</property>
<property name="defaultErrorView" value="defaulterror"/>
</bean>

Return value of HandlerExceptionResolver implementations

As per the contract of HandlerExceptionResolver it can return-

  1. ModelAndView that points to an error view.
  2. Empty ModelAndView if the exception was handled within the resolver.
  3. null if the exception remains unresolved and for subsequent resolvers to try. if the exception remains unresolved by any resolver, it is re-thrown and left to propagate to the Servlet container.

Specifying exception handler in controller class

You can specify exception handling methods with in your controller class by annotating those methods with @ExceptionHandler annotation. The exceptions these exception handler methods are supposed to handle are provided as value with the @ExceptionHandler. For example if you want to set up exception handling method in your controller class for handling exception of type MyException.


@ExceptionHandler(MyException.class)
public ModelAndView handleUserException(HttpServletRequest request, Exception ex){
ModelAndView mv = new ModelAndView();
mv.addObject("exception", ex);
mv.setViewName("error");
return mv;
}

Specifying global exception handlers using @ControllerAdvice

Though you can add exception handling methods in controller classes for few specific exception but handling the same type of exceptions in different controllers will result in a lot of redundancy. Spring framework provides @ControllerAdvice annotation using which you can set up a class with exception handler methods that are used as global exception handlers i.e. not tied with any controllers and used across controllers.


@ControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(IOException.class)
public String IOExceptionHandler() {
return "error";
}
}

Servlet container error page

If an exception is not resolved by any HandlerExceptionResolver or if the response status is set to an error status (i.e. 4xx, 5xx), Servlet containers may render a default error page in HTML. For that you can declare an error page mapping in web.xml as follows.


<error-page>
<location>/error</location>
</error-page>

This can then be mapped to a method in controller class.


@Controller
public class ErrorController {
@RequestMapping(path = "/error")
public String handle(HttpServletRequest request) {
return "defaulterror";
}
}

That's all for this topic Spring MVC Exception Handling Overview. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC Form Example With Bean Validation
  2. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  3. Difference Between @Controller And @RestController Annotations in Spring
  4. Transaction Management in Spring
  5. Data Access in Spring Framework

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice

$
0
0

In the post Spring MVC Exception Handling Overview we have already got an overview of how exception handling can be configured in Spring MVC application. In this post we’ll see a Spring MVC exception handling example using @ExceptionHandler, @ControllerAdvice, @ResponseStatus annotations and by rendering a default error page when exception is not resolved by any HandlerExceptionResolver.

Technologies used

Following is the list of tools used for the Spring MVC exception handling example.

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

Maven Dependencies

Maven is used for managing dependencies in this Spring MVC exception handling example.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-mvc</groupId>
<artifactId>spring-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring MVC</name>
<description>Spring MVC example</description>
<properties>
<spring.version>5.0.8.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<release>10</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

Project structure

Here is the final project structure of the Spring MVC exception handling example for reference.

Spring MVC exception handling project structure

Spring MVC exception handling example flow

In this example there is a user registration form (userRegister.jsp) having fields first name, last name and email. Once the form is submitted verification of the fields is done and exception is thrown if the values are not as expected.

There is one exception handler method in the controller class itself. There is also a global exception handler class created for handling exceptions globally using the @ControllerAdvice annotation. These exception handlers are example of ExceptionHandlerExceptionResolver in Spring MVC exception handling.

Bean definition for SimpleMappingExceptionResolver is also configured in the Spring MVC configuration file for handling any exception of type MyException, which is a custom exception class. This handling covers the SimpleMappingExceptionResolver in Spring MVC exception handling.

A default error page rendered by servlet container is also set, that error page is displayed if an exception is not resolved by any HandlerExceptionResolver or if the response status is set to an error status (i.e. 4xx, 5xx).

Spring MVC exception handling – Controller Classes

MessageController.java


import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.netjs.exception.MyException;
import org.netjs.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MessageController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String registerUser(Model model) {
model.addAttribute(new User());
return "userRegister";
}

@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public String showUser(@ModelAttribute("user") User user, Model model) throws Exception{
model.addAttribute("User", user);
if(user.getFirstName().length() < 5) {
// is handled by the configured SimpleMappingExceptionResolver
throw new MyException("First name too short exception");
}if(user.getEmail().equals("")) {
// is handled by the handleIOException method within this controller
throw new IOException("Email not entered exception");
}if(!user.getEmail().contains("@")) {
// handled in UniversalExceptionController
throw new IllegalArgumentException("Email not valid exception");
}if(user.getEmail().equals("123@abc")) {
// handled in UniversalExceptionController
throw new SQLException("Email not found excpetion");
}if(user.getLastName().length() < 3) {
// not resolved by any HandlerExceptionResolver - default error
throw new Exception("Last name exception");
}else {
return "user";
}
}

@ExceptionHandler(IOException.class)
public ModelAndView handleIOException(HttpServletRequest request, Exception ex){
ModelAndView mv = new ModelAndView();
mv.addObject("exception", ex);
mv.setViewName("error");
return mv;
}
}

Using the handler method registerUser(), instance of User Model bean is set and then the logical view name is returned which resolves to the registration form.

Submission of the form (request path - /registerUser) is handled by the method showUser(). In this method there are some field validations that result in different exceptions being thrown.

In the controller class there is an exception handler method handleIOException() that is used to resolve exceptions of type IOException. In the exception handler method a new ModelAndView object is created where exception message is set and the view name is set that resolves to error.jsp.

UniversalExceptionController.java

Writing exception handlers in each controller will make it a repetitive exercise. It is better to configure a global exception handler which can handle exceptions globally. Following class is set to do that.


import java.sql.SQLException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class UniversalExceptionController {

@ExceptionHandler({IllegalArgumentException.class, NumberFormatException.class})
public ModelAndView IAExceptionHandler(Exception ex) {
ModelAndView mv = new ModelAndView();
mv.addObject("exception", ex);
mv.setViewName("error");
return mv;
}

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Email not found")
@ExceptionHandler(SQLException.class)
public void SQLExceptionHandler(Exception ex) {

}
}

As you can see class is annotated with @ControllerAdvice annotation. Using this annotation you can set up a class with exception handler methods that are used as global exception handlers.

First method in the class IAExceptionHandler handles IllegalArgumentException and NumberFormatException thrown from any controller. As the value of @ExceptionHandler you can provide an array of exception classes if you want to pass more than one exception class.

Second method uses @ResponseStatus annotation, with HTTP status as not found (404) along with value attribute as SQLException. As you can see the exception handler method doesn’t resolve the exception and is not returning any value moreover the error status is 4xx so it will display the default error page.

ErrorController.java

This is the controller used for the default error.


@Controller
public class ErrorController {
@RequestMapping(path = "/error")
public String handle(HttpServletRequest request) {
return "defaulterror";
}
}

As you can see the request path is - /error here.

Deployment descriptor for Spring MVC exception handling

Default error page which is to be displayed in case exception is not resolved by any HandlerExceptionResolver is configured in web.xml. Thus, apart from the DispatcherServlet and URL mapping configuration web.xml also has the setup for the error page.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<display-name>spring-mvc</display-name>
<servlet>
<servlet-name>mvcexample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvcexample</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<error-page>
<location>/error</location>
</error-page>
</web-app>

As you can see the location is /error for the error page, we have already seen the ErrorController that has the handler method for this request path.

If you want to configure different pages for different response status codes then you can configure them as following in web.xml, that will be an example of ResponseStatusExceptionResolver.


<error-page>
<!-- Forbidden status code -->
<error-code>403</error-code>
<location>/WEB-INF/jsp/Error403.jsp</location>
</error-page>
<error-page>
<!-- Missing resource status code -->
<error-code>404</error-code>
<location>/WEB-INF/jsp/Error404.jsp</location>
</error-page>

Spring Configuration file

The Spring configuration file is as follows.

mvcexample-servlet.xml


<?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 />
<context:component-scan base-package="org.netjs.controller" />
<bean class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.netjs.exception.MyException">error</prop>
</props>
</property>
<property name="defaultErrorView" value="defaulterror"/>
</bean>
</beans>

As you can see SimpleMappingExceptionResolver is configured here to handle exception of type MyException which is a custom exception class, view name returned is error which resolves to error.jsp. Default error view is also configured.

Custom exception class

The custom exception class MyException configured in SimpleMappingExceptionResolver bean definition is as follows.


public class MyException extends RuntimeException {

/**
*
*/
private static final long serialVersionUID = -1292317882781432620L;
private String msg;

public MyException(String msg){
this.msg = msg;
}

public MyException(String msg, Throwable cause){
super(cause);
this.msg = msg;
}

@Override
public String getMessage() {
return msg;
}
}

Model bean in Spring MVC exception handling example

User.java


public class User {

private String firstName;
private String lastName;
private String 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 exception handling example - Views

JSPs used in the Spring MVC exception handling example are listed below.

User registration form – userRegister.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Registration</title>
</head>
<body>
<form:form action="registerUser" modelAttribute="user" method="post">
<table>
<tr>
<td>
<form:label path="firstName">First Name</form:label>
</td>
<td>
<form:input path="firstName" id="firstname" />
</td>
</tr>
<tr>
<td>
<form:label path="lastName">Last Name</form:label>
</td>
<td>
<form:input path="lastName" id="lastname" />
</td>
</tr>
<tr>
<td>
<form:label path="email">Email</form:label>
</td>
<td>
<form:input path="email" id="email" />
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>

user.jsp

This jsp shows the user data if no exception is thrown.


<%@ 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>First Name: ${User.firstName}</td>
</tr>
<tr>
<td>Last Name: ${User.lastName}</td>
</tr>
<tr>
<td>Email: ${User.email}</td>
</tr>
</table>
</body>
</html>

error.jsp

This is the error page which is displayed if an exception is thrown.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Error Page</title>
</head>
<body>
<h3>Error while registering user</h3>
Error Message - ${exception.getMessage()}
</body>
</html>

defaulterror.jsp

This is the default error page which is displayed if the exception is not resolved.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Error Page</title>
</head>
<body>
<h3>An error occurred in the application, please contact admin.</h3>
</body>
</html>

Deploying and running the Spring MVC exception handling example

Once the Maven build is done and application is deployed in Tomcat server you can run it using this URL- http://localhost:8080/spring-mvc/user

Here are some of the screen shots for different values.

If length of first name < 5

If email is not entered

If email doesn’t contain @

If email is entered as 123@abc

This leads to SQLException which is not resolved by any HandlerExceptionResolver so default error page is displayed.

If last name length < 3

In that case Exception is thrown. Since there is no exception handler method that handles exception of type Exception so it remains unresolved resulting in display of default error page.

That's all for this topic Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC Form Example With Bean Validation
  2. Spring MVC Redirect Example
  3. Difference Between @Controller And @RestController Annotations in Spring
  4. Insert\Update Using NamedParameterJDBCTemplate in Spring Framework
  5. Spring Transaction Management JDBC Example Using @Transactional Annotation

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC File Upload (Multipart Request) Example

$
0
0

In this post we’ll see a Spring MVC file upload example for single and multiple files.

Following is the list of tools used for the Spring MVC file upload example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. commons-fileupload 1.3.3 (If using Apache Commons file upload)
  4. Tomcat server V 9.0.10
  5. Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)

Multipart support in Spring

Spring framework provides an interface MultipartResolver residing in org.springframework.web.multipart package for parsing multipart requests including file uploads.

Spring framework provides support for two implementations of MultipartResolver-

  • Implementation based on Apache Commons FileUpload
  • Implementation based on Servlet 3.0 support for multipart request parsing.

In this post we’ll see Spring file upload example using both of these implementations and with both Spring XML configuration and Java configuration.

Spring MVC Project structure for file upload using Maven

Spring file upload (multipart request) using Servlet 3.0 support

In my opinion using Servlet 3.0 support for file upload is the better option as you don’t need any additional dependencies to use it, existing servlet container (if it supports servlet 3.0 or higher) will suffice.

Spring Servlet 3.0 support for file upload – Required XML Configuration

To use Servlet 3.0 multipart support you need to add a bean of type StandardServletMultipartResolver in your DispatcherServlet configuration.


<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>

StandardServletMultipartResolver bean has no properties to set, if you want to set some constraints on your file upload like maximum file upload size or temporary location then you need to add a "<multipart-config>" section in web.xml


<servlet>
<servlet-name>mvcexample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<multipart-config>
<!-- 2 MB max file upload size -->
<max-file-size>2097152</max-file-size>
</multipart-config>
</servlet>

Spring Servlet 3.0 support for file upload – Required Java Configuration

If you prefer Spring Java config rather than XML configuration then you need to declare StandardServletMultipartResolver as a bean and need to set a MultipartConfigElement on the Servlet registration for setting configurations like maximum size or storage location.

For Spring MVC with Java config generally AbstractAnnotationConfigDispatcherServletInitializer is used to register DispatcherServlet and it is done automatically. In that case customizeRegistration() method is used to set a MultipartConfigElement on the Servlet registration.

Here is the full class -


import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class SpringMVCConfigInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}

@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("", 2097152, 4193304, 2097152));
}
}
Here note the method customizeRegistration which uses instance of MultipartConfigElement, description of which is as follows.

public MultipartConfigElement(String location,
long maxFileSize,
long maxRequestSize,
int fileSizeThreshold)
  • location- the directory location where files will be stored.
  • maxFileSize- the maximum size allowed for uploaded files.
  • maxRequestSize- the maximum size allowed formultipart/form-data requests.
  • fileSizeThreshold- the size threshold after which files will be written to disk.

Declaring StandardServletMultipartResolver as a bean – Java config


@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");
return resolver;
}

public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}

Spring file upload (multipart request) using Commons FileUpload

Another option for parsing multipart request in Spring framework is using Commons FileUpload.

Maven dependency

To use Commons FileUpload you need to have commons-fileupload as a dependency on your classpath. If you are using Maven that can be added in pom.xml as follows-

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
That adds the following jars-

commons-fileupload-1.3.3.jar
commons-io-2.2.jar

Using Commons FileUpload for file upload – Required Spring XML Configuration

To use Apache Commons FileUpload for multipart support you need to configure a bean of type CommonsMultipartResolver with the name multipartResolver in your DispatcherServlet configuration.


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2097152" />
</bean>

CommonsMultipartResolver provides "maxUploadSize", "maxInMemorySize" and "defaultEncoding" settings as bean properties itself so need to add properties in web.xml as in the case with StandardServletMultipartResolver.

Using Commons FileUpload for file upload – Required Java Configuration

If you prefer Spring Java config then you can configure CommonsMultipartResolver as bean in the following way.


@Bean
public MultipartResolver multipartResolver() throws IOException {
CommonsMultipartResolver cmr = new CommonsMultipartResolver();
cmr.setMaxUploadSize(2097152);
return cmr;
}

Spring MVC file upload example– Views

JSP that is used for uploading a single file.

uploadFile.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>Insert title here</title>
</head>
<body>
<form action="uploadFile" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>
<label>Select a file to upload:</label>
<input type="file" name="file">
</td>
</tr>
<tr>
<td><input type="submit" value="Upload File"></td>
</tr>
</table>
</form>
</body>
</html>

In the JSP, enctype="multipart/form-data" attribute is used with the form tag to specify that it is a multipart request.

JSP that is used for uploading multiple files.

uploadMultipleFiles.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 File Upload</title>
</head>
<body>
<form action="uploadMultiFile" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td>
<label>Select a file to upload:</label>
<input type="file" name="files">
</td>
</tr>
<tr>
<td>
<label>Select a file to upload:</label>
<input type="file" name="files">
</td>
</tr>
<tr>
<td>
<label>Select a file to upload:</label>
<input type="file" name="files">
</td>
</tr>
<tr>
<td><input type="submit" value="Upload"></td>
</tr>
</table>
</form>
</body>
</html>

Here note that the same name “files” is used in all the input fields. That is required so that request is sent as an array of files.

Another JSP shows the upload status by showing a message set in the controller for success or failure of the upload. Also shows some metadata about the uploaded file like name, size and content type.

uploadStatus.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>Insert title here</title>
</head>
<body>
<table>
<tr>
<td>Upload status: ${message}</td>
</tr>
<tr>
<td>File Name: ${file.getOriginalFilename()}</td>
</tr>
<tr>
<td>File Size: ${file.getSize()}</td>
</tr>
<tr>
<td>File Type: ${file.getContentType()}</td>
</tr>
</table>
</body>
</html>

Spring MVC file upload – Controller class


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {
@RequestMapping(value = "/uploadMulti", method = RequestMethod.GET)
public String startMultiUpload(Model model) {
return "uploadMultipleFiles";
}

@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String startUpload(Model model) {
return "uploadFile";
}

// Handler Method for file upload
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
String msg= "";
if(!file.isEmpty()) {
BufferedOutputStream bos =null;
try {
byte[] fileBytes = file.getBytes();
// location to save the file
String fileName = "G:\\Test\\"+file.getOriginalFilename();
bos = new BufferedOutputStream(new FileOutputStream(new File(fileName)));
bos.write(fileBytes);
msg = "Upload successful for " + file.getName();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else {
msg = "Upload failed for " + file.getName() + " as file is empty";
}
model.addAttribute("message", msg);
model.addAttribute("file", file);
return "uploadStatus";
}

// Handler Method for multiple file uploads
@PostMapping(value = "/uploadMultiFile")
@ResponseBody
public String uploadMultipleFiles(@RequestParam("files") MultipartFile[] files, Model model) {
String msg= "";
int emptyCount = 0;
for(MultipartFile file : files) {
if(!file.isEmpty()) {
BufferedOutputStream bos =null;
try {
byte[] fileBytes = file.getBytes();
// location to save the file
String fileName = "G:\\Test\\"+file.getOriginalFilename();
bos = new BufferedOutputStream(new FileOutputStream(new File(fileName)));
bos.write(fileBytes);
msg = msg + "Upload successful for " + file.getOriginalFilename() + "<br />";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else {
emptyCount++;

}
}
// Equal means no file is selected for upload
if(files.length == emptyCount) {
msg = "Upload failed as no file is selected";
}
return msg;
}
}

In the controller class, uploadFile() method is used for handling single file upload request which has a parameter of type MultipartFile. In the logic for saving the uploaded file at a location, file path is hardcoded, you may change it to get the path from a property file or with respect to server path.

uploadMultipleFiles() method is used for handling multiple file uploads in the Spring Controller class. In the method note that MultipartFile[] parameter is an array now for holding multiple files. Method uses the new Annotation @PostMapping (from Spring 4.3) which is the shortcut for @RequestMapping(method = RequestMethod.POST).

Also uses the annotation @ResponseBody that indicates a method return value should be bound to the web response body. That way string can be returned as a response not as a logical view name to be resolved to JSP.

MultipartFile has a transferTo() method that can also be used for storing the uploaded file at the given location.


// Handler Method for file upload
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
String msg= "";
if(!file.isEmpty()) {

try {
String fileName = "G:\\Test\\"+file.getOriginalFilename();
// for storing uploaded file
file.transferTo(new File(fileName));
msg = "Upload successful for " + file.getName();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
msg = "Upload failed for " + file.getName() + " as file is empty";
}
model.addAttribute("message", msg);
model.addAttribute("file", file);
return "uploadStatus";
}

Spring MVC file upload example - Screens

Upload page with one PDF file selected for uploading.

Spring MVC file upload

Showing the status of the upload.

Spring MVC file upload status

If upload is not successful.

Spring MVC file upload error

Upload page for multiple uploads with two files selected for uploading.

Spring MVC multiple files upload

Showing the status of the upload.

Spring MVC multiple files upload

That's all for this topic Spring MVC File Upload (Multipart Request) Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC Form Example With Bean Validation
  2. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  3. Difference Between @Controller And @RestController Annotations in Spring
  4. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  5. Insert\Update Using NamedParameterJDBCTemplate in Spring Framework

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC File Download Example

$
0
0

In this post we’ll see a Spring MVC application to download a file (image, pdf, zip etc.) from web server.

Options in Spring MVC for file download

  • In your Spring MVC application for file download you can use HttpServletResponse to write the downloaded file to the output stream of the servlet response. If you are using this option then you need to do the following.
    1. Pass HttpServletResponse as a parameter to your controller handler method and the method's return type is void.
    2. Find MIME type of the content of downloaded file and set it to the response's content type. If you are not able to detect the mime type set it to application/octet-stream. Mime type can be any of these- application/pdf, application/xml, image/png, image/jpeg etc.
    3. In response set a Content-Disposition header- response.setHeader(“Content-Disposition”, “attachment; filename=” + fileName); Where fileName is the name of the file to be downloaded.
    4. Copy the file bytes to the OutputStream of response.
  • You can return the file from the controller handler method as a FileSystemResource wrapped with in ResponseEntity i.e. ResponseEntity<FileSystemResource>. If you are using this option then you need to do the following.
    1. Return type of the controller handler method is ResponseEntity<FileSystemResource>.
    2. Find MIME type of the content of downloaded file and set it to the response's header. If you are not able to detect the mime type set it to application/octet-stream. Mime type can be any of these- application/pdf, application/xml, image/png, image/jpeg etc.
    3. In response set a Content-Disposition header- response.setHeader(“Content-Disposition”, “attachment; filename=” + fileName); Where fileName is the name of the file to be downloaded.
    4. Set the response status code as OK.
    5. Set the content of the file as response entity body.

Spring MVC file download example – Technologies used

Following is the list of tools used for the Spring MVC file download example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. Tomcat server V 9.0.10
  4. Eclipse Photon 4.8.0 for Java EE development.

Spring MVC file download example project structure using Maven

Spring MVC file download example – View

In the JSP there are two links for downloading two files.

download.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<body>
<a href='<s:url value="/downloadFileUsingResponse/Rules.pdf"></s:url>'>Download Rules.pdf</a><br/>
<a href='<s:url value="/downloadFileUsingEntity/Test.png"></s:url>'>Download Test.png</a>
</body>
</body>
</html>

As you can see Spring tags library is used here for creating the URL. For that you need to add the following line in your JSP.


<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>

After the application is deployed the JSP page can be accessed using the URL- http://localhost:8080/spring-mvc/download

Here spring-mvc is the name of the Spring MVC application.

Spring MVC file download

Spring MVC file download example – Controller Class


@Controller
public class DownloadController {
@RequestMapping(value = "/download", method = RequestMethod.GET)
public String showDownload(Model model) {
return "download";
}

@RequestMapping(value = "/downloadFileUsingResponse/{fileName:.+}")
public void downloadFileAsResponse(HttpServletRequest request,
HttpServletResponse response, @PathVariable("fileName") String fileName) {
try {
// getting the path to file
String dir = request.getServletContext().getRealPath("/WEB-INF/resources/");
Path file = Paths.get(dir, fileName);
if(!Files.exists(file)){
String errorMessage = "File you are trying to download does
not exist on the server.";
OutputStream outputStream = response.getOutputStream();
outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
outputStream.close();
return;
}
// getting mimetype from context
String mimeType= request.getServletContext().getMimeType(
file.getFileName().toString());
if(mimeType == null){
// Not able to detect mimetype taking default
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.addHeader("Content-Disposition", "attachment; filename="+fileName);
Files.copy(file, response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@RequestMapping(value = "/downloadFileUsingEntity/{fileName:.+}")
public ResponseEntity<FileSystemResource> downloadFileAsEntity(
HttpServletRequest request, @PathVariable("fileName") String fileName) {

String dir = request.getServletContext().getRealPath("/WEB-INF/resources/");

Path file = Paths.get(dir, fileName);
FileSystemResource fileResource = new FileSystemResource(file.toFile());
if(!Files.exists(file)){
return ResponseEntity.notFound().build();
}
// getting mimetype from context
String mimeType= request.getServletContext().getMimeType(
file.getFileName().toString());
if(mimeType==null){
// Not able to detect mimetype taking default
mimeType = "application/octet-stream";
}
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename="+fileName)
.contentType(MediaType.valueOf(mimeType)).body(fileResource);
}
}
  • There are two methods in the controller class for handling download requests. First method downloadFileAsResponse() uses the HttpServletResponse to write the downloaded file to the output stream of the servlet response.
    Second method downloadFileAsEntity() uses the option where FileSystemResource is wrapped with in ResponseEntity and that is returned from the method.
  • File name is passed as a parameter with in the request path and @PathVariable annotation is used to retrieve the parameter from the request path.
  • In case you are wondering why path given along with @RequestMapping has a regular expression .+ in it, please refer this post- Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation
  • Path where files are kept is WEB-INF/resources, in the controller methods file is read from that location. You can change it to some other location, read it through a property file or give an absolute path as per your requirement.
  • In the methods, mime type is detected from the file name. Mime type “application/octet-stream” is used as default.

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


Related Topics

  1. Spring Web MVC Tutorial
  2. Spring MVC Example With @RequestParam Annotation
  3. Connection Pooling Using C3P0 Spring Example
  4. Spring Transaction Management JDBC Example Using @Transactional Annotation
  5. How to Read Properties File in Spring Framework

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation

$
0
0

In your Spring Web MVC application if you are using @PathVariable annotation along with @RequestMapping annotation to retrieve the parameter from the request path, then you may come across one problem- If the passed parameter has a value with a dot in it (i.e. xxx.xx) then the portion after the last dot (.), including dot, gets truncated when the value is assigned to the variable annotated with @PathVariable annotation.

For example– If you have a handler method in your controller like below.


@RequestMapping(value = "/ip/{address}")
public void processIP(@PathVariable("address") String address) {
..
..
}

Then the URI /ip/345.67.56.45 will assign 345.67.56 to the variable address.
URI /ip/198.201.231 will assign 198.201 to the variable address.

So, you can see that the value starting from the last dot is always truncated while assigning to the variable annotated with @PathVariable annotation.

Solution to the @PathVariable truncation probelm

Solution for this truncation problem is to include a regex (.+) in the @RequestMapping URI. Here regex (.+) means- match one or more of the token given with (+). That way you are explicitly asking Spring framework to match all the tokens (. in this case) and don’t leave any.

Thus the handler method should be written as following to avoid the dot (.) truncation problem.


@RequestMapping(value = "/ip/{address:.+}")
public void processIP(@PathVariable("address") String address) {
..
..
}

That's all for this topic Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring Web MVC Tutorial
  2. Spring MVC Example With @RequestParam Annotation
  3. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  4. Spring MVC File Upload (Multipart Request) Example
  5. Spring Transaction Management JDBC Example Using @Transactional Annotation

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC - Binding List of Objects Example

$
0
0

In this post we’ll see how to bind a list of objects in Spring MVC so that the objects in that List can be displayed in the view part.

Technologies used

Following is the list of tools used for the Spring MVC form example with bean validation.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. JSTL 1.2
  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

JSTL tags are also used in this Spring MVC example for binding list of objects so you need to add the following Maven dependency for JSTL apart from Spring dependencies.


<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

It adds the following jar-


jstl-1.2.jar

Spring MVC binding List example – Required XML Configuration

Since JSTL tags are used in JSP so you need your view to resolve to JstlView, for that you need to add viewClass property in the bean definition for InternalResourceViewResolver in your DispatcherServlet configuration.


<bean 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 binding List example – Model classes

List will have objects of the User class.

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;
}
}

Following class acts a container for the List of User objects.


public class UserListContainer {
private List<User> users;

public List<User> getUsers() {
return users;
}

public void setUsers(List<User> users) {
this.users = users;
}
}

Spring MVC binding List example – Controller class


@Controller
public class UserController {
@RequestMapping(value = "/getUsers", method = RequestMethod.GET)
public String getUsers(Model model) throws Exception{
List<User> users = getListOfUsers();
UserListContainer userList = new UserListContainer();
userList.setUsers(users);
model.addAttribute("Users", userList);
return "showUsers";
}

// Dummy method for adding List of Users
private List<User> getListOfUsers() {
List<User> users = new ArrayList<User>();
users.add(new User("Jack", "Reacher", "abc@xyz.com"));
users.add(new User("Remington", "Steele", "rs@cbd.com"));
users.add(new User("Jonathan", "Raven", "jr@sn.com"));
return users;
}

}

In the controller class there is a handler method getUsers() where a list of users is created and set to the UserListContainer which in turn is added as an attribute to the Model. Logical view name returned from the method is showUsers which resolves to a JSP at the location WEB-INF\jsp\showUsers.jsp.

Spring MVC binding List example – Views

If you just want to iterate the list and show the object fields then you can use the given JSP.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC List of objects display</title>
</head>
<body>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<c:forEach items="${Users.users}" var="user" varStatus="tagStatus">
<tr>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.email}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

If you want to iterate the list, show the object fields and want to bind the List of objects again to modelAttribute then you can use the following JSP.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC List of objects display</title>
</head>
<body>
<form:form method="POST" action="saveUsers" modelAttribute="Users">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<c:forEach items="${Users.users}" var="user" varStatus="tagStatus">
<tr>
<td><form:input path="users[${tagStatus.index}].firstName" value="${user.firstName}" readonly="true"/></td>
<td><form:input path="users[${tagStatus.index}].lastName" value="${user.lastName}" readonly="true"/></td>
<td><form:input path="users[${tagStatus.index}].email" value="${user.email}" readonly="true"/></td>
</tr>
</c:forEach>
</table>
<input type="submit" value="Save" />
</form:form>
</body>
</html>

In this JSP Spring form tags are used for Spring MVC form fields and for looping the List JSTL tag is used. For these tag libraries following lines are added in the JSP.


<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

To verify that the List of users is added to the Model and can be accessed in the handler method you can add the following method in the Controller class.


@RequestMapping(value = "/generatePDF", method = RequestMethod.POST)
public void generatePDF(@ModelAttribute("Users") UserListContainer userList) throws Exception{
List<User> users = userList.getUsers();
for(User user : users) {
System.out.println("First Name- " + user.getFirstName());
}
}

Once the application is deployed it can be accessed using the URL - http://localhost:8080/spring-mvc/getUsers

Just showing the object fields

Binding list of objects

Showing the object fields and binding to Model

Binding list of objects Spring MVC

That's all for this topic Spring MVC - Binding List of Objects Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC File Download Example
  2. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  3. Difference Between @Controller And @RestController Annotations in Spring
  4. Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation
  5. Insert\Update Using JDBCTemplate in Spring Framework

You may also like -

>>>Go to Spring Tutorial Page


Spring MVC PDF Generation Example

$
0
0

In this post we’ll see how to generate a PDF in Spring MVC using the fields from a view page (JSP).

Technologies used

Following is the list of tools used for the Spring MVC PDF generation 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)
  • iText 7.1.3
  • OpenPDF 1.2.3

Options for generating PDF in Spring MVC

  1. One of the option for generating PDF is iText. In Spring framework iText support is for a very old version so requires some work on your behalf to get it work with the current versions.
  2. Another option is OpenPDF which is a fork from iText. Spring framework class AbstractPdfView can directly be used to generate PDF using OpenPDF. Spring framework recommends OpenPDF.
    Reference - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/view/document/AbstractPdfView.html

Spring MVC PDF generation example using iText

First we’ll see how to generate a PDF using iText.

Maven dependencies

Maven is used for managing dependencies in this Spring MVC PDF generation example.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-mvc</groupId>
<artifactId>spring-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring MVC</name>
<description>Spring MVC example</description>
<properties>
<spring.version>5.0.8.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<!-- For JSTL tags -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- For iText -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.1.3</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<release>10</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

In the pom.xml apart from Spring framework dependencies, iText dependencies are also added which adds the following jars.


kernel-7.1.3.jar
io-7.1.3.jar
layout-7.1.3.jar

Spring MVC PDF generation example flow

In the example there is a JSP that shows a list of Users and there is a button “ViewPDF”. In the JSP that list of users is bound to a Model.

When the button is clicked, the request is mapped to the appropriate controller method and from there the logical view name and Model where the list of users is set as attribute is transferred to the view which creates a PDF. To resolve a view to a PDF another view resolver has to be added.

Spring MVC PDF generation – iText related classes

With in Spring framework there is an abstract class AbstractPdfView which acts as a superclass for PDF views. But the AbstractPdfView class works with the original iText 2.1.7 version (with com.lowagie.* package) where as the current version is iText 7.x (with com.itextpdf package).

That requires some work on your behalf to make the Spring MVC work with the current iText version. AbstractPdfView class extends AbstractView class and adds PDF specific functionality. So, you need to do that yourself, creating a class that extends AbstractView and uses the new com.itextpdf package. You can still copy most of the functionality from the AbstractPdfView class, difference is now you are pointing to the com.itextpdf.* classes where as AbstractPdfView class uses the older com.lowagie.* classes. Also code for PDF generation in iText 7.x is a little different from iText 5.x version.


import java.io.ByteArrayOutputStream;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.AbstractView;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;

public abstract class NetJSAbstractViewPDF extends AbstractView {

public NetJSAbstractViewPDF() {
setContentType("application/pdf");
}

@Override
protected boolean generatesDownloadContent() {
return true;
}

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// IE workaround: write into byte array first.
ByteArrayOutputStream baos = createTemporaryOutputStream();

// Apply preferences and build metadata.
PdfWriter writer = new PdfWriter(baos);
Document document = new Document(new PdfDocument(writer), PageSize.A4);

buildPdfMetadata(model, document, request);

// Build PDF document.
buildPdfDocument(model, document, writer, request, response);
document.close();

// Flush to HTTP response.
writeToResponse(response, baos);
}

protected void buildPdfMetadata(Map<String, Object> model, Document document, HttpServletRequest request) {
}

protected abstract void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception;
}

Now NetJSAbstractViewPDF is the abstract class which provides the PDF specific functionality and you need to extend this class to implement abstract method buildPdfDocument() as per your PDF document structure requirements.


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.netjs.model.User;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;

public class PDFView extends NetJSAbstractViewPDF {

@Override
protected void buildPdfDocument(Map<String, Object> model, Document document,
PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
// List of users that will be displayed in the PDF
List<User> users = (List<User>)model.get("Users");
// Create table with 3 columns of similar length
Table table = new Table(new float[]{4, 4, 4});
table.setWidth(UnitValue.createPercentValue(100));
PdfFont bold = PdfFontFactory.createFont("Times-Bold");
// adding header
table.addHeaderCell(new Cell().add(new Paragraph("First Name").setFont(bold)));
table.addHeaderCell(new Cell().add(new Paragraph("Last Name").setFont(bold)));
table.addHeaderCell(new Cell().add(new Paragraph("Email").setFont(bold)));
// adding rows
for(User user : users) {
table.addCell(user.getFirstName());
table.addCell(user.getLastName());
table.addCell(user.getEmail());
}

document.add(table);
}
}

Spring MVC PDF generation – Controller Class


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

import org.netjs.model.User;
import org.netjs.model.UserListContainer;
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;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserController {
@RequestMapping(value = "/getUsers", method = RequestMethod.GET)
public String getUsers(Model model) throws Exception{
List<User> users = getListOfUsers();
UserListContainer userList = new UserListContainer();
userList.setUsers(users);
model.addAttribute("Users", userList);
return "showUsers";
}

@RequestMapping(value = "/viewPDF", method = RequestMethod.POST)
public ModelAndView viewPDF(@ModelAttribute("Users") UserListContainer userList) throws Exception{
List<User> users = userList.getUsers();
return new ModelAndView("viewPDF", "Users", users);
}

// Dummy method for adding List of Users
private List<User> getListOfUsers() {
List<User> users = new ArrayList<User>();
users.add(new User("Jack", "Reacher", "abc@xyz.com"));
users.add(new User("Remington", "Steele", "rs@cbd.com"));
users.add(new User("Jonathan", "Raven", "jr@sn.com"));
return users;
}
}

In the Controller class there are two handler methods. Method getUsers() displays the list of users in a JSP page (showUsers.jsp). In that JSP there is a “View PDF” button, the request created on clicking that button is handled by the handler method viewPDF() which passes the list of users and the logical view name to be resolved to a PDF view.

Spring MVC PDF generation – Views

showUsers.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC List of objects display</title>
</head>
<body>
<form:form method="POST" action="viewPDF" modelAttribute="Users">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<c:forEach items="${Users.users}" var="user" varStatus="tagStatus">
<tr>
<td><form:input path="users[${tagStatus.index}].firstName" value="${user.firstName}" readonly="true"/></td>
<td><form:input path="users[${tagStatus.index}].lastName" value="${user.lastName}" readonly="true"/></td>
<td><form:input path="users[${tagStatus.index}].email" value="${user.email}" readonly="true"/></td>
</tr>
</c:forEach>
</table>
<input type="submit" value="View PDF" />
</form:form>
</body>
</html>

This JSP displays the users in the List by iterating the List and again bind list to the Model. Clicking “View PDF” button generates the PDF using the List bound to the Model.

We have already seen the PDF view class PDFView.java.

Spring MVC PDF generation – Model Classes

List will have objects of the User class.


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;
}
}

Following class acts a container for the List of User objects.


public class UserListContainer {
private List<User> users;

public List<User> getUsers() {
return users;
}

public void setUsers(List<User> users) {
this.users = users;
}
}

Spring MVC PDF generation – Configuration

The Spring configuration file is as follows.

mvcexample-servlet.xml


<?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 />
<context:component-scan base-package="org.netjs.controller" />
<bean id="PDFResolver" class=
"org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="order" value="1"/>
<property name="basename" value="pdf-view"/>
</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>
</beans>

As you can see two view resolver classes are configured here.

ResourceBundleViewResolver resolves the views from the properties file. ResourceBundleViewResolver is the 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.
Here “basename” property has the value pdf-view which means properties file is named pdf-view.properties file.

pdf-view.properties


viewPDF.(class)=org.netjs.config.PDFView

Controller class handler method viewPDF returns logical view name as “viewPDF” which is used to resolve the view class using this properties file.

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

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

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

Spring MVC PDF generation using OpenPDF

If you are using OpenPDF to generate PDF in your Spring MVC application then you need to make following changes.

Maven dependency

For OpenPDF you need to add following dependency in your pom.xml


<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf</artifactId>
<version>1.2.3</version>
</dependency>

PDF view class

When using OpenPDF you can directly subclass AbstractPdfView as OpenPDF uses com.lowagie.* classes, no need to create your own Abstract class by extending AbstractView class.


import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.netjs.model.User;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class OpenPDFView extends AbstractPdfView{

@Override
protected void buildPdfDocument(Map<String, Object> model, Document document,
PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("buildPdfDocument in OpenPDFView");
// List of users that will be displayed in the PDF
List<User> users = (List<User>)model.get("Users");
Font font = new Font(Font.HELVETICA, 18, Font.BOLDITALIC);

PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100.0f);
table.setWidths(new float[] {4.0f, 4.0f, 4.0f});
PdfPCell cell = new PdfPCell();
cell.setPhrase(new Phrase("First Name", font));
table.addCell(cell);
cell.setPhrase(new Phrase("Last Name", font));
table.addCell(cell);
cell.setPhrase(new Phrase("Email", font));
table.addCell(cell);
// adding rows
for(User user : users) {
table.addCell(user.getFirstName());
table.addCell(user.getLastName());
table.addCell(user.getEmail());
}
// adding table to document
document.add(table);
}
}

Properties class change

In properties class referred by ResourceBundleViewResolver, now the view class should be this new PDF view class.

pdf-view.properties


viewPDF.(class)=org.netjs.config.OpenPDFView

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/getUsers

Spring MVC PDF generation

Generated PDF

On clicking the View PDF button PDF is generated. Screen shot shows how it looks like in Chrome browser.

Spring MVC pdf generation

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


Related Topics

  1. Spring MVC File Download Example
  2. Spring MVC Redirect Example
  3. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  4. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  5. Spring Transaction Management JDBC Example Using @Transactional Annotation

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Excel Generation Example

$
0
0

In this post we’ll see how to generate an Excel sheet in Spring MVC using the fields from a view page (JSP).

Technologies used

Following is the list of tools used for the Spring MVC PDF generation 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)
  • Apache POI 4.0.0 (Required for generating excel)

Spring framework support for Apache POI

Apache POI is an open source library using which you can read and write Excel files from your Java program.

Spring framework provides support for Excel document views using two abstract classes-

  1. AbstractXlsView- You will use AbstractXlsView as superclass for Excel document views in traditional XLS format.
  2. AbstractXlsxView- You will use AbstractXlsxView as superclass for Excel document views in the Office 2007 XLSX format.

Both of these classes are compatible with Apache POI 3.5 and higher.

With in Apache POI also there are two implementations for these two types of sheets-

  1. HSSF- It is the POI Project's pure Java implementation of the Excel '97(-2007) file format.
  2. XSSF- It is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.

Note that there is a component module that attempts to provide a common high level Java API to both OLE2 and OOXML document formats which is SS for Excel workbooks. So we’ll try to use SS package as much as possible so that one implementation can be replaced by another seamlessly.

Spring MVC Excel generation example using Apache POI

In this Spring MVC Excel generation example we’ll generate a .xls file available for downloading/openeing as an xls format sheet.

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring dependencies following dependencies are also to be added to the pom.xml for generating excel and for JSTL tags.


<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<!-- For JSTL tags -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

Spring MVC PDF generation example flow

The model class used in the example is User with fields firstName, lastName, email and dob. In the example there is a JSP that shows a list of Users and there is a button “View Excel”. In the JSP that list of users is bound to a Model.

When the button is clicked, the request is mapped to the appropriate controller method and from there the logical view name and Model where the list of users is set as attribute is transferred to the view which creates an Excel sheet. To resolve a view to a PDF another view resolver has to be added.

Spring MVC PDF generation example – Model classes

User class is the bean class in this example. For field of type java.util.Date pattern is also specified using the @DateTimeFormat annotation.


import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;

public class User {

private String firstName;
private String lastName;
private String email;
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dob;
public User() {

}
public User(String firstName, String lastName, String email, Date dob) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.dob = dob;
}

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;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
Following class acts a container for the List of User objects.

public class UserListContainer {
private List<User> users;

public List<User> getUsers() {
return users;
}

public void setUsers(List<User> users) {
this.users = users;
}
}

Spring MVC Excel generation – Views

showUsers.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC List of objects display</title>
</head>
<body>
<form:form method="POST" action="viewExcel" modelAttribute="Users">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<c:forEach items="${Users.users}" var="user" varStatus="tagStatus">
<tr>
<td><form:input path="users[${tagStatus.index}].firstName" value="${user.firstName}" readonly="true"/></td>
<td><form:input path="users[${tagStatus.index}].lastName" value="${user.lastName}" readonly="true"/></td>
<td><form:input path="users[${tagStatus.index}].email" value="${user.email}" readonly="true"/></td>
<td><form:input path="users[${tagStatus.index}].dob" readonly="true"/></td>
</tr>
</c:forEach>
</table>
<input type="submit" value="View Excel" />
</form:form>
</body>
</html>

This JSP displays the users in the List by iterating the List and again bind list to the Model. Clicking “View Excel” button generates the PDF using the List bound to the Model.

Spring MVC View for Excel sheet

For generating .xls sheet you need to extend the Abstract class AbstractXlsView and provide implementation for the buildExcelDocument() method to generate excel sheet as per your requirement.


import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.netjs.model.User;
import org.springframework.web.servlet.view.document.AbstractXlsView;

public class ExcelView extends AbstractXlsView {
private static final String[] header= {"First Name", "Last Name", "Email", "DOB"};
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// List of users that will be displayed in the Excel
List<User> users = (List<User>)model.get("Users");
int rowNum = 1;
// Creating sheet with in the workbook
Sheet sheet = workbook.createSheet("Users");
/** for header **/
Font font = workbook.createFont();
font.setFontName("HELVETICA");
font.setBold(true);
CellStyle style = workbook.createCellStyle();
style.setFont(font);
Row row = sheet.createRow(0);
for(int i = 0; i < header.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(header[i]);
cell.setCellStyle(style);
}
/** header ends **/
/** Rows in the sheet **/
CellStyle dateStyle = workbook.createCellStyle();
// Setting format For the date column
dateStyle.setDataFormat(workbook.getCreationHelper().createDataFormat()
.getFormat("dd/MM/yyyy"));
for(User user : users) {
row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(user.getFirstName());
row.createCell(1).setCellValue(user.getLastName());
row.createCell(2).setCellValue(user.getEmail());
Cell cell = row.createCell(3);
cell.setCellValue(user.getDob());
cell.setCellStyle(dateStyle);
}
}
}

Spring MVC Excel generation – Controller Class


@Controller
public class UserController {
@RequestMapping(value = "/getUsers", method = RequestMethod.GET)
public String getUsers(Model model) throws Exception{
List<User> users = getListOfUsers();
UserListContainer userList = new UserListContainer();
userList.setUsers(users);
model.addAttribute("Users", userList);
return "showUsers";
}

@RequestMapping(value = "/viewExcel", method = RequestMethod.POST)
public ModelAndView viewExcel(@ModelAttribute("Users") UserListContainer userList) throws Exception{
List<User> users = userList.getUsers();
return new ModelAndView("viewExcel", "Users", users);
}

// Dummy method for adding List of Users
private List<User> getListOfUsers() throws ParseException {
List<User> users = new ArrayList<User>();
Calendar dob = Calendar.getInstance();
dob.set(1975,6,12);
users.add(new User("Jack", "Reacher", "abc@xyz.com", dob.getTime()));
// Using LocalDate from new time&date API
LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
users.add(new User("Remington", "Steele", "rs@cbd.com",
Date.from(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())));
dob.set(1965,12,6);
users.add(new User("Jonathan", "Raven", "jr@sn.com", dob.getTime()));
return users;
}
}

In the Controller class there are two handler methods. Method getUsers() displays the list of users in a JSP page (showUsers.jsp). In that JSP there is a “View Excel” button, the request created on clicking that button is handled by the handler method viewExcel() which passes the list of users and the logical view name to be resolved to an excel view.

Spring MVC Excel generation – Configuration

The Spring configuration file is as follows.

mvcexample-servlet.xml


<?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 />
<context:component-scan base-package="org.netjs.controller" />
<bean id="ExcelResolver" class=
"org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="order" value="1"/>
<property name="basename" value="excel-view"/>
</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>
</beans>

As you can see two view resolver classes are configured here.

ResourceBundleViewResolver resolves the views from the properties file. ResourceBundleViewResolver is the 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.

Here “basename” property has the value excel-view which means properties file is named excel-view.properties file.

excel-view.properties


viewExcel.(class)=org.netjs.config.ExcelView

Controller class handler method viewExcel() returns logical view name as “viewExcel” which is used to resolve the view class using this properties file.

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

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

As a rule InternalResourceViewResolver should always have higher order value because it will always be resolved to view irrespetive 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 using the URL- http://localhost:8080/spring-mvc/getUsers

Spring MVC excel generation

Generated Excel for download

On clicking the View Excel button Excel sheet is generated and there is a prompt for saving it.

Generated Excel sheet

Generated excel sheet with user details.

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


Related Topics

  1. Spring MVC File Upload (Multipart Request) Example
  2. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  3. Spring MVC Form Example With Bean Validation
  4. Spring Transaction Management JDBC Example Using @Transactional Annotation
  5. JDBCTemplate With ResultSetExtractor Example in Spring

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Generate Response as XML Example

$
0
0

In this post we’ll see how to generate XML in Spring MVC framework. For marshalling and unmarshalling (converting object from/to XML) JAXB is used in this Spring MVC example.

Technologies used

Following is the list of tools used for the Spring MVC XML generation 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)
  • JAXB API 2.3.0

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring dependencies JAXB dependencies are also to be added to the pom.xml for generation of XML. From JDK 9, JEE modules are deprecated so you will need to add dependencies in your pom.xml for inclusion of JAXB jars previously these jars were part of JDK itself.


<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
</dependency>

Requirement for generating XML in Spring MVC

In order to return XML as response with in your Spring MVC application-

  1. You need to annotate your model bean with JAXB annotations.
  2. @ResponseBody annotation has to be added to the controller's method, with that return is serialized to the response body through an HttpMessageConverter.

Spring MVC generate XML as response – Model classes

There are two classes User class whose objects are returned in the XML form and UserListContainer class which contains the List of objects of type User, this class is needed as we are sending a list of Users. These POJOs are annotated with JAXB annotations for defining the XML structure.


import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement
@XmlType(propOrder = {"firstName", "lastName", "email"})
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;
}
}

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="users")
public class UserListContainer {

private List<User> userList;

@XmlElement(name = "user")
public List<User> getUserList() {
return userList;
}

public void setUserList(List<User> userList) {
this.userList = userList;
}
}

Spring MVC XML as response – Controller class


@Controller
public class UserController {
@RequestMapping(value = "/getUsers", method = RequestMethod.GET, produces="application/xml")
@ResponseBody
public UserListContainer getUsers(Model model) throws Exception{
List<User> users = getListOfUsers();
UserListContainer userList = new UserListContainer();
userList.setUserList(users);
return userList;
}

// Dummy method for adding List of Users
private List<User> getListOfUsers() throws ParseException {
List<User> users = new ArrayList<User>();
users.add(new User("Jack", "Reacher", "abc@xyz.com"));
users.add(new User("Remington", "Steele", "rs@cbd.com"));
users.add(new User("Jonathan", "Raven", "jr@sn.com"));
return users;
}
}

Here in the handler method you can see a new attribute “produces” with value as “application/xml” with in the @RequestMapping annotation to explicitly specify the MIME media types or representations a resource can produce and send back to the client.

@ResponseBody annotation is also used in the handler method to indicate that the returned object has to be serialized to the response body. Note that return is serialized to the response body through an HttpMessageConverter.

Deploying and testing application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/getUsers and XML will be returned as response.

Spring MVC XML generation

That's all for this topic Spring MVC Generate Response as XML Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC Excel Generation Example
  2. Difference Between @Controller And @RestController Annotations in Spring
  3. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  4. Spring MVC - Binding List of Objects Example
  5. Spring MVC Form Example With Bean Validation

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Generate Response as JSON Example

$
0
0

In this post we’ll see how to generate JSON as response in Spring MVC framework.

Technologies used

Following is the list of tools used for the Spring MVC XML generation 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)
  • Jackson library (For JSON)

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring framework dependencies you need to add the following dependency for JSON.


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>

Which adds the following jars.


jackson-databind-2.9.6.jar
jackson-annotations-2.9.0.jar
jackson-core-2.9.6.jar

Requirement for generating JSON in Spring MVC

In order to return JSON as response with in your Spring MVC application-

  1. You need to add JSON related jars to the class path.
  2. @ResponseBody annotation has to be added to the controller's method, with that return is serialized to the response body through an HttpMessageConverter.

Spring MVC JSON as response – Model classes

There are two classes User class whose objects are returned in the JSON form and UserListContainer class which contains the List of objects of type User, this class is needed as we are sending a list of Users.


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;
}
}

public class UserListContainer {

private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}

Spring MVC JSON as response – Controller classes


@Controller
public class UserController {
@RequestMapping(value = "/getUsers", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public UserListContainer getUsers(Model model) throws Exception{
List<User> users = getListOfUsers();
UserListContainer userList = new UserListContainer();
userList.setUserList(users);
return userList;
}

// Dummy method for adding List of Users
private List<User> getListOfUsers() throws ParseException {
List<User> users = new ArrayList<User>();
users.add(new User("Jack", "Reacher", "abc@xyz.com"));
users.add(new User("Remington", "Steele", "rs@cbd.com"));
users.add(new User("Jonathan", "Raven", "jr@sn.com"));
return users;
}
}

Here in the handler method you can see a new attribute “produces” with value as “application/json” with in the @RequestMapping annotation to explicitly specify that response will be send back to the client in JSON format.

@ResponseBody annotation is also used in the handler method to indicate that the returned object has to be serialized to the response body. Note that return is serialized to the response body through an HttpMessageConverter.

Deploying and testing application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/getUsers and JSON will be returned as response.

Spring MVC generate JSON

That's all for this topic Spring MVC Generate Response as JSON Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC PDF Generation Example
  2. Spring MVC File Download Example
  3. Difference Between @Controller And @RestController Annotations in Spring
  4. Spring MVC Exception Handling Overview
  5. Spring MVC Example With @RequestParam Annotation

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Checkbox And Checkboxes Form Tag Example

$
0
0

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!


Related Topics

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

You may also like -

>>>Go to Spring Tutorial Page

Spring MVC Radiobutton And Radiobuttons Form Tag Example

$
0
0

In this post we’ll see how to use radiobutton and radiobuttons tag provided by the form tag library 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. Tomcat server V 9.0.10
  4. Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)

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 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>
<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

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!


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 -

>>>Go to Spring Tutorial Page

Spring MVC Dropdown Example Using Select, Option And Options Tag

$
0
0

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.

Technologies used

Following is the list of tools used for the Spring MVC dropdown list example.

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

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.

pring 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!


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 -

>>>Go to Spring Tutorial Page


HashMap in Java

$
0
0

HashMap in Java is Hash table based implementation of the Map interface that is used for storing (key, value) pairs. HashMap class in Java extends AbstractMap class and implements Map, Cloneable and Serializable interfaces.

Some of the important points about HashMap are-

  1. HashMap is an unordered collection which means HashMap does not guarantee the order of its elements.
  2. HashMap in Java permits multiple null values and a single null key.
  3. Key in the HashMap should be unique otherwise the previous stored value for the same key will be overwritten. Duplicate values are allowed though.
  4. HashMap works on the concept of hashing and the key is used to calculate the hash code. This hash code decides where will be the (key, value) pair stored.
  5. HashMap in Java is not synchronized so it is not thread safe. If HashMap is accessed concurrently by multiple threads and at least one of the threads modifies the map structurally, then the HashMap must be synchronized externally.
  6. HashMap does not implement Iterable interface so HashMap by itself can’t be iterated. You can get the “Collection view” of the Map though and iterate it.

Java HashMap constructors

HashMap class in Java has four constructors-

  • HashMap()- This constructor creates an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
  • HashMap(int initialCapacity)- This constructor creates an empty HashMap with the specified initial capacity and the default load factor (0.75). If you want a HashMap with a bigger initial capacity you can use this constructor.
  • HashMap(int initialCapacity, float loadFactor)- This constructor creates an empty HashMap with the specified initial capacity and load factor.
  • HashMap(Map<? extends K,? extends V> m)- Constructs a new HashMap with the same mappings as the specified Map.

HashMap creation example

Here is a simple Java example creating a HashMap and storing (key, value) pairs to it. We’ll also get the collection view of the Map using the entrySet method and use that to iterate the created HashMap.


public class HashMapSorting {

public static void main(String[] args) {
// creating HashMap
Map<String, String> langMap = new HashMap<String, String>();
// Storing (key, value) pair to HashMap
langMap.put("ENG", "English");
langMap.put("NLD", "Dutch");
langMap.put("ZHO", "Chinese");
langMap.put("BEN", "Bengali");
langMap.put("ZUL", "Zulu");
// retrieving value using key
String language = langMap.get("BEN");
System.out.println("Language- " + language);

System.out.println("-- Map Elements --");
for(Map.Entry<String, String> lang : langMap.entrySet()) {
System.out.println("Key- " + lang.getKey() +
" Value- " + lang.getValue());
}
}
}

Output


Language- Bengali
-- Map Elements --
Key- ZHO Value- Chinese
Key- ZUL Value- Zulu
Key- NLD Value- Dutch
Key- BEN Value- Bengali
Key- ENG Value- English

As you can see in the code a HashMap is created using the default constructor and the elements added to it using the put() method. Value mapped to any specific key can be retrieved by passing the key in the get() method.

From the displayed elements of the HashMap you can also see that the order is not maintained.

Initial capacity and load factor in HashMap

HashMap has two parameters that affect its performance:

  • Initial capacity
  • Load factor

The capacity is the number of buckets in the hash table. Initial capacity is simply the capacity at the time the hash table is created.

HashMap internally uses an array for storing its elements and each array of index is known as one bucket. By default an array has 16 buckets. For every (key, value) pair added to HashMap a hashcode is calculated using the key. That hashcode decides element goes to which bucket.

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. Default load factor is 0.75

Methods in Java HashMap class

Some of the important methods in the HashMap class are listed below.

  • clear()- Removes all of the mappings from this map.
  • computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)- If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
  • computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)- If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
  • containsKey(Object key)- Returns true if this map contains a mapping for the specified key.
  • containsValue(Object value)- Returns true if this map maps one or more keys to the specified value.
  • entrySet()- Returns a Set view of the mappings contained in this map.
  • get(Object key)- Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  • isEmpty()- Returns true if this map contains no key-value mappings.
  • keySet()- Returns a Set view of the keys contained in this map.
  • put(K key, V value)- Associates the specified value with the specified key in this map.
  • putIfAbsent(K key, V value)- If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
  • remove(Object key)- Removes the mapping for the specified key from this map if present.
  • remove(Object key, Object value)- Removes the entry for the specified key only if it is currently mapped to the specified value.
  • replace(K key, V value)- Replaces the entry for the specified key only if it is currently mapped to some value.
  • size()- Returns the number of key-value mappings in this map.

HashMap allows null as key and value

HashMap in Java allows one null key and multiple null values.


public class HashMapSorting {

public static void main(String[] args) {
// creating HashMap
Map<String, String> langMap = new HashMap<String, String>();
// Storing (key, value) pair to HashMap
langMap.put("ENG", "English");
langMap.put("NLD", null);
langMap.put("ZHO", null);
langMap.put("BEN", "Bengali");
langMap.put("ZUL", "Zulu");
langMap.put(null, "French");
langMap.put(null, "Hindi");

System.out.println("-- Map Elements --");
for(Map.Entry<String, String> lang : langMap.entrySet()) {
System.out.println("Key- " + lang.getKey() +
" Value- " + lang.getValue());
}
}
}

Output


-- Map Elements --
Key- ZHO Value- null
Key- ZUL Value- Zulu
Key- null Value- Hindi
Key- NLD Value- null
Key- BEN Value- Bengali
Key- ENG Value- English

As you can see null is inserted twice as a key but only one null key is stored. For value null can be passed multiple times.

Java HashMap iteration

HashMap by itself can’t be iterated. You can get the “Collection view” of the Map though and iterate it for example keySet() method returns a set view of the keys in the Map which can then be iterated.

The iterators returned by all of HashMap's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

Example code

In the example we’ll get the Set view of the mapped entries using the entrySet() method. While iterating that Set we’ll try to remove an element from the HashMap which means a structural modification.


public class HashMapSorting {

public static void main(String[] args) {
// creating HashMap
Map<String, String> langMap = new HashMap<String, String>();
// Storing (key, value) pair to HashMap
langMap.put("ENG", "English");
langMap.put("NLD", "Dutch");
langMap.put("ZHO", "Chinese");
langMap.put("BEN", "Bengali");
langMap.put("ZUL", "Zulu");
langMap.put("FRE", "French");

Set<Map.Entry<String, String>> langSet = langMap.entrySet();
Iterator<Map.Entry<String, String>> itr = langSet.iterator();
while (itr.hasNext()) {
Map.Entry<String, String> entry = itr.next();
System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
// removing value using HashMap's remove method
if(entry.getKey().equals("NLD")){
langMap.remove(entry.getKey());
}
}
}
}

Output


Key is ZHO Value is Chinese
Key is ZUL Value is Zulu
Key is NLD Value is Dutch
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
at org.netjs.examples.HashMapSorting.main(HashMapSorting.java:31)

Since Map is structurally modified while iteration is going on so the ConcurrentModificationException is thrown.

HashMap is not synchronized

HashMap in Java is not synchronized. If HashMap is accessed concurrently by multiple threads and at least one of the threads modifies the map structurally, then the HashMap must be synchronized externally. In order to synchronize Map you can use Collections.synchronizedMap() method which returns a synchronized Map backed by the specified map.

As example –


Map<String, String> m = Collections.synchronizedMap(new HashMap(...));

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


Related Topics

  1. How to Loop Through a Map in Java
  2. How to Sort a HashMap in Java
  3. ConcurrentHashMap in Java
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. How to Convert Array to ArrayList in Java

You may also like -

Map.Entry Interface in Java

$
0
0

Map.Entry interface in Java denotes a map entry (key-value pair). Entry interface is a nested interface with in a Map interface thus accessed as Map.Entry.

Entry interface

With in Map interface in Java Entry interface is defined as below.


interface Entry<K,V> {
K getKey();
V getValue();
..
..
}

Methods in Java Map.Entry interface

Following methods are listed in the Map.Entry interface. Comparison related static methods were added in Java 8.

  • comparingByKey()- Returns a comparator that compares Map.Entry in natural order on key. Added in Java 8.
  • comparingByKey(Comparator<? super K> cmp)- Returns a comparator that compares Map.Entry by key using the given Comparator. Added in Java 8.
  • comparingByValue()- Returns a comparator that compares Map.Entry in natural order on value. Added in Java 8.
  • comparingByValue(Comparator<? super V> cmp)- Returns a comparator that compares Map.Entry by value using the given Comparator. Added in Java 8.
  • equals(Object o)- Compares the specified object with this entry for equality.
  • getKey()- Returns the key corresponding to this entry.
  • getValue()- Returns the value corresponding to this entry.
  • hashCode()- Returns the hash code value for this map entry.
  • setValue(V value)- Replaces the value corresponding to this entry with the specified value (optional operation).

Map.entrySet method

The Map.entrySet method defined in the Map interface returns a collection-view of the map, whose elements are of this class.

Example code using entrySet() to get Map.Entry elements

Here is a Java example where we’ll get the “Collection view” of the map using the entrySet() method which returns a set view of the Map.Entry elements contained in this map.


public class HashMapSorting {

public static void main(String[] args) {

Map<String, String> langMap = new HashMap<String, String>();

langMap.put("ENG", "English");
langMap.put("NLD", "Dutch");
langMap.put("ZHO", "Chinese");
langMap.put("BEN", "Bengali");
langMap.put("ZUL", "Zulu");
langMap.put("FRE", "French");

//Getting Map.Entry elements using entrySet()
Set<Map.Entry<String, String>> langSet = langMap.entrySet();
// Looping the set of Map.Entry values
for(Map.Entry<String, String> entry : langSet){
System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
}
}
}

Output


Key is ZHO Value is Chinese
Key is ZUL Value is Zulu
Key is NLD Value is Dutch
Key is FRE Value is French
Key is BEN Value is Bengali
Key is ENG Value is English

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


Related Topics

  1. How HashMap Internally Works in Java
  2. TreeMap in Java
  3. Difference Between HashMap And ConcurrentHashMap in Java
  4. How to Sort Elements in Different Order in TreeSet
  5. How to Remove Elements From an ArrayList in Java

You may also like -

Spring MVC Configuring Multiple View Resolvers Example

$
0
0

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>

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"));
}
}

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>

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

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!


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 -

>>>Go to Spring Tutorial Page

Private Methods in Java Interface

$
0
0
Interfaces in Java were living the life of having public static final fields and public abstract methods till Java 7 but got a makeover with some new features added to them later namely-
  • Capability to add default methods to interface from Java 8 onward.
  • Capability to add static methods to interface from Java 8 onward.
  • Capability to add private methods to interface from Java 9 onward.

In this post we’ll see how to add private methods to a Java interface, what is the reason to include private methods to an interface.

Private methods in Java interface

Private methods in Java interfaces are defined using private modifier the same way it is done for a Java class.


private methodName(argument_List){
..
..
}

Private methods in Java interface can be both static and non-static.

Reason to include private methods to an interface in Java

Java 8 included interface default methods and interface static methods to an interface with that inclusion it became possible to write method bodies with in an interface but a new problem was observed.

Let’s say you have 2 methods and both of them share some code and you want to write that code as a separate method which can be called from both the methods. In Java 8 that method with common code could be default or static.

Here note that both default and static methods with in a Java interface are public by default meaning the method having common code would also be implicitly public. Which means any class implementing the interface can access this method too. But that method has some code which makes sense with in the interface, calling it from any other class doesn’t make sense and it is also against the encapsulation OOPS concept because access is given to some method which is not at all required.

Let’s try to understand this scenario in Java 8 with an example-


public interface TestInterface {
default void defMethod1(){
sharedCode();
System.out.println("In default method 1");
}

default void defMethod2(){
sharedCode();
System.out.println("In default method 2");
}

default void sharedCode(){
System.out.println("In sharedCode, invoking it on its own"
+ " doesn't make much sense");
}
}

As you can see in the Interface there are two default methods defMethod1() and defMethod2() in the interface. Common code executed by both the methods is kept in a separate default method to avoid duplication of the code.

But the problem with this interface is that any class implementing this interface could access sharedCode() method too as all the methods were public by default till Java 8.


public class TestClass implements TestInterface {
public static void main(String[] args) {
TestClass obj = new TestClass();
obj.sharedCode();
}
}

Output


In sharedCode, invoking it on its own doesn't make much sense

Interface private methods Java 9 onward

With the new feature of private methods in interfaces from Java 9 onward such methods (as shown in the above example) can be written as private methods which are not visible outside the interface. That way code redundancy can be avoided while keeping the access to the method restricted.

The example showed above can use private access modifier (Java 9 onward) with the sharedCode() method with in the interface to keep access to it restricted.


public interface TestInterface {
default void defMethod1(){
sharedCode();
System.out.println("In default method 1");
}

default void defMethod2(){
sharedCode();
System.out.println("In default method 2");
}

private void sharedCode(){
System.out.println("In sharedCode, invoking it on its own"
+ " doesn't make much sense");
}
}

Now trying to access sharedCode() method from a class implementing this interface will result in compile time error “The method sharedCode() is undefined for the type TestClass”.


public class TestClass implements TestInterface {
public static void main(String[] args) {
TestClass obj = new TestClass();
obj.sharedCode();
}
}
Now you can invoke default method from the implementing class which in turn invokes the private method.

public class TestClass implements TestInterface {
public static void main(String[] args) {
TestClass obj = new TestClass();
obj.defMethod1();
}
}

Output


In sharedCode, invoking it on its own doesn't make much sense
In default method 1

As you can see now private method can be accessed through methods of the interfaces only.

Rules for private methods in Java interfaces

The usage of private methods in the Java interfaces is guided by the following rules-

  1. Private methods in an interface can't be abstract they should have method body. Trying to define a private method as a regular public abstract method in an interface results in the error "This method requires a body instead of a semicolon"
  2. If you want to invoke a private method from a static method in an interface then you should write a private static method. From a static context you cannot access a non-static method it will give you an error “Cannot make a static reference to the non-static method”.
  3. A default method in an interface can invoke both static and non-static private methods with in an interface.

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


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. New Date And Time API in Java 8
  4. PermGen Space Removal in Java 8
  5. Core Java Basics Interview Questions

You may also like -

>>>Go to Java Basics Page

Creating PDF in Java Using iText

$
0
0

In this post we’ll see how to create PDF in Java using iText library. Version of iText used here is 7.x.x which has different API from iText 5.x.x versions.

In the post we’ll see various examples of PDF creation showing the use of classes in iText like PdfDocument, Document, PdfWriter, Paragraph, Table, PdfFont, PDFReader.

Note that iText is open source but the open source version is AGPL licensed which means you must distribute all source code, including your own product and web-based applications.

Maven dependecy

For using iText library you must add the following dependencies to your pom.xml file.


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<itext.version>7.1.3</itext.version>
</properties>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>${itext.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>io</artifactId>
<version>${itext.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>${itext.version}</version>
</dependency>
<!-- Java logging used-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.13</version>
</dependency>

This adds the following jars to the project’s class path.


kernel-7.1.3.jar
io-7.1.3.jar
layout-7.1.3.jar
slf4j-api-1.7.13.jar
slf4j-jdk14-1.7.13.jar

Following examples are listed in this post for generating PDF in Java using iText.

  1. PDF creation hello world example
  2. Content in a table in PDF
  3. Adding background image in PDF
  4. Adding image in PDF
  5. Showing list in PDF
  6. Rendering PDF in web application
  7. Password protected PDF with user permissions

Creating PDF in Java using iText – Hello World

First lets see a simple example where “Hello world” is written to the PDF using a Java program. Also the font and color for the text is specified before writing it to the PDF.


import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;

public class PDFCreation {
public static final String DEST = "G://Test//hello_world.pdf";
public static void main(String[] args) {
PdfWriter writer;
try {
writer = new PdfWriter(new FileOutputStream(DEST));
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
Text text = new Text("Hello World with font and color")
.setFont(font)
.setFontColor(ColorConstants.BLUE);
//Add paragraph to the document
document.add(new Paragraph(text));
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Creating PDF in Java using iText – Content in a Table

In this example we’ll see how to present content as a table in PDF from your Java program. Example uses a bean class User, fields of object of type User are displayed in the table.

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;
}
}

Class used for creating PDF showing data in a table.


import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.netjs.Model.User;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;

public class PDFTableCreation {
public static void main(String[] args) {
new PDFTableCreation().createTablePDF("G://Test//table.pdf");
}

private void createTablePDF(String PDFPath){
PdfWriter writer;
try {
writer = new PdfWriter(new FileOutputStream(PDFPath));
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, new PageSize(PageSize.A4));
PdfFont headerFont = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
PdfFont cellFont = PdfFontFactory.createFont(StandardFonts.COURIER);
// Create table with 3 columns of similar length
Table table = new Table(new float[]{4, 4, 4});
table.setWidth(UnitValue.createPercentValue(100));
// adding header
table.addHeaderCell(new Cell().add(new Paragraph(
"First Name").setFont(headerFont)));
table.addHeaderCell(new Cell().add(new Paragraph(
"Last Name").setFont(headerFont)));
table.addHeaderCell(new Cell().add(new Paragraph(
"Email").setFont(headerFont)));
List<User> users = getListOfUsers();
// adding rows
for(User user : users) {
table.addCell(new Cell().add(new Paragraph(
user.getFirstName()).setFont(cellFont)));
table.addCell(new Cell().add(new Paragraph(
user.getLastName()).setFont(cellFont)));
table.addCell(new Cell().add(new Paragraph(
user.getEmail()).setFont(cellFont)));
}
document.add(table);
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

// Dummy method for adding List of Users
private List<User> getListOfUsers() {
List<User> users = new ArrayList<User>();
users.add(new User("Jack", "Reacher", "abc@xyz.com"));
users.add(new User("Remington", "Steele", "rs@cbd.com"));
users.add(new User("Jonathan", "Raven", "jr@sn.com"));
return users;
}
}

Created PDF

Creating table in PDF Using iText- Java

Creating PDF in Java using iText – Adding background image to PDF


public class PDFCreation {
public static final String DEST = "G://Test//image.pdf";

public static void main(String[] args) {
new PDFCreation().addImageToPDF(DEST);
}

private void addImageToPDF(String PDFPath){
PdfWriter writer;
try {
writer = new PdfWriter(new FileOutputStream(PDFPath));
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
PageSize pageSize = new PageSize(PageSize.A4).rotate();

PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
// creating image data instance by passing the path to image
ImageData img = ImageDataFactory.create("resources//netjs.png");
canvas.saveState();
// graphic state
PdfExtGState state = new PdfExtGState();
state.setFillOpacity(0.2f);
canvas.setExtGState(state);
canvas.addImage(img, 20, 650, pageSize.getWidth()/2, false);
canvas.restoreState();
document.add(new Paragraph("Adding image to PDF Example"));

document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Created PDF

adding image to PDF in Java

Creating PDF in Java using iText – Adding image to PDF

If you want to add image to PDF.


public class PDFCreation {
public static final String DEST = "G://Test//image.pdf";

public static void main(String[] args) {
new PDFCreation().addImageToPDF(DEST);
}

private void addImageToPDF(String PDFPath){
PdfWriter writer;
try {
// creating image data instance by passing the path to image
Image image = new Image(ImageDataFactory.create("resources//netjs.png"));
writer = new PdfWriter(new FileOutputStream(PDFPath));
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
document.add(new Paragraph("Adding image to PDF Example"));
document.add(image);

document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Creating PDF in Java using iText – Adding List to PDF

If you want to show a list of items in PDF then you can create a List and add ListItems to it. Symbol used for marking ListItems can be passed using setListSymbol() method. There is an Enum ListNumberingType that holds possible values for list item prefix. You can also pass a unicode character.


import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.ListNumberingType;

public class PDFCreation {

public static void main(String[] args) {
new PDFCreation().addImageToPDF("G://Test//list.pdf");
}

private void addImageToPDF(String PDFPath){
PdfWriter writer;
try {
writer = new PdfWriter(new FileOutputStream(PDFPath));
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
document.add(new Paragraph("Choices Are (Using English Letters)"));
List list = new List()
.setSymbolIndent(14) // for offset (space from the left)
.setListSymbol(ListNumberingType.ENGLISH_LOWER);

// Add ListItem objects
list.add(new ListItem("Aerobic"))
.add(new ListItem("Anaerobic"))
.add(new ListItem("Flexibility Training"));
// Add the list
document.add(list);

document.add(new Paragraph("Choices Are (Using Roman upper)"));
list = new List()
.setSymbolIndent(14)
.setListSymbol(ListNumberingType.ROMAN_UPPER);
// Add ListItem objects
list.add(new ListItem("Aerobic"))
.add(new ListItem("Anaerobic"))
.add(new ListItem("Flexibility Training"));
// Add the list
document.add(list);

document.add(new Paragraph("Choices Are (Using bullet symbol)"));
list = new List()
.setSymbolIndent(14)
.setListSymbol("\u2022"); // Passing unicode for bullet
// Add ListItem objects
list.add(new ListItem("Aerobic"))
.add(new ListItem("Anaerobic"))
.add(new ListItem("Flexibility Training"));
// Add the list
document.add(list);


document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Created PDF

creating PDF with list items using Java

Creating PDF in Java using iText – Rendered to browser as web response

If you want to render PDF to the browser in your web project using the HTTPResponse, then you can do it as follows. PDFWriter constructor also accepts an OutputStream as parameter. If you want to write a web application, then you can create a ServletOutputStream.


PdfWriter writer;
try{
response.setContentType("application/pdf");
writer = new PdfWriter(response.getOutputStream());
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
PdfFont titleFont = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
PdfFont textFont = PdfFontFactory.createFont(StandardFonts.COURIER);
document.add(new Paragraph("PDF generated in Web")
.setFont(titleFont).setFontColor(ColorConstants.RED)
.setTextAlignment(TextAlignment.CENTER));
Paragraph p = new Paragraph("This is the text of the PDF created using iText library and
rendered to the browser using a Servlet.");
document.add(p.setFont(textFont).setFontColor(ColorConstants.ORANGE));
document.close();
}catch(Exception e){
e.printStackTrace();

}

Created PDF

rendering PDF in web application

Creating PDF in Java using iText – Password protected PDF with user permissions

You can encrypt the created PDF, there are two types of passwords you can set-

  • User password
  • Owner password

The userPassword and the ownerPassword can be null or have zero length.

You can also set user permissions (operation permitted when the PDF document is opened with the user password). Available user permissions are defined in the EncryptionConstants class.

  • EncryptionConstants.ALLOW_PRINTING
  • EncryptionConstants.ALLOW_MODIFY_CONTENTS
  • EncryptionConstants.ALLOW_COPY
  • EncryptionConstants.ALLOW_MODIFY_ANNOTATIONS
  • EncryptionConstants.ALLOW_FILL_IN
  • EncryptionConstants.ALLOW_SCREENREADERS
  • EncryptionConstants.ALLOW_ASSEMBLY
  • EncryptionConstants.ALLOW_DEGRADED_PRINTING

The permissions can be combined by ORing them, as example (EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_MODIFY_CONTENTS)

Example code

For this code to run you will need bouncycastle jar. Maven dependency for it is as follows-


<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.60</version>
</dependency>

which adds the following jar-

  • bcprov-jdk15on-1.60.jar

public class PDFWithPwd {

public static void main(String[] args) {
new PDFWithPwd().changePermissions("G://Test//Permissions.pdf");

}

private void changePermissions(String pdfPath) {
final String USER_PWD="user";
final String OWNER_PWD="owner";
try {
PdfWriter writer = new PdfWriter(pdfPath, new WriterProperties()
.setStandardEncryption(USER_PWD.getBytes(), OWNER_PWD.getBytes(),
EncryptionConstants.ALLOW_PRINTING,
EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA));
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
document.add(new Paragraph("This PDF is password protected and its content can’t be copied by user."));
document.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

If you open the created PDF it will ask for the password. If you open it using the user password then you won’t be able to copy the content as per the user permission settings.

password protected PDF in Java using iText

That's all for this topic Creating PDF in Java Using iText. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Create PDF From XML Using Apache FOP
  2. Spring MVC PDF Generation Example
  3. How to Create Password Protected Zip File in Java
  4. Print Odd-Even Numbers Using Threads And wait-notify - Java Program
  5. Converting double to int - Java Program

You may also like -

>>>Go to Java Programs Page

Viewing all 862 articles
Browse latest View live