Wednesday, 21 November 2018

Spring mvc: @PathVariable: Handling multiple path variables.

This is continuation to my previous post, in my previous post, I explained how to bound path variables to method arguments using @PathVariable annotation. In this post, I am going to show you how can you bound multiple path variables.

If you have multiple path variables in the url, it doesn't looks good if you try to bound them to the method arguments. Suppose if there are 5 path variables, we need to write a method with 5 arguments like below.

@RequestMapping("welcome/{countryName}/{state}/{firstName}/{lastName}/{customMsg}")
public ModelAndView getWelcomeMsg(@PathVariable("countryName") String countryName,
@PathVariable("state") String state, @PathVariable("firstName") String firstName,
@PathVariable("lastName") String lastName, @PathVariable("customMsg") String customMsg) {
         .....
         .....
}

What if you want to bound 10 path variables, would you like to write a method of 10 arguments? Obviously, No.

Spring MVC provides a better way to handle multiple path variable. You can map all the path variables to map like below.

@RequestMapping("welcome/{countryName}/{userName}")
public ModelAndView getWelcomeMessage(@PathVariable Map<String, String> pathVariables) {
         String name = pathVariables.get("userName");
         String country = pathVariables.get("countryName");
         .....
         .....
}

As you see above snippet, I mapped all the path variables to a map and access the path variable value using the map.

Find the below working application.

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

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("greeting")
public class HelloWorldController {

