This post is in continuation with web service tutorial (Part -10).
    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example
In previous post, we have created a very simple Spring Restful web services  which returns plain text. In this post, we will see Spring Restful web services which will return json as example. If you want complete integration with hibernate and mysql, you can go through Spring Restful hibernate mysql example.

Here are steps to create a simple Spring Restful web services which will return json.

1) Create a dynamic web project using maven in eclipse.
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:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <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" />

</beans>

Create bean class 

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

public class Country{
 
 int id;
 String countryName; 
 
 public Country(int i, String countryName) {
  super();
  this.id = i;
  this.countryName = countryName;
 }
 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;
 } 
 
}

Create controller 

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

import java.util.ArrayList;
import java.util.List;

import org.arpit.java2blog.bean.Country;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@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;
 }

 @RequestMapping(value = "/country/{id}", method = RequestMethod.GET,headers="Accept=application/json")
 public Country getCountryById(@PathVariable int id)
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();

  for (Country country: listOfCountries) {
   if(country.getId()==id)
    return country;
  }
  
  return null;
 }

// Utiliy method to create country list.
 public List<Country> createCountryList()
 {
  Country indiaCountry=new Country(1, "India");
  Country chinaCountry=new Country(4, "China");
  Country nepalCountry=new Country(3, "Nepal");
  Country bhutanCountry=new Country(2, "Bhutan");

  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries.add(indiaCountry);
  listOfCountries.add(chinaCountry);
  listOfCountries.add(nepalCountry);
  listOfCountries.add(bhutanCountry);
  return listOfCountries;
 }
}

@PathVariable: Used to inject values from the URL into a method parameter.This way you inject id in getCountryById method .
We are not providing any view information in springrest-servlet.xml as we do in Spring MVC. 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
6) It 's time to do maven build.
Right click on project -> Run as -> Maven build
7) Provide goals as clean install (given below) and click on run


Run the application


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

When you run the application, you might get this kind of warning
Mar 26, 2016 1:45:51 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringRestfulWebServicesWithJSONExample/] in DispatcherServlet with name 'SpringRestfulWebServicesWithJSONExample'

Please ignore above warning. When you start application, you have below URL if you have not provided start page:
http://localhost:8080/SpringRestfulWebServicesWithJSONExample/ 

As we have used DispatcherServlet in web.xml, this request goes to spring DispatcherServlet and it did not find corresponding mapping in controller , hence you get that warning.

9) Test your REST service under: "http://localhost:8080/SpringRestfulWebServicesWithJSONExample/countries".
You will get following output:


10) Now pass country id as parameter to url.
"http://localhost:8080/SpringRestfulWebServicesWithJSONExample/country/2".

click to begin
20KB .zip
We are done with Spring Restful web services 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:SpringRestfulWebServicesExample' 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
then

This should solve you issues.

This post is in continuation with web service tutorial (Part -10).
    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example
We have already seen Restful web services tutorial and Spring mvc web example. In this post, we will see combination of both.
Spring have started supporting Restful web services after Spring 3 version. In this post, we will see how to create Restful web services with Spring framework.If you want complete integration with hibernate and mysql, you can go through Spring Restful hibernate mysql example.

Here are steps to create a simple Spring Restful web services which will return plain text.

1) Create a dynamic web project using maven in eclipse.
2) 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>SpringRestfulWebServicesExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestfulWebServicesExample 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>
 </dependencies>
 <build>
  <finalName>SpringRestfulHelloWorldExample</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:
<
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <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" />

</beans>

Create controller 

5) Create a controller named "SpringRestController.java"
package org.arpit.java2blog.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/hello")
public class SpringRestController {
 @RequestMapping(value = "/{name}", method = RequestMethod.GET)
 public String hello(@PathVariable String name) {
  String result="Hello "+name;  
  return result;
 }
}
@PathVariable: Used to inject values from the URL into a method parameter.This way you inject name in hello method .
We are not providing any view information in springrest-servlet.xml as we do in Spring MVC. 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
6) It 's time to do maven build.
Right click on project -> Run as -> Maven build
7) Provide goals as clean install (given below) and click on run


Run the application


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

9) Test your REST service under: "http://localhost:8080/SpringRestfulWebServicesExample/hello/arpit".
You will get following output:

Download
click to begin
20KB .zip
We are done with Spring Restful web services 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:SpringRestfulWebServicesExample' 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
then

This should solve you issues.


In this post , we will see how to use ModelMap in Spring MVC.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL 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
ModelMap object is used to pass multiple values from Spring MVC controller to JSP .

Some basics about Spring MVC ModelMap class:

  • ModelMap class subclasses LinkedHashMap. It add some methods for convenience.
  • It provides addAttribute method to put key value pair. This method return ModelMap objects that can be used for chaining. 
  • ModelMap uses <String,Object> as generics.
  • ModelMap checks for null values.

Example:

Prerequisite:

You need to create spring mvc hello world example first.

Once you are done with spring mvc sample project. We need to add or modify following files.
  • Make changes to HelloWorldController.java
  • Modify index.jsp
  • Modify hello.jsp
Thats all we need to do to demonstrate Spring MultiActionController example.

1) change HelloWorldController.java as below

package org.arpit.java2blog.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class HelloWorldController {
 
 @RequestMapping("/helloworld")
 public String hello(ModelMap map) {
 
  String helloWorldMessage = "Hello world from java2blog!";
  String welcomeMessage = "Welcome to  java2blog!";
  map.addAttribute("helloMessage", helloWorldMessage);
  map.addAttribute("welcomeMessage", welcomeMessage);
  
  return "hello";
 }
}
We have added two attributes to ModelMap and they will be used in jsp with helloMessage and welcomeMessage

2) Modify index.jsp
<%@ 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>HelloWorld</title>
</head>
<body>
<a href="helloworld.html">Click here to read hello and welcome message </a>
</body>
</html>

3)Modify hello.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>Hello</title>
</head>
<body>
${helloMessage}
<br/>
${welcomeMessage}
</body>
</html>

4) It 's time to do maven build.
Right click on project -> Run as -> Maven build
5) Provide goals as clean install (given below) and click on run


Run the application


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

7) You will see below screen:


 When you click on  link, you will get below screen







We are done with Spring MVC ModelMap example. If you are still facing any issue, please comment.

In this post, we will see difference between Iterator and ListIterator in java. They are both used for traversal but it is good to point out differences between them.

Iterator vs ListIterator:


Parameter
Iterator
ListIterator
Traversal
Iterator can be used to traverse List,set, Queue
ListIterator can be used to traverse only List.
Traversal direction
Iterator can be traversed only in forward direction
ListIterator can be traverse in forward direction as well backward.
Adding elements while traversing
You can not add elements while traversing using Iterator. It will through ConcurrentModificationException
You can add elements while traversing using ListIterator.
Replacing existing elements 
You can not replace exisitng elements while traversing using Iterator.
You can replace exisitng elements while traversing using ListIterator using set(E e).
Accessing Index
You can not access index using Iterator

You can access index using ListIterator via nextIndex() or previousIndex methods

Example: 

1. Country.java 
package org.arpit.java2blog;
public class Country {

 String name;
 long population;
 
 public Country(String name, long population) {
  super();
  this.name = name;
  this.population = population;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 } 
  
}
2. IterateListMain.java 
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

public class IterateListMain {
 /**
     * @author Arpit Mandliya
     */
    public static void main(String[] args) {
          
        Country india=new Country("India",1000);
        Country japan=new Country("Japan",10000);
          
        Country france=new Country("France",2000);
        Country russia=new Country("Russia",20000);
        
        // We are going to iterate on this list and will print 
        //name of the country 
        ArrayList<Country> countryLists=new ArrayList<Country>();
        countryLists.add(india);
        countryLists.add(japan);
        countryLists.add(france);
        countryLists.add(russia);
        
    
        System.out.println("-----------------------------");
      
        // Iterator
        System.out.println("Iterating using iterator : ");
        Iterator<Country> iteratorCountryLists= countryLists.iterator();
        while(iteratorCountryLists.hasNext())
        {
         System.out.println(iteratorCountryLists.next().getName());
        }
        
        System.out.println("-----------------------------");
        //List iterator
        
        System.out.println("Iterating using ListIterator in forward direction : ");
        ListIterator<Country> listIteratorCountry= countryLists.listIterator();
        while(listIteratorCountry.hasNext())
        {
         System.out.println(listIteratorCountry.next().getName());
        }
        
        System.out.println("-----------------------------");
        System.out.println("Iterating using ListIterator in backward direction : ");
 
        while(listIteratorCountry.hasPrevious())
        {
         System.out.println(listIteratorCountry.previous().getName());
        }
        
    }
}

