In this post, we will see how to integrate Spring MVC with log4j.
Logging is essential part of programming. It helps developer to track code workflow and fix bugs efficiently. If we get any issue in the code, we check logs for that workflow or functionality.
Log4j is fast , reliable logging framework and can be easily integrated with the code.

We will extend Spring MVC hello world example and enable log4j logging into it.If you are wondering how to use log4j in maven project, you can follow log4j maven integration example.
You only need to follow below steps to enable log4j in Spring MVC.
  • Put log4j jar in classpath and you can use maven to do it for you by adding dependency to pom.xml.
  • Create log4j.properties and put it in the classpath (resource folder in maven)
Project structure:

Step 1:
Add log4j dependency in pom.xml for maven project. For non maven project , put log4j.jar in Web-INF/lib folder.
<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
</dependency>

Your pom.xml will look as below:
<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.arpit.java2blog</groupId>
	<artifactId>SpringMVCLog4JExample</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVCLog4JExample Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>


		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
</dependency>
	</dependencies>
	<build>
		<finalName>SpringMVCLog4JExample</finalName>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>

	</build>
	<properties>
		<spring.version>4.2.1.RELEASE</spring.version>
		<jdk.version>1.6</jdk.version>
	</properties>
</project>
Step 2: 
Create log4j.properties as below and put it in the java/main/resources folder.
log4j.rootLogger=DEBUG, console, file

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
log4j.appender.file.File=applicationLogs.log

Step 3:
Change HelloWorldController.java as below:
package org.arpit.java2blog.springmvc.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class HelloWorldController {
 
	private static final Logger logger = Logger.getLogger(HelloWorldController.class);
 @RequestMapping("/helloworld")
 public ModelAndView hello() {
 
  String helloWorldMessage = "Hello world from java2blog!";
	logger.info("This is info message");
	logger.error("This is error message");
  
  return new ModelAndView("hello", "message", helloWorldMessage);
 }
}

Step 4:
When you run the project, you will get below screen.
When you click on the link, you will get below screen.
When you will see logs, you will get below entries.

As you can see, logging is enable for our Spring MVC project.

Logging is essential part of programming. It helps developer to track code workflow and fix bugs efficiently. If we get any issue in the code, we check logs for that workflow or functionality.

Log4j is fast , reliable logging framework and can be easily integrated with the code. It is possible to enable logging at run time without using

There are two ways, you can do logging using log4j.
  1. log4j.properties
  2. log4j.xml
In this post, we will see how to configure using log4.properties

1) Create simple maven java project.

2) Put log4j entry in pom.xml .

<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
</dependency>

3) Update maven project to download require jar

Right click on project-> Maven -> update project

4) Create log4j.properties file

This file is main file for log4j configuration. It has information about log levels, log appenders.

Log to console:

If you want to log to console, you need to have following lines in log4j.properties.
log4j.rootLogger=DEBUG, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
Log to file :

If you want to log to console, you need to have following lines in log4j.properties and also you need to provide log file name too.
log4j.rootLogger=DEBUG, console
log4j.rootLogger=DEBUG,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
log4j.appender.file.File=applicationLogs.log

Log to console and file both :

If you want to log on both to console and file, you can use below code:
log4j.rootLogger=DEBUG, console, file

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
log4j.appender.file.File=applicationLogs.log

5) Sample class for Logger 

Create a class called "LoggingMain.java" in src/main/java in package org.arpit.java2blog
package org.arpit.java2blog;

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class LoggingMain {

  private static final Logger logger = LogManager.getLogger(LoggingMain.class);
 public static void main(String[] args) {
 
  PropertyConfigurator.configure("log4j.properties");
  logger.info("Hello world");
  logger.info("we are in logger info mode");

 }

}

6) Run program:

When you run above program , you will get below output to console and file(applicationLogs.log)
0 [main] INFO org.arpit.java2blog.LoggingMain  - Hello world
1 [main] INFO org.arpit.java2blog.LoggingMain  - we are in logger info mode
Bingo!! we have successfully configured log4j using properties file in maven project.