 @RequestMapping("welcome/{countryName}/{userName}")
 public ModelAndView getWelcomeMessage(@PathVariable Map<String, String> pathVariables) {
  String name = pathVariables.get("userName");
  String country = pathVariables.get("countryName");

  ModelAndView modelAndView = new ModelAndView("hello");

  String msg = String.format("Hello %s, You are from %s", name, country);
  modelAndView.addObject("message", msg);
  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 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 file 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 the below url.






Previous                                                 Next                                                 Home

Spring mvc: @PathVariable tutorial

@PathVariable annotation is used to bound a method parameter to a URI template variable.

For example, consider below snippet, I bound the URI template variable (Template variable are declared in curly braces) userName to the method parameter name.

@Controller
@RequestMapping("greeting")
public class HelloWorldController {

         @RequestMapping("welcome/{userName}")
         public ModelAndView getWelcomeMessage(@PathVariable("userName") String name) {
                  ModelAndView modelAndView = new ModelAndView("hello");

                  String msg = String.format("Hello %s, Welcome to spring MVC programming", name);
                  modelAndView.addObject("message", msg);
                  return modelAndView;
         }

}

If I hit the url 'http://localhost:8080/springdemo/greeting/welcome/krishna', then the method parameter name is bound with value "krishna".

If I hit the url 'http://localhost:8080/springdemo/greeting/welcome/Deeepa', then the method parameter name is bound with value "Deepa".

Find the below working application.

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("greeting")
public class HelloWorldController {

 @RequestMapping("welcome/{userName}")
 public ModelAndView getWelcomeMessage(@PathVariable("userName") String name) {
  ModelAndView modelAndView = new ModelAndView("hello");

  String msg = String.format("Hello %s, Welcome to spring MVC programming", name);
  modelAndView.addObject("message", msg);
  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 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 file 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 the below url.

Can I bound multiple path variables in one url?
Yes, you can bound any number of path variables in one url.
For example,
@RequestMapping("welcome/{countryName}/{userName}")
public ModelAndView getWelcomeMessage(@PathVariable("userName") String name, @PathVariable("countryName") String country)

In the above example, countryName is mapped to the method argument country, username is mapped to the method argument country.

Update HelloWorldController class like below and rerun the application.


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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("greeting")
public class HelloWorldController {

 @RequestMapping("welcome/{countryName}/{userName}")
 public ModelAndView getWelcomeMessage(@PathVariable("userName") String name,
   @PathVariable("countryName") String country) {
  ModelAndView modelAndView = new ModelAndView("hello");

  String msg = String.format("Hello %s, You are from %s", name, country);
  modelAndView.addObject("message", msg);
  return modelAndView;
 }

}


When you hit the url ‘http://localhost:8080/springdemo/greeting/welcome/India/krishna’.
, you can able to see below kind of message.







Previous                                                 Next                                                 Home

Tuesday, 20 November 2018

Spring mvc: @RequestMapping annotation example

@RequestMapping annotation is used to map the web requests to methods in request-handling classes.

@Controller
public class HelloWorldController {

         @RequestMapping("welcome")
         public ModelAndView getWelcomeMessage() {
                  ModelAndView modelAndView = new ModelAndView("hello");
                  modelAndView.addObject("message", "Welcome to spring MVC programming");
                  return modelAndView;
         }

}

For example, as you see above snippet, I mapped the url /welcome to getWelcomeMessage.

When you hit the request url {SERVER_URL}/welcome, getWelcomeMessage() method is invoked.

Can I add @RequestMapping on a class?
Yes you can add @RequestMapping annotation to a class.

@Controller
@RequestMapping("greeting")
public class HelloWorldController {

         @RequestMapping("welcome")
         public ModelAndView getWelcomeMessage() {
                  ModelAndView modelAndView = new ModelAndView("hello");
                  modelAndView.addObject("message", "Welcome to spring MVC programming");
                  return modelAndView;
         }
}


When you hit the url {SERVER_URL}/greeting/welcome (class url mapping followed by method url mapping), getWelcomeMessage() method is called.

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.servlet.ModelAndView;

@Controller
@RequestMapping("greeting")
public class HelloWorldController {

 @RequestMapping("welcome")
 public ModelAndView getWelcomeMessage() {
  ModelAndView modelAndView = new ModelAndView("hello");
  modelAndView.addObject("message", "Welcome to spring MVC programming");
  return modelAndView;
 }

 @RequestMapping("hello")
 public ModelAndView getHelloMessage() {
  ModelAndView modelAndView = new ModelAndView("hello");
  modelAndView.addObject("message", "Hello, How are you");
  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 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 file under webapp folder.


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

Project structure looks like below.


Run the application on server.

When you hit the url ‘http://localhost:8080/springdemo/greeting/welcome’, you can able to see below kind of window.



When you hit the url ‘http://localhost:8080/springdemo/greeting/hello’, you can able to see below kind of window.



Previous                                                 Next                                                 Home

Monday, 19 November 2018

Spring mvc: Multi Action controller class

In all my previous posts, I added a request mapping url in the controller class.
@Controller
public class HelloWorldController {

         @RequestMapping("welcome")
         public ModelAndView getWelcomeMessage() {
                  ModelAndView modelAndView = new ModelAndView("hello");
                  modelAndView.addObject("message", "Welcome to spring MVC programming");
                  return modelAndView;
         }

}

Spring provides greater flexibility such that, you can add more url patterns in same controller class.

@Controller
public class HelloWorldController {

         @RequestMapping("welcome")
         public ModelAndView getWelcomeMessage() {
                  ModelAndView modelAndView = new ModelAndView("hello");
                  modelAndView.addObject("message", "Welcome to spring MVC programming");
                  return modelAndView;
         }

         @RequestMapping("hello")
         public ModelAndView getHelloMessage() {
                  ModelAndView modelAndView = new ModelAndView("hello");
                  modelAndView.addObject("message", "Hello, How are you");
                  return modelAndView;
         }

}

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.servlet.ModelAndView;

@Controller
public class HelloWorldController {

 @RequestMapping("welcome")
 public ModelAndView getWelcomeMessage() {
  ModelAndView modelAndView = new ModelAndView("hello");
  modelAndView.addObject("message", "Welcome to spring MVC programming");
  return modelAndView;
 }

 @RequestMapping("hello")
 public ModelAndView getHelloMessage() {
  ModelAndView modelAndView = new ModelAndView("hello");
  modelAndView.addObject("message", "Hello, How are you");
  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 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>


Project structure looks like below.

Run the application on server.





Previous                                                 Next                                                 Home