When you run above program, you will get following output:
-----------------------------
Iterating using iterator : 
India
Japan
France
Russia
-----------------------------
Iterating using ListIterator in forward direction : 
India
Japan
France
Russia
-----------------------------
Iterating using ListIterator in backward direction : 
Russia
France
Japan
India


In this post, we will see TreeSet in java.
Java TreeSet have following properties:
  • It can contain only unique element.
  • It stores objects in ascending order by default,
  • It implements NavigableSet interface which extends SortedSet.
  • When you put objects in TreeSet, it must implement Comparable interface.

Lets understand it more with the help of example.

Example:

1) create a class named Country.java.
package com.org.arpit.java2blog;
public class Country implements Comparable{

    String countryName;

    public Country(String countryName) {
        super();   
        this.countryName = countryName;
    }

    @Override
    public int compareTo(Object arg0) {
        Country country=(Country) arg0;
        
        return (this.countryName.compareTo(country.countryName) ) ;
    }
    
    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

}

2) create TreeSetMain.java as below:
package com.org.arpit.java2blog;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
  Country indiaCountry=new Country("India");
  Country chinaCountry=new Country("China");
  Country nepalCountry=new Country("Nepal");
  Country bhutanCountry=new Country("Bhutan");
  Country indiaCountry2=new Country("India");
  Country nepalCountry2=new Country("Nepal");

  TreeSet<country> countryTreeSet = new TreeSet<country>();
  countryTreeSet.add(indiaCountry);
  countryTreeSet.add(chinaCountry);
  countryTreeSet.add(nepalCountry);
  countryTreeSet.add(bhutanCountry);
  countryTreeSet.add(indiaCountry2);
  countryTreeSet.add(nepalCountry2);

  Iterator<country> counIter=countryTreeSet.iterator(); // put debug point here
  while(counIter.hasNext())
  {
   System.out.println(counIter.next().countryName);
  }
 }

}
When you run above program, you get below out:
Bhutan
China
India
Nepal
As you can see, we have added 6 country objects in Treeset but we have only 4!!. As TreeSet can only have unique elements,indiaCountry2 and nepalCountry2 did not add to the TreeSet. Explanation: 
When you will put indiaCountry2 in treeSet it will compare this object with indiaCountry as indiaCountry2.compareTo(indiaCountry) and compareTo method will return 0. Both object will treated as equal. As you can not add duplicate element in TreeSet, indiaCountry2 will not be added to above TreeSet.

Now put debug point at line 27 and right click on project-&gt;debug as-&gt; java application. Program will stop execution at line 27 then right click on countryTreeSet then select watch.You will be able to see structure as below.
TreeSet in java

Tricky question on TreeSet: 

Guess output of below program:
package com.org.arpit.java2blog;
import java.util.Iterator;
import java.util.TreeSet;
public class Employee implements Comparable { 
 public String name;
 public int compareTo(Object o) {
  return 0;
 }
 public static void main(String args [])
 {
  Employee employeeOne = new Employee();
  Employee employeeTwo = new Employee();
  employeeOne.name= "John";
  employeeTwo.name= "Martin";
  TreeSet<Employee> employeeSet = new TreeSet<Employee>();
  employeeSet.add(employeeOne);
  employeeSet.add(employeeTwo);
  Iterator<Employee> empIt=employeeSet.iterator();
  while(empIt.hasNext())
  {
   System.out.println(empIt.next().name);
  } 
 }
}

What will be output of above program:
A. Martin
B. John
C. John
    Martin
D. Compilation fails.
E. The code runs with no output.
F. An exception is thrown at runtime.

Correct Answer is B here.

Explanation:

As you can see we have overridden compareTo method in Employee class and always return 0.
Following steps will take place:
  • First element with "John" will be added to employeeSet.
  • When we will added second element with martin, compareTo method will get called with employeeOne.compareTo(employeeTwo) and it will return 0.
  • As compareTo method returns 0, employeeOne is equals to employeeTwo, so employeeTwo will not be added to treeSet.
  • So output of above program is "John"