In this post , we will see how to check or uncheck checkbox or radio button in jQuery.
You can use prop() method to set "checked" as true or false. If you set it to true, it will be checked else it will be unchecked.
prop() function required jQuery 1.6 or more.
To check a checkbox/radio button.
$('selector').prop( "checked", true );
To uncheck a checkbox/radio button.
$('selector').prop( "checked", false);
Lets understand with the help of simple example:
<html>
<head>
<title>jQuery check/uncheck a check box example</title>
 <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<body>

<h1>jQuery check / uncheck a check box example</h1>

<script type="text/javascript">

  $(document).ready(function(){
 
    $("#checkIt").click(function () {

 $('#checkme').prop( "checked", true );

    });

    $("#UnCheckIt").click(function () {

 $('#checkme').prop( "checked", false );

    });

  });
</script>
</head><body>

<input id="checkme" type="checkbox" name="checkme">Check Me</input>

<br/>
<br/>
<input type='button' value='Check It' id='checkIt'>
<input type='button' value='UnCheck It' id='UnCheckIt'>

</body>
</html>

Live Demo: 

jQuery check/uncheck a check box example on jsbin.com

In this post, we will see how to refresh a page using jQuery.
You can use location.reload() method of jQuery to reload the page. It is same as pressing f5 for refreshing a page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Reload/Refresh a Page in jQuery</title>
    <script type="text/javascript"
        src="http://code.jquery.com/jquery-latest.js">
    </script>
 
    <script type="text/javascript">
        $(document).ready(function() {
            $('#reload').click(function() {
                location.reload();
            });
        });     
    </script>
</head>
<body>
    <input id="reload" type="button" value="reload" />
</body>
</html>
Let me know if it works for your browser or not.

In this post,  we are going to see jQuery after and insertAfter methods.
Both do the same task, insert text or html after every selected elements but syntax is quite different. 

Syntax for after():

$("selectors").after("element to be inserted") ;
Example :
$("div").after("<p class='red'>inserting using after</p>");

Syntax for insertAfter() :

$("element to be inserted") .insertAfter("div");
Example:
$("<p class='blue'>inserting using insertAfter</p>").insertAfter("div");
Let's understand with the help of example:
<!doctype>
<html>
<head>
  <title>Jquery after and insertAfter example example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery after and insertAfter example example</h2>
<style>
   .red{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
   }
 .blue{
        border:3px dotted red;
        color:blue;
        font-family: arial narrow;
   }
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#afterButton").click(function(){
         $("div").after("<p class='red'>inserting using after</p>");
      });
$("#insertAfterButton").click(function(){
         $("<p class='blue'>inserting using insertAfter</p>").insertAfter("div");
      });
$("#reset").click(function(){
         location.reload();
   });
 });

</script>
<body>
  <button id="afterButton">Using after</button>

  <button id="insertAfterButton">Using insertAfter</button>
<button id="reset">Reset</button>
<div>
 Hello world from java2blog!!!!
   </div>
<div>
 Welcome to JQuery.
  </div>
</body>
</html>
Live demo: Jquery after and insertAfter example example on jsbin.com

With jQuery toggleClass method, you can add or remove class depending on its presence.  If class is present , it will be removed and if class is not present , it will be applied.
jQuery.toggleClass( classname [, function(index,currentclass) ] [, state ] )
classname: Required. It is classname for which you want to toggle class
function(index,currentclass) :  Optional .It is function that will be returned with one or more classname to be removed or added.
index : It will provide you index of element in the set.
currentclass: It is current class for selected elements.
State : Optional.If state is true, classname will only be added and if it false, className will be only removed.

jQuery toggleClass example: 

Lets create html file named jQuerytoggleClass.html as below
<!doctype>
<html>
<head>
  <title>JQuery Toggle to Show/Hide Content</title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery toggleClass example</h2>
<style>
   .divClass{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
   }
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#mybutton").click(function(){
         $("div").toggleClass("divClass");
      });
   });
</script>
<body>
  <button id="mybutton">Click to toggle class</button>
  <div>
 Hello world from java2blog!!!!
    <br/>
 Welcome to JQuery.
  </div>
