Spring @PathVariable Annotation

In Spring Web MVC, we can use the @PathVariable annotation to access the captured URI variables. Table of contents: 1. Basic Mapping 2. Basic Mapping – Different Name 3. Basic Mapping – Class and method levels 4. Multiple Captured URI Variables 5. Multiple Captured URI Variables – Map Version 6. Regex Mapping 7. @PathVariable variables …

Read more

Spring MVC – WebMvcConfigurerAdapter is deprecated

I migrated from Spring 3 to Spring 5 and found out the WebMvcConfigurerAdapter class is deprecated; what should we do? SpringWebConfig.java package com.mkyong.helloworld.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan({ "com.mkyong.helloworld.web" }) public class SpringWebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) …

Read more

Spring @RequestBody Annotation

In the Spring framework, the @RequestBody annotation maps the web request’s body to the method’s parameter, usually a domain object or a Map. Table of contents 1. Spring @RequestBody example 2. Spring @RequestBody example – Map version 3. Download Source Code 4. References 1. Spring @RequestBody example Below is a @RequestBody example to map the …

Read more

Spring @Controller and @RestController Annotations

This article shows you what @Controller and @RestController are and their differences. Table of contents: 1. Spring @Controller annotation 2. Spring @RestController annotation 3. Download Source Code 4. References 1. Spring @Controller annotation Spring 2.5 introduced the @Controller as the web controller for the MVC architecture. Spring 3.0 introduced the @ResponseBody to return the method’s …

Read more

Spring @ResponseBody Annotation

In the Spring framework, the @ResponseBody annotation tells the Spring framework to write the method’s return type to the HTTP response body (not placed in a Model or interpreted as a view name). Spring 3.0 introduced the @ResponseBody annotation on the method level. Spring 4.0 enhanced the @ResponseBody annotation to put on the class level, …

Read more

Maven – How to create a multi module project

In this tutorial, we will show you how to use Maven to manage a Multi-module project containing four modules : Password module – Interface only. Password md5 module – Password module implementation, MD5 password hashing. Password sha module – Password module implementation, SHA password hashing. Web module – A simple MVC web app to hash …

Read more

Spring MVC – How to get client IP address