Please go through java interview programs for more such programs.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL 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
Spring MultiActionController is used to map similar actions to single controller. So If you use MultiActionController class, you do not need to create new controller class for each action.

For example: When we login to internet banking, there is an option to add and delete payee. So we can use single PayeeController to perform similar actions such as add and delete.

As per spring docs, Method handler have to follow structure:
public (ModelAndView | Map | String | void) actionName(HttpServletRequest request, HttpServletResponse response, [,HttpSession] [,AnyObject]);

Example:

Prerequisite:

You need to create spring mvc hello world example first.

Once you are done with spring mvc sample project. We need to add or modify following files.
  • Add a controller class named "PayeeController,java "
  • Modify index.jsp
  • Add new file named "payee.jsp" in /WEB-INF/ folder.
Thats all we need to do to demonstrate Spring MultiActionController example.

1) create Controller named "PayeeController.java" in org.arpit.java2blog.java2blog.springmvc.controller

package org.arpit.java2blog.springmvc.controller;

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

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

@Controller
public class PayeeController {
 @RequestMapping("/payee/add.htm")
 public ModelAndView add(HttpServletRequest request,
  HttpServletResponse response) throws Exception {
  return new ModelAndView("payee", "message", "Payee Added"); 
 }
 @RequestMapping("/payee/delete.htm")
 public ModelAndView delete(HttpServletRequest request,
  HttpServletResponse response) throws Exception {
  return new ModelAndView("payee", "message", "Payee Deleted"); 
 }
}

As you can see here, you do not need to extend MultiAction class explicitly if you are using @controller annotation.

2) Modify index.jsp
<%@ 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>Spring MVC multiActionControllerExample</title>
</head>
<body>
<a href="payee/add.htm" >Add Payee</a> | 
<a href="payee/delete.htm" >Delete Payee</a> 
</body>
</html>

3)Create payee.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>Payee</title>
</head>
<body>
${message}
</body>
</html>


Project structure after following above steps:

4) It 's time to do maven build.
Right click on project -> Run as -> Maven build
5) Provide goals as clean install (given below) and click on run


Run the application


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

7) You will see below screen:

 When you click on Add Payee link, you will get below screen






We are done with Spring MVC MutliActionController example. If you are still facing any issue, please comment.

In this post, we will see Spring MVC hello world example using maven.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL 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
Tools used for this post are:
  • Eclipse
  • Maven plugin(m2eclipse)
  • JDK 1.7
  • Apache tomcat 8

Steps for creating Spring MVC hello world example.


1) Install m2eclipse for maven plugin in eclipse. Please follow this link for installing m2eclipse plugin in eclipse.

2) goto new -> project-> Maven Project and click on next

3) You will see below screen , again click on next


4) We need to select type of archetype here.As we are creating web app here, please put following text in filter : maven-archetype-webapp



5) We need to put group id and artifact id here.

Let me tell you more about group id and artifact id.

Group id : It uniquely identifies your project among all. So it may be something like com.companyname

Artifact id : It is name of jar or war without version. it may be something like project, so here we have put artifact id as mavenWebApp

Version : Version is used for version control for artifact id. If you distribute this project, you may incrementally create different version of it.


When you follow above steps, your project structure will look like below:
As you can see, we are getting an error ("The superclass "javax.servlet.http.HttpServlet" was found in java build path") in index.jsp. 
To solve this issue, follow below steps:
you need to set target run time as Apache tomcat. To do that,right click on project -> properties -> target runtimes



Adding Spring MVC dependency

6) Add spring dependency in pom.xml. We require spring core and spring mvc dependency here.

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>SpringMVCHelloWorldExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCHelloWorldExample 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>
  </dependencies>
  <build>
    <finalName>SpringMVCHelloWorldExample</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>

Create Controller  and view

7) Create a package named "org.arpit.java2blog.springmvc.controller"
create a controller class named "HelloWorldController.java"
package org.arpit.java2blog.springmvc.controller;

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

@Controller
public class HelloWorldController {
 
 @RequestMapping("/helloworld")
 public ModelAndView hello() {
 
  String helloWorldMessage = "Hello world from java2blog!";
  return new ModelAndView("hello", "message", helloWorldMessage);
 }
}