</body>
</html>
Live demo:
JQuery toggleClass example
Explanation:
  • $(document).ready(function() : This function will get called when fully DOM is loaded.
  • $("button").click(function(event) : This function will get called when "click to toggle class" button is clicked.
  • $("div").toggleClass("divClass"): Here we are calling toggleClass for div elements. 

In this post, we will see jquery hide ,show and toggle example.

jQuery hide()

It is used to hide matched element. With jQuery, you can hide elements with hide method
Example :
$("#hide").click(function(){
  $("p").hide();
});
Syntax :
$(selector).hide(speed,callback);
The optional speed parameter is used to specify the speed of the hiding, and can take the following values: "slow", "fast", or milliseconds.
The optional callback parameter is a function that will be executed after the hide() method completes. The following example demonstrates the speed parameter with hide():
$("button").click(function(){
  $("p").hide(1000);
});
Create html file as jQueryHide.html
 
<!doctype>
<html>
<head>
  <title>JQuery Toggle to Show/Hide Content</title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery Toggle Example to Display and Hide Content</h2>
<style>
   div{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
   }
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#button").click(function(){
         $(".mydiv").hide();
      });
   });
</script>
<body>
  <button id="button">Click to Hide Content</button>
  <div class="mydiv">
 <p>Hello world from java2blog!!!!</p>
 <p>Welcome to JQuery.</p>
  </div>
</body>
</html>
Live demo: JQuery Hide Content on jsbin.com

jQuery show()

It is used to show matched element. With jQuery, you can show elements with show method Example :
$("#hide").click(function(){
  $("p").show();
});
Syntax :
 
$(selector).show(speed,callback);
The optional speed parameter is used to specify the speed of the showing, and can take the following values: "slow", "fast", or milliseconds.
The optional callback parameter is a function that will be executed after the show() method completes.
The following example demonstrates the speed parameter with show():
$("button").click(function(){
  $("p").show(1000);
});
Create html file as jQueryShow.html
<!doctype>
<html>
<head>
  <title>JQuery Toggle to Show/Hide Content</title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery Toggle Example to Display and Hide Content</h2>
<style>
   div{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
  display :  none;
   }
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#button").click(function(){
         $(".mydiv").show();
      });
   });
</script>
<body>
  <button id="button">Click to Show Content</button>
  <div class="mydiv">
 <p>Hello world from java2blog!!!!</p>
 <p>Welcome to JQuery.</p>
  </div>
</body>
</html>
Live demo: JQuery Show Content on jsbin.com

jQuery toggle()

With jQuery, you can toggle between the hide() and show() methods with the toggle() method. Shown elements are hidden and hidden elements are shown:
Example :
 
$("button").click(function(){
  $("p").toggle();
});
Syntax:
$(selector).toggle(speed,callback);
The optional speed parameter can take the following values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after toggle() completes. Example:
<!doctype>
<html>
<head>
  <title>JQuery Toggle to Show/Hide Content</title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery Toggle Example to Display and Hide Content</h2>
<style>
   div{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
        display:none;
   }
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#mybutton").click(function(){
         $(".mydiv").toggle();
      });
   });
</script>
<body>
  <button id="mybutton">Click to Show/Hide Content</button>
  <div class="mydiv">
 <p>Hello world from java2blog!!!!</p>
 <p>Welcome to JQuery.</p>
  </div>
</body>
</html>
Live Demo:
JQuery Toggle to Show/Hide Content on jsbin.com

jQuery ajax getJson method is used to load json data from server using http get method. Lets go through syntax for getJson method.
jQuery.getJSON( url [, data ] [, success ] )
Url: It is url for get request on server
data: Data which you want to send to server with request.
Success : Callback function which get executed when request succeeds.
Data which you send with get request will be in the form of query string.

jQuery getJson example: 

Lets first create the json file named country.json which we are going to read from server. country.json
{
"countryName" : "India", 
"population" : 10000
}
Lets create html file named jQueryGetJson.html.
 