In Spring framework, you can @Autowired a HttpServletRequest in any Spring managed bean directly, and later get the client’s IP address from the request headers WebUtils.java package com.mkyong.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; @Component public class WebUtils { private HttpServletRequest request; @Autowired public void setRequest(HttpServletRequest request) { this.request = request; } private static String …

Read more

Spring REST API Validation

In Spring MVC, just annotate a @Valid on the @RequestBody to fire the validation process. Note For complete source code, please refer to this – Spring Boot Ajax example P.S Tested with Spring Boot 1.5.1.RELEASE (Spring 4.3.6.RELEASE) 1. JSR 303 Validation Add JSR303 annotations on a bean. package com.mkyong.model; import org.hibernate.validator.constraints.NotBlank; public class SearchCriteria { …

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 MVC + Mustache JS template example

In this tutorial, we will show you a Spring MVC + Mustache JS template web application example. Technologies used : Spring 4.2.4.RELEASE mustache.js JDK 1.8.0_66 Jackson 2.7 Eclipse 4.3 Tomcat 8 Maven 3 Bootstrap 3 Note This solution is still working, but recommend this simple Spring Boot + JMustache solution. In Spring, we can use …

Read more

jQuery – Ajax request return 200 OK but error event is fired?

Review a jQuery Ajax form submit. $(document).ready(function () { $("#hostingForm").submit(function (e) { e.preventDefault(e); var data = {} data["id"] = $("#id").val(); data["domain"] = $("#domain").val(); data["name"] = $("#name").val(); //… $.ajax({ type: "POST", contentType: "application/json", url: "{{home}}/hosting/update", data: JSON.stringify(data), dataType: ‘json’, timeout: 600000, success: function (data) { console.log("SUCCESS: ", data); }, error: function (e) { console.log("ERROR: ", e); …

Read more

Spring @PathVariable – Why is value truncated after the last (.)dot?

Review the below @PathVariable example. @RequestMapping("/site") public class SiteController { @RequestMapping(value = "/{q}", method = RequestMethod.GET) public ModelAndView display(@PathVariable("q") String q) { return getModelAndView(q, "site"); } } See the following cases : For input /site/google, q = google For input /site/google.com, q = google where is the .com? For input /site/google.com.my, q = google.com For …

Read more

Spring MVC – Refactoring a jQuery Ajax Post example

Reviewing a jQuery Ajax form POST and Spring MVC example, find out the following patterns : <script> jQuery(document).ready( function($) { $("#btn-save").click(function(event) { var id = $(‘#id’).val(); var domain = $(‘#domain’).val(); var name = $(‘#name’).val(); var desc = $(‘#desc’).val(); var tags = $(‘#tags’).val(); var afflink = $(‘#afflink’).val(); var cdn = $("#cdn").prop("checked") ? true : false; var …

Read more

Spring MVC – Catch the exceptions thrown by view page

Here’s the scenario, the controller returns a ModelAndView, and an exception is thrown while rendering the JSP view page, reason behind is one of message code is not found. org.apache.jasper.JasperException: org.springframework.context.NoSuchMessageException: No message found under code ‘Diff.userform.password’ for locale ‘en_US’. org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) An exception is thrown and render an HTTP 500 error …

Read more

How to register a servlet filter in Spring MVC

In a nutshell, a servlet filter lets you intercepts requests and responses on your web application. This article shows you how to register a servlet filter in Spring XML and JavaConfig. 1. Servlet Filter Review the following custom filter, it will catch any exceptions and redirect to an error page. package com.mkyong.form.web; import java.io.IOException; import …

Read more

Spring – Mixing XML and JavaConfig

Spring examples to show you how to mix both Spring XML and JavaConfig together. 1. Load JavaConfig From Spring XML A Spring MVC example, uses @Configuration to load everything, and you want integrate with web.xml SpringWebConfig.java package com.mkyong.form.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc …

Read more

Spring MVC Form – Check if a field has an error

In this article, we will show you few Spring form tag examples to check if a field has an error message. Review the following Spring MVC bean validation example : Technologies used : Spring 4 JSTL 1.2 //Bean validation import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty String name; //… } //Controller class @RequestMapping(value = "/users", …

Read more

Spring MVC – How to set active profile

In this example, we will show you how to set active @Profile in a Spring MVC web application. @Profile Examples @Configuration public class AppConfig { @Profile("dev") @Bean public CacheManager cacheManager() { //… } @Profile("live") @Bean public EhCacheManagerFactoryBean ehCacheCacheManager() { //… } @Profile("testdb") @Bean public DataSource dataSource() { //… } } To set active @Profile in …

Read more

Spring MVC + Logback SLF4j example

In this tutorial, we will show you how to setup slf4j and logback in a Spring MVC web application. Technologies used : Spring 4.1.6.RELEASE Logback 1.1.3 Maven 3 or Gradle 2.0 Tomcat 7 Eclipse 4.4 Note By default, Spring is using the Jakarta Commons Logging API (JCL), read this. To setup logback framework you need …

Read more

Spring MVC – Beans loaded twice

A Spring MVC web application, noticed all the Spring’s beans are loaded twice!? package com.mkyong.config.db; @Configuration public class MongoDevConfig { private final static Logger logger = LoggerFactory.getLogger(MongoDevConfig.class); @Bean MongoDbFactory mongoDbFactory() throws Exception { logger.debug("Init…… MongoDbFactory() in production mode!"); //… return new new SimpleMongoDbFactory(mongo, "db");; } } During Application startup : 2015-03-05 17:52:32 DEBUG c.m.config.MongoLiveConfig – …

Read more

Ant – Spring MVC and WAR file Example

In this tutorial, we will show you how to use Ant build script to manage a Spring MVC web application project, create a WAR file and deploy to Tomcat. Technologies used : Eclipse 4.2 JDK 1.7 Ant 1.9.4 Ant-Ivy 2.4 logback 1.1.2 jstl 1.2 Spring 4.1.3.RELEASE Tomcat 7 1. Project Directory Review the final project …

Read more

Spring MVC hello world example (Gradle and JSP)

This tutorial shows you how to create a Spring Web MVC application with the Jakarta Server Pages (JSP; formerly JavaServer Pages) template. Technologies and tools used: Java 11 Spring 5.2.22.RELEASE JSP JSTL 1.2 Servlet API 4.0.1 Bootstrap 5.2.0 (webjars) IntelliJ IDEA Gradle 7.5.1 Gradle Gretty plugin 3.0.9 for embedded servlet containers (Tomcat 9 and Jetty …

Read more

How To Get HTTP Request Header In Java

This example shows you how to get the HTTP request headers in Java. To get the HTTP request headers, you need this class HttpServletRequest : 1. HttpServletRequest Examples 1.1 Loop over the request header’s name and print out its value. WebUtils.java package com.mkyong.web.utils; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; public class WebUtils { …

Read more

Spring MVC – find location using IP Address (jQuery + Google Map)

In this tutorial, we show you how to find a location using an IP address, with the following technologies : Spring MVC frameworks. jQuery (Ajax Request). GeoLite database. Google Map. Review the tutorial’s flows A page with a text input and button. Type an IP address, and clicks on the button. jQuery fires an Ajax …

Read more

Spring MVC @ExceptionHandler Example

In this tutorial, we show you how to do exception handling in Spring MVC frameworks. Normally, we use @ExceptionHandler to decide which “view” should be returned back if certain exception is raised. P.S This @ExceptionHandler class is available since Spring 3.0 1. Project Structure Review the project directory structure, a standard Maven project. 2. Custom …

Read more

Spring MVC and List Example

In this tutorial, we show you how to print the List values via JSTL c:forEach tag. P.S This web project is using Spring MVC frameworks v3.2 1. Project Structure Review the project directory structure, a standard Maven project. 2. Project Dependencies Add Spring and JSTL libraries. pom.xml <properties> <spring.version>3.2.2.RELEASE</spring.version> <jstl.version>1.2</jstl.version> </properties> <dependencies> <!– jstl –> …

Read more

According to TLD, tag form:input must be empty, but is not

Problem Developing a search form with the Spring MVC framework. /WEB-INF/pages/tools/webserver.jsp – Spring mvc + form tag <form:form method="post" commandName="searchForm" action="${pageContext.request.contextPath}/tools/webserver/" class="navbar-form pull-left" id="search-form"> Type a website : <form:input path="domainName" type="text" width="165px" placeholder="example – google.com" /> <button type="submit" class="btn btn-top-margin">Search</button> </form:form> Spring Controller @Controller @RequestMapping(value = "/tools", method = RequestMethod.GET) public class ToolsController { @RequestMapping(value …

Read more

Spring REST @RequestMapping extract incorrectly if value contains ‘.’

Problem See following Spring REST example, if a request such as “http://localhost:8080/site/google.com” is submitted, Spring returns “google“. Look like Spring treats “.” as file extension, and extract half of the parameter value. SiteController.java package com.mkyong.web.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/site") public class SiteController { @RequestMapping(value = "/{domain}", method …

Read more

Google App Engine + JDO + Spring MVC, CRUD example

Note This tutorial is more on practice guide, please refer to this official Using JDO in datastore for detail explanation. See following code snippets to perform CRUD on GAE datastore, using Java Data Objects(JDO). Just annotate the Customer with JDO annotation and perform the CRUD via PersistenceManager. Add Customer c = new Customer(); c.setName(name); PersistenceManager …

Read more

Google App Engine + Spring MVC, CRUD example with datastore low level api

GAE datastore Refer to this official “Using datstore guide” to understand what is GAE datastore. See following code snippets to perform CRUD for Google App Engine datastore, Java, using low-level API. Add Store a customer into datastore, with “name” as the key. Key customerKey = KeyFactory.createKey("Customer", "your name"); Entity customer = new Entity("Customer", customerKey); customer.setProperty("name", …

Read more

Spring 3 REST hello world example

In Spring 3, old RequestMapping class is enhanced to support RESTful features, which makes Spring developers easier to develop REST services in Spring MVC. In this tutorial, we show you how to use Spring 3 MVC annotations to develop a RESTful style web application. 1. Project Directory Review the project folder structure. 2. Project Dependency …

Read more

Spring 3 MVC ContentNegotiatingViewResolver example

Spring 3, ContentNegotiatingViewResolver, is an interesting view resolver, which allow you to output a same resource (content or data) to different type of views like JSP, XML, RSS, JSON and etc. Put it simple, see following web requested URL, which will return in different views. https://mkyong.com/fruit/banana.rss , returned as RSS file. https://mkyong.com/fruit/banana.xml , returned as …

Read more

Spring 3 MVC and JSR303 @Valid example

In Spring 3, you can enable “mvc:annotation-driven” to support JSR303 bean validation via @Valid annotation, if any JSR 303 validator framework on the classpath. Note Hibernate Validator is the reference implementation for JSR 303 In this tutorial, we show you how to integrate Hibernate validator with Spring MVC, via @Valid annotation, to perform bean validation …

Read more