As  request first goes to dispatcherServlet and it redirects to controller class. Here @Controller depicts that this is our controller class. @RequestMapper is used to map incoming http request to handler method(hello() in above controller).So hello() method of HelloWorldController.java will handle GET request from dispatcher.So when we have url of
http://localhost:8080/SpringMVCHelloWorldExample/helloworld or
http://localhost:8080/SpringMVCHelloWorldExample/helloworld.html
above method will get called.

As you can see ModelAndView object is being returned in hello() method. It will call below constructor of ModelAndView class.
ModelAndView(String viewName, String modelName, Object modelObject)
Below diagram will make it clear

8) Modify index.jsp as below
<%@ 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>HelloWorld</title>
</head>
<body>
<a href="helloworld.html">Click here to read hello message </a>
</body>
</html>
Create hello.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>Hello</title>
</head>
<body>
${message}
</body>
</html>

Configuring spring mvc application 

 9) Now we need to configure two files "web.xml" and "springmvc-dispatcher-servlet.xml" We need to declare DispatcherServlet in web.xml for spring MVC. When DisplatcherServlet is initialized,spring tries to load application context from [servlet name]-servet.xml file. So in this case, it will be try to load springmvc-dispatcher-servlet.xml.
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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>springmvc-dispatcher</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping> 
    </web-app>

10) create xml file named "springmvc-dispatcher-servlet.xml" in /WEB-INF folder as below.
<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.springmvc.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:annotation-driven/>

</beans>
context:component-scan allows spring to load its class and child class. As you can see, we have given controller package here, so it will load HelloWorldController.class.
InternalResourceViewResolver is resource view resolver bean which will resolve view, prefix and suffix will be added to view used in ModelViewObject. As we have used "hello" as viewName in ModelAndView object. It will search for view in /WEB-INF/hello.jsp.


11) It 's time to do maven build.
Right click on project -> Run as -> Maven build
12) Provide goals as clean install (given below) and click on run


Run the application


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

14) You will see below screen:

When you click on above link, you will get below screen

We are done with Spring MVC hello example. If you are still facing any issue, please comment.
Download
click to begin
20KB .zip

Project structure:


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:SpringMVCHelloWorldExample' 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
then

This should solve you issues.

In this post, we will see how to create dynamic web project using maven in eclipse. If you can also create simple java maven project in eclipse.

I am using following tools for this post.
  • eclipse-jee-mars-R-macosx-cocoa-x86_64
  • Apache tomcat 8
  • m2eclipse plugin
  • jdk 1.7

Steps for creating dynamic web project using maven in eclipse.


1) Install m2eclipse for maven plugin in eclipse. Please follow this link for installing m2eclipse plugin in eclipse.

2) goto new -> project-> Maven Project and click on next

3) You will see below screen , again click on next


4) We need to select type of archetype here.As we are creating web app here, please put following text in filter : maven-archetype-webapp


5) We need to put group id and artifact id here.

Let me tell you more about group id and artifact id.

Group id : It uniquely identifies your project among all. So it may be something like com.companyname

Artifact id : It is name of jar or war without version. it may be something like project, so here we have put artifact id as mavenWebApp

Version : Version is used for version control for artifact id. If you distribute this project, you may incrementally create different version of it.

6) You project structure should look something like below image.

7) When I have followed above steps, I was getting below error.
"The superclass "javax.servlet.http.HttpServlet" was found in java build path".



You can resolve this error using two ways.

1) you can add following dependency to pom.xml

 javax.servlet
 javax.servlet-api
 3.1.0

2) you can set target run time as Apache tomcat .
right click on project -> properties -> target runtimes

8) It 's time to do maven build.
Right click on project -> Run as -> Maven build

9)  Provide goals as clean install (given below) and click on run




10) When you run maven build, you will see below screen
11) Deploy this application to tomcat server and run it.
If you don't have tomcat server configured in eclipse, follow these steps.
Right click on project -> run as -> run on server -> choose tomcat.

12)
When you run application, you will get following output:

Bingo !! we are done with creating dynamic web project using maven in eclipse.

Please comment if you are facing any issue with this.


 

Java tutorial for beginners Copyright © 2012