<!DOCTYPE>
 <html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<head>
  <title>getJson example</title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript" language="javascript">
   $(document).ready(function() {
      $("button").click(function(event){
          $.getJSON("country.json", function(country) {
             $("#getJsonDiv").html('<p> Name: ' + country.countryName + '</p>');
             $("#getJsonDiv").append('<p>Population : ' + country.population+ '</p>');
          });
      });
   });
</script>
</head>
<body>
  <div id="getJsonDiv">
 jQuery ajax getJSON example
  </div>
  <button>Get country data</button>
</body>
</html>

Lets deploy html file on server and send getJson request.
When you click on Get country data , you will get below output

Explanation:

  • $(document).ready(function() : This function will get called when fully DOM is loaded.
  • $("button").click(function(event) : This function will get called when "get country data" button is clicked.
  •  $.getJSON("country.json", function(country) : Here we are calling getJson method and URL is "country.json".  When request is successfully completed, callback function will be get called.

In this post,  we are going to see another important annotation called @RestController. It is generally used while working with Spring restful Web services implementation.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
If we need to directly get resource from controller, we need to return @ResponseBody as per Spring 3 but with Spring 4, we can use @RestController for that.
In spring 4.0, we can use @RestController which is combination of @Controller + @ResponseBody.
@RestController = @Controller + @ResponseBody
So
@Controller
public class CountryController {
 
 @RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json")
 public @ResponseBody List<Country> getCountries()
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();
  return listOfCountries;
 }
Is same as
@RestController
public class CountryController {
 
 @RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json")
 public List<Country> getCountries()
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();
  return listOfCountries;
 }
Instead of annotating each method return type as @ResponseBody, we can directly annotate a class with @RestController. You can see Spring rest Json example to get complete working example on @RestController.


In previous post, we have already seen Spring Rest crud example . In this post, we will extend same example and integrate it with hibernate and mysql.
We will use following annotations for CRUD operation.
Method
Description
Get
It is used to read resource
Post
It is used to create new resource.
It is not idempotent method
Put
It is generally used to update resource.It is idempotent method
Delete
It is used to delete resource

Idempotent means result of multiple successful request will not change state of resource after initial application
For example :
Delete is idempotent method because when you first time use delete, it will delete the resource (initial application) but after that, all other request will have no result because resource is already deleted.

Post is not idempotent method because when you use post to create resource , it will keep creating resource for each new request, so result of multiple successful request will not be same.

Source code:

click to begin

20KB .zip

Here are steps to create a Spring Restful web services  with hibernate integration.

1) Create a dynamic web project using maven in eclipse named "SpringRestHibernateExample"

Maven dependencies 

2) We need to add Jackson json utility in the classpath. 
 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
 </dependency>
Spring will load Jackson2JsonMessageConverter into its application context automatically. Whenever you request resource as json with accept headers="Accept=application/json", then Jackson2JsonMessageConverter comes into picture and convert resource to json format.
Now change pom.xml as follows:
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.arpit.java2blog</groupId>
  <artifactId>SpringRestfulWebServicesWithJSONExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestfulWebServicesWithJSONExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
        </dependency>
 </dependencies>
 <build>
  <finalName>SpringRestfulWebServicesWithJSONExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
</project>

Spring application configuration:

3) Change web.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>Archetype Created Web Application</display-name>
 <servlet>
 <servlet-name>spring</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

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

</web-app>
4) create a xml file named spring-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

 <annotation-driven />

 <resources mapping="/resources/**" location="/resources/" />

 <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <beans:property name="url"
   value="jdbc:mysql://localhost:3306/CountryData" />
  <beans:property name="username" value="root" />
  <beans:property name="password" value="" />
 </beans:bean>

 <!-- Hibernate 4 SessionFactory Bean definition -->
 <beans:bean id="hibernate4AnnotatedSessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <beans:property name="dataSource" ref="dataSource" />
  <beans:property name="annotatedClasses">
   <beans:list>
    <beans:value>org.arpit.java2blog.model.Country</beans:value>
   </beans:list>
  </beans:property>
  <beans:property name="hibernateProperties">
   <beans:props>
    <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
    </beans:prop>
    <beans:prop key="hibernate.show_sql">true</beans:prop>
   </beans:props>
  </beans:property>
 </beans:bean>
 
 <context:component-scan base-package="org.arpit.java2blog" />
 
 <tx:annotation-driven transaction-manager="transactionManager"/>
 
 <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
 </beans:bean>


