Spring @ExceptionHandler and RedirectAttributes

Since Spring 4.3.5 and 5.0 M4, it supports RedirectAttributes argument in the @ExceptionHandler method. @ExceptionHandler(MyCustomException.class) public String handleError1(MyCustomException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", "abcdefg"); return "redirect:/viewName"; } @ExceptionHandler(MultipartException.class) public String handleError2(MultipartException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return "redirect:/viewName"; } P.S Read this SPR-14651 Noted If you are using Spring < 4.3.5, do not add ...

Read more

Spring Boot – Configure maxSwallowSize in embedded Tomcat

In Spring Boot, you can’t configure the embedded Tomcat maxSwallowSize via the common application properties, there is no option like server.tomcat.*.maxSwallowSize Solution To fix it, you need to declare a TomcatEmbeddedServletContainerFactory bean and configure the maxSwallowSize like this : //… import org.apache.coyote.http11.AbstractHttp11Protocol; import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; private int maxUploadSizeInMb = 10 * 1024 * 1024; …

Read more

Eclipse – How to know this class belongs to which JAR

For example, I want to know this SpringBootApplication class belongs to which JAR or dependency : import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootWebApplication { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootWebApplication.class, args); } } Solution In Eclipse IDE, double clicks on the class name, press CTRL + SHIFT + T (win/*nix) or …

Read more

IntelliJ IDEA – How to know this class belongs to which JAR

For example, how to find out this FileUploadBase class belongs to which JAR or dependency? //… import org.apache.tomcat.util.http.fileupload.FileUploadBase; @ExceptionHandler(FileUploadBase.FileSizeLimitExceededException.class) public String handleError3(Exception e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return "redirect:/uploadStatus"; } Solution In IntelliJ IDEA, double clicks on the class name and press CTRL + n (win/*nix) or CMD + n (mac) to prompt out …

Read more

Spring Boot file upload example

This article shows you how to upload a file in Spring Boot web application. Tools used : Spring Boot 1.4.3.RELEASE Spring 4.3.5.RELEASE Thymeleaf Maven Embedded Tomcat 8.5.6 1. Project Structure A standard project structure. 2. Project Dependency Spring boot dependencies, no need extra library for file upload. pom.xml <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong</groupId> …

Read more

Spring MVC – How to handle max upload size exceeded exception

In Spring, you can declare a @ControllerAdvice to catch the ugly max upload size exceeded exception like this : Solution Depends the types of multipartResolver : StandardServletMultipartResolver – catch MultipartException, refer to this example. CommonsMultipartResolver – catch MaxUploadSizeExceededException – refer to this example. GlobalExceptionHandler.java package com.mkyong.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartException; import …

Read more

Spring MVC file upload example – Commons FileUpload

This article will shows you how to use CommonsMultipartResolver to handle file upload in Spring MVC web application. Tools used : Spring 4.3.5.RELEASE commons-fileupload 1.3.2 Maven 3 Tomcat 7 or 8 and Jetty 8, 9 Note For StandardServletMultipartResolver – file upload using Servlet 3.0 multipart request parsing, please refer to this Spring MVC file upload …

Read more

Spring file upload and connection reset issue

A Spring servlet initializer to configure the file upload limit, 5mb per file and 10mb per request. MyWebInitializer.java public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { private int maxUploadSizeInMb = 5 * 1024 * 1024; // 5 MB //… @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { // upload temp file will put here File uploadDirectory = new File(System.getProperty("java.io.tmpdir")); …

Read more

Spring Boot – Deploy WAR file to Tomcat

In this article, we will show you how to create a Spring Boot traditional WAR file and deploy to a Tomcat servlet container. In Spring Boot, to create a WAR for deployment, we need 3 steps: Extends SpringBootServletInitializer Marked the embedded servlet container as provided. Update packaging to war Tested with Spring Boot 2.1.2.RELEASE Tomcat …

Read more

Spring Boot @ConfigurationProperties example

Spring Boot @ConfigurationProperties lets developers map or bind the entire external configuration values in .properties or .yml files to Java objects. Table of contents: 1. Access a single value using @Value 2. @ConfigurationProperties 3. Add JSR303 Validation 3.1 Add JSR 303 dependencies 3.2 @ConfigurationProperties and @Validated 4. Testing @ConfigurationProperties 5. Download Source Code 6. References …

Read more

wget on Mac OS X

By default, there is no wget on Mac OS X. $ wget http://www-us.apache.org/dist/tomcat/tomcat-8/v8.5.9/bin/apache-tomcat-8.5.9.tar.gz -bash: wget: command not found On Mac OS X, the equivalent of Linux’s wget is curl -O $ curl -O http://www-us.apache.org/dist/tomcat/tomcat-8/v8.5.9/bin/apache-tomcat-8.5.9.tar.gz % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 49 9112k 49 …

Read more

Intellij IDEA – Spring boot reload static file is not working

In Eclipse, just include the Spring Boot Dev Tools dependency, then the hot swapping and static file reload will be enabled magically. For Intellij IDE, we need extra steps to enable it. 1. Spring Boot Dev Tools With Spring Boot Dev Tools enabled : Any changes to views or resources can be seen in the …

Read more

Spring Boot – Which main class to start

If Spring Boot project contains multiple main classes, Spring Boot will fail to start or packag for deployment. Terminal $ mvn package #or $ mvn spring-boot:run Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run (default-cli) Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run failed: Unable to find a single main class from the following candidates [com.mkyong.Test, com.mkyong.SpringBootWebApplication] -> [Help 1] Maven …

Read more

Spring Boot – Jetty as embedded server

By default, Spring Boot use Tomcat as the default embedded server, to change it to Jetty, just exclude Tomcat and include Jetty like this : 1. spring-boot-starter-web pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> 2. spring-boot-starter-thymeleaf pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> …

Read more

How to change the default port in Spring Boot

Default, Spring Boot web application starts embedded web server (Tomcat, Jetty, etc.) in port 8080. And we can configure or change the port using the server.port property. Table of contents 1. application.properties 2. application.yml 3. Command Line 4. Environment Variable 5. WebServerFactoryCustomizer 6. Download Source Code 7. References P.S Tested with Spring Boot 1, 2, …

Read more

Spring Boot – How to change Context Path

In Spring Boot, to change the context path, update server.contextPath properties. The following examples update the context path from / to /mkyong or http://localhost:8080/mkyong Note By default, the context path is “/”. P.S Tested with Spring Boot 1.4.2.RELEASE 1. Properties & Yaml 1.1 Update via a properties file. /src/main/resources/application.properties server.port=8080 server.contextPath=/mkyong 1.2 Update via a …

Read more

Spring Boot Hello World Example – Thymeleaf

In this article, we will show you how to develop a Spring Boot web application, using Thymeleaf view, embedded Tomcat and package it as an executable JAR file. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Thymeleaf 3.0.11.RELEASE Tomcat embed 9.0.14 JUnit 4.12 Maven 3 Java 8 1. Project Directory 2. Maven Put spring-boot-starter-web and …

Read more

Spring Boot Hello World Example – JSP

A Spring Boot web application example, using embedded Tomcat + JSP template, and package as an executable WAR file. Technologies used : Spring Boot 1.4.2.RELEASE Spring 4.3.4.RELEASE Tomcat Embed 8.5.6 Maven 3 Java 8 1. Project Directory Create the following folders manually : 2. Project Dependencies Maven example. Read comments for self-explanatory. pom.xml <?xml version="1.0" …

Read more

Spring Boot web JSP – No Java compiler available

Spring boot web application with embeded Tomcat and JSP. Run and access the JSP page, but hits the following errors $ mvn spring-boot:run … java.lang.IllegalStateException: No Java compiler available at org.apache.jasper.JspCompilationContext.createCompiler(JspCompilationContext.java:235) ~[tomcat-embed-jasper-8.5.6.jar:8.5.6] at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592) ~[tomcat-embed-jasper-8.5.6.jar:8.5.6] at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:368) ~[tomcat-embed-jasper-8.5.6.jar:8.5.6] at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385) ~[tomcat-embed-jasper-8.5.6.jar:8.5.6] at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329) ~[tomcat-embed-jasper-8.5.6.jar:8.5.6] at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.6.jar:8.5.6] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) [tomcat-embed-core-8.5.6.jar:8.5.6] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.6.jar:8.5.6] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) …

Read more

Java – Check if Array contains a certain value?

Java examples to check if an Array (String or Primitive type) contains a certain values, updated with Java 8 stream APIs. 1. String Arrays 1.1 Check if a String Array contains a certain value “A”. StringArrayExample1.java package com.mkyong.core; import java.util.Arrays; import java.util.List; public class StringArrayExample1 { public static void main(String[] args) { String[] alphabet = …

Read more

CSF – How to limit the number of connections per IP address

In the ConfigServer Security & Firewall (CSF) configuration file, update the CT_LIMIT value to limit the number of connections per IP address. This is a simple trick to prevent some types of Denial of Service (DOS) attack. Note To stop the Denial of Service (DoS) attack immediately, read this null route example. 1. /etc/csf/csf.conf SSH …

Read more

Java Date Time Tutorials

A collection of Java date and time examples. 1. Java Date Time APIs In old days, we use the following classic Date and Calendar APIs to represent and manipulate date. java.util.Date – date and time, print with default time-zone. java.util.Calendar – date and time, more methods to manipulate date. java.text.SimpleDateFormat – formatting (date -> text), …

Read more

Java 8 – TemporalAdjusters examples

In Java 8, you can use the predefined java.time.temporal.TemporalAdjusters to adjust a date or Temporal 1. TemporalAdjusters Example to move a date to firstDayOfMonth, firstDayOfNextMonth, next Monday and etc. TestDate.java package com.mkyong.time; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; public class TestDate { public static void main(String[] args) { LocalDate localDate = LocalDate.now(); System.out.println("current date : …

Read more

Java – How to add days to current date

This article shows you how to add days to the current date, using the classic java.util.Calendar and the new Java 8 date and time APIs. 1. Calendar.add Example to add 1 year, 1 month, 1 day, 1 hour, 1 minute and 1 second to the current date. DateExample.java package com.mkyong.time; import java.text.DateFormat; import java.text.SimpleDateFormat; import …

Read more

Java 8 – Period and Duration examples

Few examples to show you how to use Java 8 Duration, Period and ChronoUnit objects to find out the difference between dates. Duration – Measures time in seconds and nanoseconds. Period – Measures time in years, months and days. 1. Duration Example A java.time.Duration example to find out difference seconds between two LocalDateTime DurationExample.java package …

Read more

Java 8 – How to format LocalDateTime

Few examples to show you how to format java.time.LocalDateTime in Java 8. 1. LocalDateTime + DateTimeFormatter To format a LocalDateTime object, uses DateTimeFormatter TestDate1.java package com.mkyong.time; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TestDate1 { public static void main(String[] args) { //Get current date time LocalDateTime now = LocalDateTime.now(); System.out.println("Before : " + now); DateTimeFormatter formatter …

Read more

Java – Convert Object to Map example

In Java, you can use the Jackson library to convert a Java object into a Map easily. 1. Get Jackson pom.xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> 2. Convert Object to Map 2.1 A Jackson 2 example to convert a Student object into a java.util.Map Student.java package com.mkyong.examples; import java.util.List; public class Student { private String …

Read more

Gradle – Multiple start script examples

Few build.gradle examples to show you how to create multiple start scripts or executable Java application. 1. Single Start Script 1.1 In Gradle, you can use the application plugin to create an executable Java application : build.gradle apply plugin: ‘application’ mainClassName = "com.mkyong.analyzer.run.threads.MainRunApp" applicationName = ‘mainApp’ applicationDefaultJvmArgs = ["-Xms512m", "-Xmx1024m"] 1.2 Create the executable Java …

Read more

Java – How to compare two Sets

In Java, there is no ready make API to compare two java.util.Set 1. Solution Here’s my implementation, combine check size + containsAll : SetUtils.java package com.mkyong.core.utils; import java.util.Set; public class SetUtils { public static boolean equals(Set<?> set1, Set<?> set2){ if(set1 == null || set2 ==null){ return false; } if(set1.size()!=set2.size()){ return false; } return set1.containsAll(set2); } …

Read more

Spring Data MongoDB + JSR-310 or Java 8 new Date APIs

While saving an object containing the new Java 8 java.time.LocalDateTime, the following error is thrown : org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.time.LocalDateTime] to type [java.util.Date] Tested Spring 4.3.2.RELEASE Spring Data MongoDB 1.9.2.RELEASE Is Spring-data supporting the new Java 8 Date APIs (JSR-310)? 1. Spring Data + JSR-310 Yes, Spring-data supports the …

Read more

Java 8 – HijrahDate, How to calculate the Ramadan date

Ramadan is the 9th month of the Islamic calendar, the entire month. 1. HijrahDate -> Ramadan 2016 Full example to calculate the start and end of the Ramadan 2016 TestHijrahDate.java package com.mkyong.date; import java.time.LocalDate; import java.time.chrono.HijrahDate; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAdjusters; public class TestDate { public static void main(String[] args) { //first day of Ramadan, 9th …

Read more

Java 8 – MinguoDate examples

This MinguoDate calendar system is primarily used in Taiwan (Republic of China…) (ISO) 1912-01-01 = 1-01-01 (Minguo ROC) To convert the current date to the Minguo date, just subtracts the current year with number 1911, for example 2016 (ISO) – 1911 = 105 (Minguo ROC) 1. LocalDate -> MinguoDate Review a full example to convert …

Read more

Java 8 – ZonedDateTime examples

Few Java 8 java.time.ZonedDateTime examples to show you how to convert a time zone between different countries. Table of contents 1. Convert LocalDateTime to ZonedDateTime 2. Malaysia (UTC+08:00) -> Japan (UTC+09:00) 3. France, Paris (UTC+02:00, DST) -> (UTC-05:00) 4. References 1. Convert LocalDateTime to ZonedDateTime The LocalDateTime has no time zone; to convert the LocalDateTime …

Read more

Java 8 – Convert Date to LocalDate and LocalDateTime

Here is the code to convert java.util.Date to java.time.LocalDate. Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // different way of create instant object LocalDate localDate = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); Convert java.util.Date to java.time.LocalDateTime. Date date = new Date(); LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); Convert java.util.Date to java.time.ZonedDateTime. Date date = new Date(); ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault()); …

Read more

Java 8 – Convert Instant to ZonedDateTime

Java 8 examples to show you how to convert from Instant to ZonedDateTime 1. Instant -> ZonedDateTime Example to convert a Instant UTC+0 to a Japan ZonedDateTime UTC+9 InstantZonedDateTime1.java package com.mkyong.date; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; public class InstantZonedDateTime1 { public static void main(String[] argv) { // Z = UTC+0 Instant instant = Instant.now(); …

Read more