Monday, 19 November 2018

Spring mvc: SimpleUrlHandlerMapping annotation based configuration

In my previous post, I explained an example of SimpleUrlHandlerMapping using xml based approach. In this post, I am going to rewrite the same example using annotation based approach.

         <bean
         class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
                  <property name="mappings">
                           <value>
                                    /hello=helloMsg
                                    /welcome=helloMsg
                                    /*/welcome=helloMsg
                           </value>
                  </property>
         </bean>

         <bean id="helloMsg" class="com.sample.myApp.controllers.HelloWorldController" />

Above configurations can be written like below.

@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
         SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();

         Map<String, Object> urlMap = new HashMap<>();
         urlMap.put("/hello", helloMsg());
         urlMap.put("/welcome", helloMsg());
         urlMap.put("/*/welcome", helloMsg());
         simpleUrlHandlerMapping.setUrlMap(urlMap);

         return simpleUrlHandlerMapping;
}

@Bean
public HelloWorldController helloMsg() {
         return new HelloWorldController();
}

Find the below working application.

ApplicationConfig.java
package com.sample.myApp.configs;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;

import com.sample.myApp.controllers.HelloWorldController;

@Configuration
public class ApplicationConfig {
 @Bean
 public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
  SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();

  Map<String, Object> urlMap = new HashMap<>();
  urlMap.put("/hello", helloMsg());
  urlMap.put("/welcome", helloMsg());
  urlMap.put("/*/welcome", helloMsg());
  simpleUrlHandlerMapping.setUrlMap(urlMap);

  return simpleUrlHandlerMapping;
 }

 @Bean
 public HelloWorldController helloMsg() {
  return new HelloWorldController();
 }

}


HelloWorldController.java
package com.sample.myApp.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController {

 @Override
 protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  ModelAndView modelAndView = new ModelAndView("hello");

  modelAndView.addObject("message", "Welcome to Spring MVC framework");
  return modelAndView;

 }

}

Create hello.jsp file under WEB-INF/jsp folder.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Spring Web MVC</title>
</head>
<body>
 <h2>${message}</h2>
</body>
</html>


Create web.xml, HelloWorld-servlet.xml file under WEB-INF folder.

web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:component-scan
  base-package="com.sample.myApp" />

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

</beans>

Create index.jsp under webapp folder.

index.jsp
<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>


Total project structure looks like below.


Run the application on server and hit any of below urls.

You will get the message 'Welcome to Spring MVC framework'.




Previous                                                 Next                                                 Home

Spring mvc: SimpleUrlHandlerMapping example

SimpleUrlHandlerMapping implements HandlerMapping interface, provides the mapping from URLS to the request handler beans.

Example
<bean
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
         <property name="mappings">
                  <value>
                           /hello=helloMsg
                           /welcome=helloMsg
                           /*/welcome=helloMsg
                  </value>
         </property>
</bean>

<bean id="helloMsg" class="com.sample.myApp.controllers.HelloWorldController" />

As you see above snippet, the urls /hello, /welcome and /*/welcome are mapped to HelloWorldController.

Find the below working application.

HelloWorldController.java
package com.sample.myApp.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController {

 @Override
 protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  ModelAndView modelAndView = new ModelAndView("hello");

  modelAndView.addObject("message", "Welcome to Spring MVC framework");
  return modelAndView;
 }

}


Create hello.jsp file under WEB-INF/jsp folder.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Spring Web MVC</title>
</head>
<body>
 <h2>${message}</h2>
</body>
</html>


Create web.xml, HelloWorld-servlet.xml files under WEB-INF directory