</beans:beans>
In Spring-servlet.xml, we have done hibernate configuration.
dataSource bean is used to specify java data source. We need to provide driver, URL , Username and Password.
transactionManager bean is used to configure hibernate transaction manager. hibernate4AnnotatedSessionFactory bean is used to configure FactoryBean that creates a Hibernate SessionFactory. This is the common way to set up a shared Hibernate SessionFactory in a Spring application context, so you can use this SessionFactory to inject in Hibernate data access objects.

Create bean class 

4) Create a bean name "Country.java" in org.arpit.java2blog.bean.
package org.arpit.java2blog.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/*
 * This is our model class and it corresponds to Country table in database
 */
@Entity
@Table(name="COUNTRY")
public class Country{
 
 @Id
 @Column(name="id")
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 int id;
 
 @Column(name="countryName")
 String countryName; 
 
 @Column(name="population")
 long population;
 
 public Country() {
  super();
 }
 public Country(int i, String countryName,long population) {
  super();
  this.id = i;
  this.countryName = countryName;
  this.population=population;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 } 
 
}
@Entity is used for making a persistent pojo class.For this java class,you will have corresponding table in database. @Column is used to map annotated attribute to corresponding column in table. So Create Country table in mysql database with following code:
CREATE TABLE COUNTRY
(
   id int PRIMARY KEY NOT NULL,
   countryName varchar(100) NOT NULL,
   population int NOT NULL
)
;
CREATE UNIQUE INDEX PRIMARY ON COUNTRY(id)
;

Create Controller 

5) Create a controller named "CountryController.java" in package org.arpit.java2blog.controller
package org.arpit.java2blog.controller;

import java.util.List;
import org.arpit.java2blog.model.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CountryController {
 
 @Autowired
 CountryService countryService;
 
 @RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List<Country> getCountries() {
  
  List<Country> listOfCountries = countryService.getAllCountries();
  return listOfCountries;
 }

 @RequestMapping(value = "/getCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
 public Country getCountryById(@PathVariable int id) {
  return countryService.getCountry(id);
 }

 @RequestMapping(value = "/addCountry", method = RequestMethod.POST, headers = "Accept=application/json")
 public void addCountry(@RequestBody Country country) { 
  countryService.addCountry(country);
  
 }

 @RequestMapping(value = "/updateCountry", method = RequestMethod.PUT, headers = "Accept=application/json")
 public void updateCountry(@RequestBody Country country) {
  countryService.updateCountry(country);
 }

 @RequestMapping(value = "/deleteCountry/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
 public void deleteCountry(@PathVariable("id") int id) {
  countryService.deleteCountry(id);  
 } 
}

Create DAO class

Create a class CountryDAO.java in package org.arpit.java2blog.dao.  This class will execute hibernate statements while interacting with database.
package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.model.Country;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class CountryDAO {

 @Autowired
 private SessionFactory sessionFactory;

 public void setSessionFactory(SessionFactory sf) {
  this.sessionFactory = sf;
 }

 public List<Country> getAllCountries() {
  Session session = this.sessionFactory.getCurrentSession();
  List<Country> countryList = session.createQuery("from Country").list();
  return countryList;
 }

 public Country getCountry(int id) {
  Session session = this.sessionFactory.getCurrentSession();
  Country country = (Country) session.load(Country.class, new Integer(id));
  return country;
 }

 public Country addCountry(Country country) {
  Session session = this.sessionFactory.getCurrentSession();
  session.persist(country);
  return country;
 }

 public void updateCountry(Country country) {
  Session session = this.sessionFactory.getCurrentSession();
  session.update(country);
 }

 public void deleteCountry(int id) {
  Session session = this.sessionFactory.getCurrentSession();
  Country p = (Country) session.load(Country.class, new Integer(id));
  if (null != p) {
   session.delete(p);
  }
 } 
}

@Repository is specialised component annotation which is used to create bean at DAO layer. We have use Autowired annotation to inject hibernate SessionFactory into CountryDAO class. We have already configured hibernate SessionFactory object in Spring-Servlet.xml file.

Create Service class

6) Create a class CountryService.java in package org.arpit.java2blog.service
It is service level class. It will call DAO layer class.
package org.arpit.java2blog.service;

import java.util.List;
import org.arpit.java2blog.dao.CountryDAO;
import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("countryService")
public class CountryService {

 @Autowired
 CountryDAO countryDao;
 
 @Transactional
 public List<Country> getAllCountries() {
  return countryDao.getAllCountries();
 }

 @Transactional
 public Country getCountry(int id) {
  return countryDao.getCountry(id);
 }

 @Transactional
 public void addCountry(Country country) {
  countryDao.addCountry(country);
 }

 @Transactional
 public void updateCountry(Country country) {
  countryDao.updateCountry(country);

 }

 @Transactional
 public void deleteCountry(int id) {
  countryDao.deleteCountry(id);
 }
}

@Service is specialised component annotation which is used to create bean at Service layer.
7) It 's time to do maven build.
Right click on project -> Run as -> Maven build
Maven build in eclipse

