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 MVC – WebMvcConfigurerAdapter is deprecated

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 @Controller and @RestController Annotations

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 MVC – How to get client IP address

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 REST API Validation

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 @PathVariable – Why is value truncated after the last (.)dot?

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 – Refactoring a jQuery Ajax Post example

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 Spring MVC – Catch the exceptions thrown by view page

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 How to register a servlet filter in Spring MVC

In this article, we will show you how to validate the submitted form values with Spring validator and Hibernate Validator (bean validation). Technologies used : Spring 4.1.6.RELEASE Hibernate Validator 5.1.3.Final 1. Hibernate Validator The Hibernate validator will be fired if @Valid is provided. import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty String name; //… } @RequestMapping(value […]

Read more Combine Spring validator and Hibernate validator

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 Form – Check if a field has an error

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 – How to set active profile

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 Spring MVC – Beans loaded twice

For self-reference, this article shows you how to create a Abstract class for Spring Controller, or a template method design pattern. 1. Abstract Controller In Abstract class, the @Controller annotation is optional, your implemented class will apply it. AbstractResultController.java package com.mkyong.web.controller; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; […]

Read more Spring MVC Abstract Controller example

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 Spring MVC hello world example (Gradle and JSP)

Developing a Spring MVC, using a JSP file as a View resource. example.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body> <h1>Spring MVC web application</h1> </body> </html> Above is a simple JSP page, but hits the following jstl error? SEVERE: Servlet.service() for servlet mvc-dispatcher threw exception org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either […]

Read more The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved

In Spring MVC + JSP view page environment. index.jsp <html> <head> <title>Welcome!</title> <c:url var="assets" value="/resources/abc" /> <link href="${assets}/css/style.min.css" rel="stylesheet"> <script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />"> </script> </head> … </html> In the Spring config file, mapped a resource path, mvc-dispatcher-servlet.xml <beans … <context:component-scan base-package="com.mkyong.test" /> <mvc:resources mapping="/resources/**" location="/resources/" /> </beans> 1. Problem After deployed, Spring MVC can’t get […]

Read more JSP – jsessionid appear in CSS and JS link

In this tutorial, we will show you how to include static resources like JavaScript or CSS in a JSP page. Summary steps : Put static resources like cs, js or images into this folder webapp\resources Create a Spring mvc:resources mapping Include in JSP page via JSTL tag c:url or Spring tag spring:url P.S This project […]

Read more Spring MVC – How to include JS or CSS files in a JSP page

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 – find location using IP Address (jQuery + Google Map)

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 @ExceptionHandler 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 Spring MVC and List Example

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 According to TLD, tag form:input must be empty, but is not

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 Spring REST @RequestMapping extract incorrectly if value contains ‘.’

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 ContentNegotiatingViewResolver 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 Spring 3 MVC and JSR303 @Valid example

Problem Developing RSS with Spring MVC, extends “AbstractRssFeedView“, hit following error message during application start up. Caused by: java.lang.NoClassDefFoundError: com/sun/syndication/feed/WireFeed at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getDeclaredConstructors(Class.java:1836) //… Caused by: java.lang.ClassNotFoundException: com.sun.syndication.feed.WireFeed at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 41 more Solution Spring MVC using “ROME” to generate RSS feed. For Maven, include below dependency […]

Read more ClassNotFoundException : com.sun.syndication.feed.WireFeed

Problem XML development in Spring MVC, via oxm , hit “HierarchicalStreamReader” class not found exception? Caused by: java.lang.ClassNotFoundException: com.thoughtworks.xstream.io.HierarchicalStreamReader at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 49 more Solution The class “HierarchicalStreamReader” class belong to “xstream.jar“. If you are using Maven, declares following dependency in your pom.xml file. <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.3.1</version> </dependency> Note For […]

Read more ClassNotFoundException : com.thoughtworks.xstream.io.HierarchicalStreamReader

Problem Recently, just converted the Spring MVC xml-based form controller to annotation-based form controller, and hits the following error message. SEVERE: Neither BindingResult nor plain target object for bean name ‘customerForm’ available as request attribute java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘customerForm’ available as request attribute Above error message is clearly […]

Read more Spring MVC – Neither BindingResult nor plain target object for bean name ‘xxx’ available as request attribute.

Spring uses MultipartResolver interface to handle the file uploads in web application, two of the implementation : StandardServletMultipartResolver – Servlet 3.0 multipart request parsing. CommonsMultipartResolver – Classic commons-fileupload.jar Tools used in this article : Spring 4.3.5.RELEASE Maven 3 Tomcat 7 or 8, Jetty 9 or any Servlet 3.0 container In a nutshell, this article shows […]

Read more Spring MVC file upload example

Problem In Spring MVC application, while clicking on the file upload button, it hits the following property type conversion error? Failed to convert property value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [byte[]] for property file; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [byte] for property file[0]: PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned […]

Read more Spring MVC failed to convert property value in file upload form