web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <bean
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
   <value>
    /hello=helloMsg
    /welcome=helloMsg
    /*/welcome=helloMsg
   </value>
  </property>
 </bean>

 <bean id="helloMsg"
  class="com.sample.myApp.controllers.HelloWorldController" />

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

</beans>


Create index.jsp under webapp folder.


index.jsp
<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>

Project structure looks like below.


Run the application on server and hit any of below urls.

You will get the message 'Welcome to Spring MVC framework'.



Previous                                                 Next                                                 Home

Spring mvc: RequestMapping Handler example

RequestMapping Handler provides a mapping between request url and the controllers that are going to handle this request.

@Controller
@RequestMapping("/hello")
public class HelloWorldController extends AbstractController {

         @RequestMapping(method = RequestMethod.GET)
         @Override
         protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
                           throws Exception {
                  ModelAndView modelAndView = new ModelAndView("hello");

                  modelAndView.addObject("message", "Welcome to Spring MVC framework");
                  return modelAndView;
         }

}

For example, for the request http://{SERVER_URL}/hello, RequestMappingHandlerMapping maps the request to the method handleRequestInternal.

Find the below working application.

HelloWorldController.java
package com.sample.myApp.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;

@Controller
@RequestMapping("/hello")
public class HelloWorldController {
 SimpleUrlHandlerMapping map;

 @RequestMapping(method = RequestMethod.GET)
 protected ModelAndView hello() {
  ModelAndView modelAndView = new ModelAndView("hello");

  modelAndView.addObject("message", "Welcome to Spring MVC framework");
  return modelAndView;
 }

}

Define hello.jsp file under WEB-INF/jsp folder.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Spring Web MVC</title>
</head>
<body>
 <h2>${message}</h2>
</body>
</html>


Define web.xml, HelloWorld-servlet.xml files under WEB-INF folder.

web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   
 <context:component-scan
 base-package="com.sample.myApp" />

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

</beans>

Define index.jsp under webapp folder.

index.jsp
<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>


Project structure looks like below.


Run the application on server and hit the url http://localhost:8080/springdemo/hello.







Previous                                                 Next                                                 Home

Friday, 16 November 2018

Spring mvc: BeanNameUrlHandlerMappingConfig annotation based example

This is continuation to my previous post, I explained the usage of BeanNameUrlHandlerMapping by xml configuration approach. In this post, I am going to give an example of annotation based approach.

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean name="/hello" class="com.sample.myApp.controllers.HelloWorldController" />

Java equivalent of above xml configuration looks like below.

@Configuration
public class BeanNameUrlHandlerMappingConfig {
         @Bean
         BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() {
                  return new BeanNameUrlHandlerMapping();
         }

         @Bean("/hello")
         public HelloWorldController welcome() {
                  return new HelloWorldController();
         }
}

Find the below working application.

BeanNameUrlHandlerMappingConfig.java
package com.sample.myApp.configurations;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;

import com.sample.myApp.controllers.HelloWorldController;

@Configuration
public class BeanNameUrlHandlerMappingConfig {
 @Bean
 BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() {
  return new BeanNameUrlHandlerMapping();
 }

 @Bean("/hello")
 public HelloWorldController welcome() {
  return new HelloWorldController();
 }
}


HelloWorldController.java
package com.sample.myApp.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController {

 @Override
 protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  ModelAndView modelAndView = new ModelAndView("hello");

  modelAndView.addObject("message", "Welcome to Spring MVC framework");
  return modelAndView;
 }

}

Define hello.jsp file under WEB-INF/jsp folder.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Spring Web MVC</title>
</head>
<body>
 <h2>${message}</h2>
</body>
</html>


Define web.xml, HelloWorld-servlet.xml files under WEB-INF folder.

web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   
 <context:component-scan
 base-package="com.sample.myApp" />

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

</beans>


Define index.jsp under webapp folder.

index.jsp
<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>


Project structure looks like below.


Run the application on server and hit the url http://localhost:8080/springdemo/hello.




Previous                                                 Next                                                 Home

Wednesday, 14 November 2018

Spring mvc: BeanNameUrlHandlerMapping

BeanNameUrlHandlerMapping class maps the URLs to beans with names that start with a slash ("/").

To use BeanNameUrlHandlerMapping class, we need to define that bean and specify the url mappings to the controller in <bean> tag.

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

<bean name="/hello" class="com.sample.myApp.controllers.HelloWorldController" />

Find the below working application.

HelloWorldController.java
package com.sample.myApp.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController {

 @Override
 protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  ModelAndView modelAndView = new ModelAndView("hello");

  modelAndView.addObject("message", "Welcome to Spring MVC framework");
  return modelAndView;
 }

}


Define hello.jsp file under WEB-INF/jsp folder.



hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Spring Web MVC</title>
</head>
<body>
 <h2>${message}</h2>
</body>
</html>


Define web.xml, HelloWorld-servlet.xml files under WEB-INF folder.

web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

HelloWorld-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <bean
  class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

 <bean name="/hello"
  class="com.sample.myApp.controllers.HelloWorldController" />

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

</beans>

Define index.jsp file under webapp folder.


index.jsp
<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>

Project structure looks like below.

Run the application on server and hit the url http://localhost:8080/springdemo/hello.



Previous                                                 Next                                                 Home

Spring MVC: Handler Mapping Tutorial

Spring MVC use controller pattern to serve the requests. DispatcherServlet acts as a front controller, it receives all the requests, and pass the requests to correspondent handlers with the help of handler mappings.

'org.springframework.web.servlet.HandlerMapping' interface is responsible for maping the requests to handlers. Spring provides concrete implementation to this interface, you can choose one of them based on your interest.

At the time of writing this post, below are the concrete implementations of the HandlerMapping interface.
         a. BeanNameUrlHandlerMapping,
         b. RequestMappingHandlerMapping,
         c. RequestMappingInfoHandlerMapping,
         d. SimpleUrlHandlerMapping,
         e. WebSocketHandlerMapping
        
My next posts will explain all these mappers in detail.




Previous                                                 Next                                                 Home

Spring MVC: Get http status codes

Spring provides ‘org.springframework.http.HttpStatus’ enum, it provides all the required http status codes.

Test.java
package com.sample.myApp.test;

import org.springframework.http.HttpStatus;

public class Test {
 public static void main(String ... args) {
  HttpStatus[] httpStatuses = HttpStatus.values();
  
  for(HttpStatus httpStatus : httpStatuses) {
   String reason = httpStatus.getReasonPhrase();
   int statusCode = httpStatus.value();
   
   System.out.println(statusCode + " : " + reason);
  }
 }
}

When you ran above application, you can get below kind of output.

100 : Continue
101 : Switching Protocols
102 : Processing
103 : Checkpoint
200 : OK
201 : Created
202 : Accepted
203 : Non-Authoritative Information
204 : No Content
205 : Reset Content
206 : Partial Content
207 : Multi-Status
208 : Already Reported
226 : IM Used
300 : Multiple Choices
301 : Moved Permanently
302 : Found
302 : Moved Temporarily
303 : See Other
304 : Not Modified
305 : Use Proxy
307 : Temporary Redirect
308 : Permanent Redirect
400 : Bad Request
401 : Unauthorized
402 : Payment Required
403 : Forbidden
404 : Not Found
405 : Method Not Allowed
406 : Not Acceptable
407 : Proxy Authentication Required
408 : Request Timeout
409 : Conflict
410 : Gone
411 : Length Required
412 : Precondition Failed
413 : Payload Too Large
413 : Request Entity Too Large
414 : URI Too Long
414 : Request-URI Too Long
415 : Unsupported Media Type
416 : Requested range not satisfiable
417 : Expectation Failed
418 : I'm a teapot
419 : Insufficient Space On Resource
420 : Method Failure
421 : Destination Locked
422 : Unprocessable Entity
423 : Locked
424 : Failed Dependency
426 : Upgrade Required
428 : Precondition Required
429 : Too Many Requests
431 : Request Header Fields Too Large
451 : Unavailable For Legal Reasons
500 : Internal Server Error
501 : Not Implemented
502 : Bad Gateway
503 : Service Unavailable
504 : Gateway Timeout
505 : HTTP Version not supported
506 : Variant Also Negotiates
507 : Insufficient Storage
508 : Loop Detected
509 : Bandwidth Limit Exceeded
510 : Not Extended
511 : Network Authentication Required


Previous                                                 Next                                                 Home