8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

10) We will test this application in  postman , UI based client for testing restful web applications. It is chrome plugin. Launch postman.If you want java based client, then you can also use how to send get or post request in java.

Post method

12) Post method is used to create new resource. Here we are adding new Country India to country list, so you can see we have used new country json in post body.
URL: "http://localhost:8080/SpringRestHibernateExample/addCountry".



Lets see corresponding entry in Country table in database.
Lets create 3 more countries i.e. china, nepal and USA in similar way.

Put Method

13) Put method is used to update resource. Here will update population of nepal using put method.
We will update country json in body of request.
URL : "http://localhost:8080/SpringRestHibernateExample/updateCountry"

Lets check Nepal's population in database.

Delete method

14) Delete method is used to delete resource.We will pass id of country which needs to be deleted as PathParam. We are going delete id:3 i.e. Nepal to demonstrate delete method.

URL : "http://localhost:8080/SpringRestHibernateExample/deleteCountry/3"

Lets check entry in database now.

As you can see, we have deleted country with id 3 i.e. Nepal

Project structure:


We are done with Spring Restful web services json CRUD example. If you are still facing any issue, please comment.

If you getting 404 error with above steps, you may need to follow below steps:


1) If you are getting this warning into your Tomcat startup console log, then it can cause the issue

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server: JAXRSJsonCRUDExample' did not find a matching property.

This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.
To resolve this in eclipse,
Remove the project from the server from the Server View. Right click on server -> add and remove

then remove project from server configuration.
Then run the project under the same server. Warning should be removed now
Or if warning still remains then
  • Go to server view
  • Double click on your tomcat server. It will open the server configuration.
  • Under server options check ‘Publish module contents to separate XML files’ checkbox. 
  • Restart your server. This time your page will come without any issues.
2) Try to update Maven project.
Right click on project ->Maven-> update project
Update Maven project
then

This should solve you issues.

Enti

@ModelAttribute is one of most important Spring MVC annotation.
There are two ways to create model object.
  • Object is already present in session or ModelMap object.
  • Annotate another method with @ModelAttribute annotation and create the model object. This method will get called before actual handler call.

Example:

Source code:

click to begin

20KB .zip

Here are steps to create a Spring MVC ModelAttribute example.

1) Create a dynamic web project using maven in eclipse named "SpringMVCModelAttributeExample"

Maven dependencies 

2) We need to add Jackson json utility in the classpath. 
 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
 </dependency>

Spring will load Jackson2JsonMessageConverter into its application context automatically. Whenever you request resource as json with accept headers="Accept=application/json", then Jackson2JsonMessageConverter comes into picture and convert resource to json format.
Now change pom.xml as follows:
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.arpit.java2blog</groupId>
  <artifactId>SpringRestfulWebServicesWithJSONExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestfulWebServicesWithJSONExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
        </dependency>
 </dependencies>
 <build>
  <finalName>SpringRestfulWebServicesWithJSONExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
</project>

Spring application configuration:

3) Change web.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>  
 
  </welcome-file-list>
 <servlet>
 <servlet-name>springrest</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

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

</web-app>
4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.

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

 <mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 <mvc:default-servlet-handler/>
</beans>

Create bean class 

5) Create a bean name "Country.java" in org.arpit.java2blog.bean.
package org.arpit.java2blog.bean;

public class Country{
 
 String countryName; 
 long population;
 
 public Country() {
  super();
 }
 public Country(String countryName,long population) {
  super();
  this.countryName = countryName;
  this.population=population;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 } 
 
}

Create Controller 

6) Create a controller named "CountryController.java" in package org.arpit.java2blog.controller
package org.arpit.java2blog.controller;

import org.arpit.java2blog.bean.Country;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CountryController {

 @ModelAttribute
 public Country getCountry(@RequestParam String countryName, @RequestParam  long population)
 {
  Country country=new Country();
  country.setCountryName(countryName);
  country.setPopulation(population);
  return country;
 }
 @RequestMapping(value = "/addCountry", method = RequestMethod.POST)
 public String addCountry(@ModelAttribute Country country,ModelMap model) {
  model.addAttribute("countryName", country.getCountryName());
  model.addAttribute("population", country.getPopulation());
  return "countryDetails";
 }
} 

Create view
Modify index.jsp as below
<head>
<style>
           
.blue-button{
 background: #25A6E1;
 filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
 padding:3px 5px;
 color:#fff;
 font-family:'Helvetica Neue',sans-serif;
 font-size:12px;
 border-radius:2px;
 -moz-border-radius:2px;
 -webkit-border-radius:4px;
 border:1px solid #1A87B9
}     
table {
  font-family: "Helvetica Neue", Helvetica, sans-serif;
   width: 50%;
}
th {
  background: SteelBlue;
  color: white;
}
 td,th{
                border: 1px solid gray;
                width: 25%;
                text-align: left;
                padding: 5px 10px;
            }
</style>
</head>
<body>
<form action="addCountry" method="post">

<table>
  <tr>
   <th colspan="2">Add Country</th>
  </tr>
  <tr>
   <td>Country</td>
   <td><input type="text" name=countryName></td>
  </tr>
  <tr>
   <td>Population</td>
   <td><input type="text" name=population>
  </td></tr>
  <tr>
   <td colspan="2"><input type="submit"
    class="blue-button" /></td>
  </tr>
 </table>
 
</form>
</body>
Create countryDetails.jsp in /WEB-INF/ folder
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Country Details</title>
</head>
<body>
  Added country :
 <h3>Country Name: ${countryName}</h3>
 <h3>Population : ${population}</h3>
 </body> 
</html>
7) It 's time to do maven build.
Right click on project -> Run as -> Maven build
Maven build in eclipse

8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish
10) You will see screen as below:
Spring MVC model attribute example
11) When you click on submit button , you will see below screen.

We have already seen @Autowired annotation but we have used xml configuration to configure beans and inject it to container but if you use  @Component, @Service, @Repository and @Controller annotations and enable component auto scan, spring will automatically import these bean into container and you don't have to explicitly define them in xml file.
So basically all 4 annotations are used to register bean definition with spring's application context.

@Component:

@Component is generic annotation for bean definition and registers with application context.

@Service :

@Service is specialised component annotation which is used to annotate classes which belongs to service layer.

@Repository :

@Repository annotation is specialised component annotation which is used to annotate classes at DAO layer. It also makes unchecked exception eligible for conversion into Spring DataAccessException.

@Controller :

@ Controller annotation is specialised component annotation which is used to annotate classes at Presentation  layer. It is widely used in Spring MVC applications.
You should not use @Component annotation unless you are sure that it does not belong to @Service, @Repository and @Controller annotation.

Enable component Scanning : 

All these annotations will work only when you use context:component-scan in applicationcontext.xml. It basically scans for above 4 annotated classes and registers bean with Spring application context.
<context:component-scan base-package="org.arpit.java2blog" />

Spring annotations example : 

In this example,we are going to create country object with help of controller, service and Dao classes by using above annotations.
Lets first create our bean class
Country.java
package org.arpit.java2blog.bean;

public class Country{
 
 String countryName; 
 long population;
 
 public Country() {
  super();
 }
 public Country(String countryName,long population) {
  super();
  this.countryName = countryName;
  this.population=population;
 }

 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 } 
 
}
CountryController,java
package org.arpit.java2blog.controller;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller ("countryController")
public class CountryController 
{
     @Autowired
    CountryService countryService;
     
    public Country createNewCountry()
    {
        return countryService.createNewCountry();
    }
}

CountryService.java
package org.arpit.java2blog.service;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.dao.CountryDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("countryService")
public class CountryService {
    @Autowired
 CountryDAO countryDAO;
 public Country createNewCountry() {
 
  return countryDAO.createNewCountry();
 }

}

CountryDAO.java
package org.arpit.java2blog.dao;

import org.arpit.java2blog.bean.Country;
import org.springframework.stereotype.Repository;

@Repository("countryDAO")
public class CountryDAO {

 public Country createNewCountry() {
  // You should get it from database
  Country country = new Country("√Źndia", 40000);
  return country;
 }

}

applicationcontext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.arpit.java2blog" />
</beans>
SpringApplicationMain.java
package org.arpit.java2blog.main;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.controller.CountryController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplicationMain {
 public static void main(String[] args) {
  
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  CountryController controller = (CountryController) context.getBean("countryController");
  Country country = controller.createNewCountry();
  System.out.println("Country Name : " + country.getCountryName());
  System.out.println("Country's Population : " + country.getPopulation());
 }
}
When you run above program, you will get below output:
Aug 08, 2016 12:00:42 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1c2709da: startup date [Mon Aug 08 00:00:42 IST 2016]; root of context hierarchy
Aug 08, 2016 12:00:42 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Country Name : √Źndia
Country's Population : 40000

We have already seen Spring MVC hello world example. @RequestMapping is one of important annotation which you use in Spring MVC.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
@RequestMapping is used to define mapping of web request to handler method or class. @RequestMapping can be used at method level or class level. We will see example of it later.
If you use @RequestMapping annotation at class level, it will be used for relative path for method level path.
Lets understand with the help of example:
@RestController
@RequestMapping(value = "/countryController")
public class CountryController {

 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List<Country> getCountries() {
 
  List<country> listOfCountries = countryService.getAllCountries();
  return listOfCountries;
 }
so web request with URL http://localhost:8080/ProjectName/countryController/countries will execute getCountries() method. Below image will make it clear:
Spring MVC RequestMapping example

Method level RequestMapping example :

When you provide @RequestMapping annotation at method level, you may call it method level request mapping.
@RestController
public class CountryController {

 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List<Country> getCountries() {
 
  List<country> listOfCountries = countryService.getAllCountries();
  return listOfCountries;
 }
so web request with URL http://localhost:8080/ProjectName/countries will execute getCountries() method.

Class level RequestMapping example :

When you provide @RequestMapping annotation at class level, you may call it class level request mapping.
@RestController
@RequestMapping(value = "/countries")
public class CountryController {
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
 public Country addCountry(@RequestBody Country country) {
  return countryService.addCountry(country);
 }

 @RequestMapping(method = RequestMethod.PUT, headers = "Accept=application/json")
 public Country updateCountry(@RequestBody Country country) {
  return countryService.updateCountry(country);

 }
}
If you notice, we did not define method level request mapping here, so it will automatically call corresponding PUT or POST method when you hit :
http://localhost:8080/ProjectName/countries If you want to practice more examples for @RequestMapping annotation, you can go through Spring Rest CRUD example. It will definitely help you to understand @RequestMapping annotation better.
 

Java tutorial for beginners Copyright © 2012