Spring MVC Content Negotiation Tutorial with Example


When making a request via HTTP it is possible to specify what type of response you would like by setting the Accept header property. Web browsers have this preset to request HTML. In fact, if you look, you will see that browsers actually send very confusing Accept headers, which makes relying on them impractical.

So, for those situations where the Accept header property is not desirable, Spring offers some conventions to use instead. You can configure a content negotiation strategy centrally once and it will apply wherever different formats (media types) need to be determined.

Enabling Content Negotiation in Spring MVC

Spring supports a couple of conventions for selecting the format required: URL suffixes and/or a URL parameter. These work alongside the use of Accept headers. As a result, the content-type can be requested in any of three ways. By default they are checked in this order:

Add a path extension (suffix) in the URL

If the incoming URL is something like http://localhost:8080/SpringContentNegotiation/api/users.html then HTML is required. For a spreadsheet the URL should be http://localhost:8080/SpringContentNegotiation/api/users.xls.

The suffix to media-type mapping is automatically defined via the JavaBeans Activation Framework or JAF (so activation.jar must be on the class path).

A URL parameter

If the incoming URL supplies request parameter something like http://myserver/myapp/accounts/list?format=xls. The name of the parameter is format by default, but this may be changed. Using a parameter is disabled by default, but when enabled, it is checked second.

Accept HTTP header property is checked

This is how HTTP is actually defined to work, but, as previously mentioned, it can be problematic to use.

When using XML configuration, the content negotiation strategy is most easily setup via the ContentNegotiationManagerFactoryBean:

<!--
 Setup a simple strategy: 
 1. Take all the defaults.
 2. Return XML by default when not sure. 
 -->
 <bean id="contentNegotiationManager"
 class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
 <property name="defaultContentType" value="application/xml"
/>
 </bean>

 <!-- Make this available across all of Spring MVC -->
 <mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager" />

The ContentNegotiationManager created by either setup is an implementation of ContentNegotationStrategy that implements the PPA Strategy (path extension, then parameter, then Accept header).

Additional Configuration Options

the strategy can be configured using methods on the factory bean:

<!-- Total customization - see below for explanation. -->
 <bean id="contentNegotiationManager"
 class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
 <property name="favorPathExtension" value="false" />
 <property name="favorParameter" value="true" />
 <property name="parameterName" value="format" />
 <property name="ignoreAcceptHeader" value="true"/>
 <property name="useJaf" value="false"/>
 <property name="defaultContentType" value="application/json"
/>
 
 <property name="mediaTypes">
 <map>
 <entry key="json" value="application/json" />
 <entry key="xml" value="application/xml" />
 </map>
 </property>
</bean>

what it is mean:
  • Disabled path extension. Note that favor does not mean use one approach in preference to another, it just enables or disables it. The order of checking is always path extension, parameter, Accept header.
  • Enable the use of the URL parameter but instead of using the default parameter, format, we can use any Parameter Name instead.
  • Ignore the Accept header completely. This is often the best approach if most of your clients are actually web-browsers (typically making REST calls via AJAX).
  • Don't use the JAF, instead specify the media type mappings manually - we only wish to support JSON and XML.

Listing Employees Example



Below is the example To return a list of employees in JSON or XML. We will ignore the HTML generating methods for now.

STEP 1:- Open Eclipse and Create Dynamic Web Project named SpringContentNegotiationExample

STEP 2:- Make sure you use Target Runtime as Apache Tomcat 7.0. 

STEP 3:- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • jackson-annotations-2.6.0.jar
  • jackson-core-2.6.0.jar
  • jackson-databind-2.6.0.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="com.tutorialsdesk" />
 
 <bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
 <property name="favorPathExtension" value="true" />
 <property name="favorParameter" value="true" />
 <property name="parameterName" value="mediaType" />
 <property name="ignoreAcceptHeader" value="true"/>
 <property name="useJaf" value="false"/>
 <property name="defaultContentType" value="application/json"
/>
 <property name="mediaTypes">
 <map>
 <entry key="json" value="application/json" />
 <entry key="xml" value="application/xml" />
 </map>
 </property>
 </bean>
 
 <mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager" />
 
</beans>

In the above file we have configured property favorPathExtension to true, so system will process URL like Employees.json.

STEP 5 :- Map Spring MVC in /WebContent/WEB-INF/web.xml file 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>SpringContentNegotiationExample</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>

STEP 6 :- Create Controller Class.
  • Package: com.tutorialsdesk.controller
  • Filename: EmployeeController.java
package com.tutorialsdesk.controller;

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

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.tutorialsdesk.model.Employee;

@RestController
public class EmployeeController {
 @RequestMapping(value = "/Employees", method = RequestMethod.GET)
 @ResponseStatus(HttpStatus.OK)
 public List<Employee> getCountries(){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees=createEmployeeList(); 
 return listOfEmployees; 
 } 

 public List<Employee> createEmployeeList(){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees.add(new Employee(29,
"Bill","Smith","bill@tutorialsdesk.com")); 
 listOfEmployees.add(new Employee(30,
"Tom","Moore","tom@gmail.com")); 
 listOfEmployees.add(new Employee(35,
"Sachin","Sharma","sachin@yahoo.com")); 
 listOfEmployees.add(new Employee(25,
"Martin","Jung","mj@hotmail.com")); 
 return listOfEmployees; 
 } 
}


STEP 7 :- Create model class.
  • Package: com.tutorialsdesk.model
  • Filename: Employee.java
package com.tutorialsdesk.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;

@XmlRootElement (name = "employee")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee implements Serializable{

 private static final long serialVersionUID = 5088863992478607917L;

 @XmlAttribute
 private Integer id;
 
 @XmlElement
 private String firstName;
 
 @XmlElement
 private String lastName;
 
 @XmlElement
 private String email;

 public Employee(Integer id, String firstName, String lastName, String email) {
 super();
 this.id = id;
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }

 public Employee() {
 super();
 }

 public Integer getId() {
 return id;
 }

 public void setId(Integer id) {
 this.id = id;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastName() {
 return lastName;
 }

 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public static long getSerialversionuid() {
 return serialVersionUID;
 }

 @Override
 public String toString() {
 return "Employee [id=" + id + ", firstName=" + firstName
 + ", lastName=" + lastName + ", email=" + email + "]";
 }
 
}


Provided We have JAXB2 and Jackson on my classpath, Spring MVC will automatically setup the necessary HttpMessageConverters. Our domain classes must also be marked up with JAXB2 and Jackson annotations to enable conversion.

STEP 8 :- Run your project enter below URL in your browser

localhost:8080/SpringContentNegotiationExample/Employees.json
or
localhost:8080/SpringContentNegotiationExample/Employees.xml
or
localhost:8080/SpringContentNegotiationExample/Employees.xml
http://localhost:8080/SpringContentNegotiationExample/Employees?format=json
or
http://localhost:8080/SpringContentNegotiationExample/Employees?format=xml

Combining Data and Presentation Formats

Spring MVC’s REST support builds on the existing MVC Controller framework. So it is possible to have the same web-applications return information both as raw data (like JSON) and using a presentation format (like HTML).

Both techniques can easily be used side by side in the same controller, like this:
@RestController
public class EmployeeController {
 @RequestMapping(value = "/Employees", method = RequestMethod.GET,
produces={"application/xml", "application/json"})
 @ResponseStatus(HttpStatus.OK)
 public List<Employee> getEmployeesJSONXML(){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees=createEmployeeList(); 
 return listOfEmployees; 
 } 
 @RequestMapping(value = "/Employees", method = RequestMethod.GET)
 
 public String getEmployeesView(Model model){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees=createEmployeeList(); 
 model.addAttribute("empList",listOfEmployees );
 return "listEmployee"; 
 } 
 public List<Employee> createEmployeeList(){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees.add(new Employee(29,
"Bill","Smith","bill@tutorialsdesk.com")); 
 listOfEmployees.add(new Employee(30,
"Tom","Moore","tom@gmail.com")); 
 listOfEmployees.add(new Employee(35,
"Sachin","Sharma","sachin@yahoo.com")); 
 listOfEmployees.add(new Employee(25,
"Martin","Jung","mj@hotmail.com")); 
 return listOfEmployees; 
 } 
}



Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC Content Negotiation Example, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left). Please share us on social media if you like the tutorial.

Spring REST Client with RestTemplate Consume RESTful Web Service Example for XML and JSON


In this tutorial we will learn how to use spring RestTemplate to consume RESTful Web Service. RestTemplate communicates HTTP server using RESTful principals. RestTemplate provides different methods to communicate via HTTP methods. The HTTP methods of RestTemplate accepts three variants as an argument. Two of them accepts URL template as string and URI variables as map. Third variant is that it accepts URI object. Find the description of RestTemplate methods which we are using in our example.

getForObject() : Use HTTP GET method to retrieve data.
exchange() : Executes the URI for the given HTTP method and returns the response.
headForHeaders() : Retrieves all headers.
getForEntity() : Use HTTP GET method with the given URL variables and returns ResponseEntity. delete() : Deletes the resources at the given URL.
put(): Creates the new resource for the given URL.
postForEntity(): Creates a news resource using HTTP POST method.
optionsForAllow() : Returns the allow header for the given URL.

We will use these methods in our example with different scenarios. We will show the demo to consume JSON and XML both.

Required Jars :- Add below jars to project class Path.
  • commons-logging-1.2.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar

Get XML / JSON representation in String format

RestTemplate getForObject()

final String uri = "http://localhost:8080/SpringRESTExample/rest/Employees";
 RestTemplate restTemplate = new RestTemplate();
 String result = restTemplate.getForObject(uri, String.class); 
 System.out.println(result);

Using custom HTTP Headers with RestTemplate

RestTemplate exchange()

final String uri = "http://localhost:8080/SpringRESTExample/rest/Employees";
 RestTemplate restTemplate = new RestTemplate();
 HttpHeaders headers = new HttpHeaders();
 headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
 HttpEntity<String> entity = new
HttpEntity<String>("parameters", headers);
 ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET,
entity, String.class);
 System.out.println(result);

Get data as mapped object

final String uri = "http://localhost:8080/SpringRESTXMLExample/employees";
 RestTemplate restTemplate = new RestTemplate();
 EmployeeList result = restTemplate.getForObject(uri, EmployeeList.class);
 System.out.println(result.getEmployees().get(0).getFirstName());

Java Bean used in Example

package com.tutorialsdesk.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;

@XmlRootElement (name = "employee")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee implements Serializable{

 private static final long serialVersionUID = 5088863992478607917L;

 @XmlAttribute
 private Integer id;
 
 @XmlElement
 private String firstName;
 
 @XmlElement
 private String lastName;
 
 @XmlElement
 private String email;

 public Employee(Integer id, String firstName, String lastName, String email) {
 super();
 this.id = id;
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }

 public Employee() {
 super();
 // TODO Auto-generated constructor stub
 }

 public Integer getId() {
 return id;
 }

 public void setId(Integer id) {
 this.id = id;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastName() {
 return lastName;
 }

 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public static long getSerialversionuid() {
 return serialVersionUID;
 }

 @Override
 public String toString() {
 return "Employee [id=" + id + ", firstName=" + firstName
 + ", lastName=" + lastName + ", email=" + email + "]";
 }
 
 
}


package com.tutorialsdesk.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement (name="employees")
public class EmployeeList implements Serializable{

 private static final long serialVersionUID = -7565600226888520442L;
 private List<Employee> employees = new ArrayList<Employee>();
 public List<Employee> getEmployees() {
 return employees;
 }
 
 public void setEmployees(List<Employee> employees) {
 this.employees = employees;
 }
}

Passing parameters in URL

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 Map<String, String> params = new HashMap<String, String>();
 params.put("id", "1");
 RestTemplate restTemplate = new RestTemplate();
 Employee result = restTemplate.getForObject(uri, Employee.class, params);
 System.out.println(result.getFirstName());

HTTP POST Method Example

RestTemplate postForObject()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/create";
 Employee newEmployee = new Employee(1, "Adam", "Gilly",
"test@email.com");
 RestTemplate restTemplate = new RestTemplate();
 Employee result = restTemplate.postForObject( uri, newEmployee, Employee.class);
 System.out.println(result);

HTTP PUT Method Example

RestTemplate put()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 Map<String, String> params = new HashMap<String, String>();
 params.put("id", "2");
 Employee updatedEmployee = new Employee(2, "New Name", "Gilly",
"test@email.com");
 RestTemplate restTemplate = new RestTemplate();
 restTemplate.put ( uri, updatedEmployee, params);

HTTP DELETE Method Example

RestTemplate delete()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 Map<String, String> params = new HashMap<String, String>();
 params.put("id", "2");
 RestTemplate restTemplate = new RestTemplate();
 restTemplate.delete ( uri, params );

RestTemplate headForHeaders()

RestTemplate restTemplate = new RestTemplate();
 String url = "http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 HttpHeaders httpHeaders = restTemplate.headForHeaders(url);
 System.out.println(httpHeaders.getContentLength());

RestTemplate optionsForAllow()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 RestTemplate restTemplate = new RestTemplate();
 Set<HttpMethod> entity= restTemplate.optionsForAllow(url);

RestTemplate getForEntity()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 RestTemplate restTemplate = new RestTemplate();
 Map<String, String> map = new HashMap<String, String>();
 map.put("district", "Varanasi");
 map.put("state", "100");
 ResponseEntity<Employee> personEntity = restTemplate.getForEntity(uri,
Employee.class, map);
 System.out.println("Name:"+personEntity.getBody().getName());
 System.out.println("Village:"+personEntity.getBody().getAddress().getVillage());

RestTemplate postForEntity()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 RestTemplate restTemplate = new RestTemplate();
 Map<String, String> map = new HashMap<String, String>();
 Employee newEmployee = new Employee(1, "Adam", "Gilly",
"test@email.com");
 map.put("district", "Varanasi");
 map.put("state", "100");
 ResponseEntity<Employee> personEntity = restTemplate.postForEntity(uri,null,
Employee.class, map);
 //ResponseEntity<Employee> personEntity =
restTemplate.postForEntity(uri,newEmployee, Employee.class, map);
 System.out.println("Name:"+personEntity.getBody().getName());


Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring REST Client with RestTemplate Consume RESTful Web Service Example for XML and JSON, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.

Spring REST Hello World XML tutorial with Example

In this tutorial, we will learn to write APIs capable of returning XML representations of resources.

Step 1 :- Open Eclipse and Create Dynamic Web Project named SpringRESTXMLExample

Step 2:- Make sure you use Target Runtime as Apache Tomcat 7.0 and Dynamic web module version as 3.0.

Step 3 :- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • jackson-annotations-2.6.0.jar
  • jackson-core-2.6.0.jar
  • jackson-databind-2.6.0.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="com.tutorialsdesk" />
 <mvc:annotation-driven/>
 <bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
 <property name="messageConverters">
 <list>
 <ref bean="xmlMessageConverter"/>
 </list>
 </property>
 </bean>
 
 <bean id="xmlMessageConverter"
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
</beans>


Here we are relying on the Spring MVC HttpMessageConverter to convert an object to the xml representation requested by the user. @ResponseBody annotation (included through @RestController) tells Spring MVC that the result of the method should be used as the body of the response. As we want XML this marshaling is done by the Jaxb2RootElementHttpMessageConverter provided by Spring which is automatically registered in spring context if JAXB libraries are found in classpath. As we are using JRE 7 to run this application and it has JAXB inbuilt,

STEP 5:- Map Spring MVC in /WebContent/WEB-INF/web.xml file 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>SpringRESTXMLExample</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>


STEP 6:- Create Controller Class
  • package com.tutorialsdesk.controller
  • Filename: EmployeeController.java
package com.tutorialsdesk.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;

import com.tutorialsdesk.model.Employee;
import com.tutorialsdesk.model.EmployeeList;

@RestController
public class EmployeeController {

 private static EmployeeList employees = new EmployeeList();
 
 static{
 employees.getEmployees().add(new
Employee(1,"Martin","Gates","martin@tutorialsdesk.com"));
 employees.getEmployees().add(new
Employee(2,"Jhon","Smith","jhon@tutorialsdesk.com"));
 employees.getEmployees().add(new
Employee(3,"Manav","Kushal","manav@tutorialsdesk.com"));
 employees.getEmployees().add(new
Employee(4,"Prince","Sethi","prince@tutorialsdesk.com"));
 }
 
 @RequestMapping(value = "/employees")
 public ResponseEntity<EmployeeList> getAllEmployees()
 {
 if(employees.getEmployees().size() > 0){
 return new ResponseEntity<EmployeeList>(employees, HttpStatus.OK);
 }
 return new ResponseEntity<EmployeeList>(HttpStatus.NOT_FOUND);
 }
 
 @RequestMapping(value = "/employees/create", method = RequestMethod.POST)
 public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee)
 {
 return new ResponseEntity<Employee>(employee,HttpStatus.OK);
 }
 
 @RequestMapping(value = "/employees/{id}")
 public ResponseEntity<Employee> getEmployeeById
(@PathVariable("id") int id)
 {
 for(Employee employee : employees.getEmployees()){
 if(id == employee.getId()){
 return new ResponseEntity<Employee>(employee, HttpStatus.OK);
 }
 }
 
 return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
 }
 
 @RequestMapping(value = "/employees/{id}", method = RequestMethod.PUT)
 public ResponseEntity<Employee> updateEmployee(@PathVariable("id")
int id, @RequestBody Employee employee)
 {
 return new ResponseEntity<Employee>(employee, HttpStatus.OK);
 }
 
 @RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)
 public ResponseEntity<String> deleteEmployee(@PathVariable("id")
int id)
 {
 return new ResponseEntity<String>(HttpStatus.OK);
 }
}

Instead of returning the java objects directly, you can wrap them inside ResponseEntity. The ResponseEntity is a class in Spring MVC that acts as a wrapper for an object to be used as the body of the result together with a HTTP status code. This provides greater control over what you are returning to client in various use cases. e.g. returning a 404 error if no employee is found for given employee id.

STEP 7:- Create Model Class
  • package com.tutorialsdesk.model
  • Filename: Employee.java
You will need to annotate your model objects with jaxb annotations so that JAXB can marshal the java object into XML representation to be sent to client for that API.
package com.tutorialsdesk.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;

@XmlRootElement (name = "employee")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee implements Serializable{

 private static final long serialVersionUID = 5088863992478607917L;

 @XmlAttribute
 private Integer id;
 
 @XmlElement
 private String firstName;
 
 @XmlElement
 private String lastName;
 
 @XmlElement
 private String email;

 public Employee(Integer id, String firstName, String lastName, String email) {
 super();
 this.id = id;
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }

 public Employee() {
 super();
 }

 public Integer getId() {
 return id;
 }

 public void setId(Integer id) {
 this.id = id;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastName() {
 return lastName;
 }

 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public static long getSerialversionuid() {
 return serialVersionUID;
 }

 @Override
 public String toString() {
 return "Employee [id=" + id + ", firstName=" + firstName
 + ", lastName=" + lastName + ", email=" + email + "]";
 }
 
}

STEP 8:- Create Model Class
  • package com.tutorialsdesk.model
  • Filename: EmployeeList.java
package com.tutorialsdesk.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement (name="employees")
public class EmployeeList implements Serializable{

 private static final long serialVersionUID = -7565600226888520442L;
 private List<Employee> employees = new ArrayList<Employee>();
 public List<Employee> getEmployees() {
 return employees;
 }
 
 public void setEmployees(List<Employee> employees) {
 this.employees = employees;
 }
}


STEP 9 :- Run your project enter below URL in your browser

Now when you hit the URL : http://localhost:8080/SpringRESTXMLExample/employees you will get this result.
<?xml version="1.0" encoding="UTF-8"
standalone="yes" ?> 
- <employees>
- <employees id="1">
 <firstName>Martin</firstName> 
 <lastName>Gates</lastName> 
 <email>martin@tutorialsdesk.com</email> 
 </employees>
- <employees id="2">
 <firstName>Jhon</firstName> 
 <lastName>Smith</lastName> 
 <email>jhon@tutorialsdesk.com</email> 
 </employees>
- <employees id="3">
 <firstName>Manav</firstName> 
 <lastName>Kushal</lastName> 
 <email>manav@tutorialsdesk.com</email> 
 </employees>
- <employees id="4">
 <firstName>Prince</firstName> 
 <lastName>Sethi</lastName> 
 <email>prince@tutorialsdesk.com</email> 
 </employees>
 </employees>


If you hit the URL : http://localhost:8080/SpringRESTXMLExample/employees/4 you will get this result.
<employee id="4">
<firstName>Prince</firstName>
<lastName>Sethi</lastName>
<email>prince@tutorialsdesk.com</email>
</employee>


Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring REST Hello World XML Example, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.

Spring REST Hello World JSON Tutorial with Example

In this tutorial, we will learn to write APIs capable of returning JSON representations of resources.

Step 1 :- Open Eclipse and Create Dynamic Web Project named SpringRESTExample

Step 2:- Make sure you use Target Runtime as Apache Tomcat 7.0 and Dynamic web module version as 3.0.

Step 3 :- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • jackson-annotations-2.6.0.jar
  • jackson-core-2.6.0.jar
  • jackson-databind-2.6.0.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="com.tutorialsdesk.controller" />
 <mvc:annotation-driven/>
 <bean name="viewResolver"
class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
 <bean name="jsonTemplate"
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</beans>

You will need to configure viewName “jsonTemplate” as bean of type MappingJackson2JsonView. And you will need to configure view resolver of type BeanNameViewResolver. This way viewName “jsonTemplate” will be matched with MappingJackson2JsonView and parsed JSON response will be returned to client.

STEP 5:- Map Spring MVC in /WebContent/WEB-INF/web.xml file 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>SpringRESTExample</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>


Using @ResponseBody Annotation

This technique is simple and easy. You have to include only jackson dependencies into classpath of your application and spring will register Jackson2JsonMessageConverter class automatically into context. Whenever you ask for a resource from REST API and provide http header “accept: application/json“, you will get back the json representation of resource.

Here @RestController = @Controller + @ResponseBody

If you are using @RestController you don't need to specify @ResponseBody

STEP 6:- Create Controller Class
  • package com.tutorialsdesk.controller
  • Filename: EmployeeController.java
package com.tutorialsdesk.controller;

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

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;

import com.tutorialsdesk.model.Employee;

@RestController
@RequestMapping("rest")
public class EmployeeController {
 @RequestMapping(value = "/Employees", method =
RequestMethod.GET,headers="Accept=application/json") 
 public List<Employee> getCountries(){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees=createEmployeeList(); 
 return listOfEmployees; 
 } 
 
 @RequestMapping(value = "/Employee/{id}", method =
RequestMethod.GET,headers="Accept=application/json") 
 public Employee getEmployeeById(@PathVariable int id){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees=createEmployeeList(); 
 for (Employee Employee: listOfEmployees) { 
 if(Employee.getEmpId()==id) 
 return Employee; 
 } 
 
 return null; 
 } 

 public List<Employee> createEmployeeList(){ 
 List<Employee> listOfEmployees = new ArrayList<Employee>(); 
 listOfEmployees.add(new Employee(29, "Prakash")); 
 listOfEmployees.add(new Employee(30, "Rambir")); 
 listOfEmployees.add(new Employee(35, "Sachin")); 
 listOfEmployees.add(new Employee(25, "Martin")); 
 return listOfEmployees; 
 } 
}

STEP 7:- Create Model Class
  • package com.tutorialsdesk.model
  • Filename: Employee.java
package com.tutorialsdesk.model;

public class Employee {

 private String name;
 private int empId;

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public int getEmpId() {
 return empId;
 }

 public void setEmpId(int empId) {
 this.empId = empId;
 }

 public Employee(int empId, String name){
 this.name = name;
 this.empId = empId;
 }
 
}


STEP 8 :- Run your project enter below URL in your browser

Now when you hit the URL : http://localhost:8080/SpringRESTExample/rest/Employees you will get this result.
[{"name":"Prakash","empId":29},{"name":"Rambir","empId":30},{"name":"Sachin","empId":35},{"name":"Martin","empId":25}]


If you hit the URL : http://localhost:8080/SpringRESTExample/rest/Employee/25 you will get this result.
{"name":"Martin","empId":25}



Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring REST Hello World JSON Example, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.

Spring MVC Form Validation using Annotation Tutorial with Example

When we accept user inputs in any web application, it become necessary to validate them. We can validate the user input at client side using JavaScript but it’s also necessary to validate them at server side to make sure we are processing valid data incase user has javascript disabled.

Spring MVC Framework supports JSR-303 specs by default and all we need is to add JSR-303 and it’s implementation dependencies in Spring MVC application. Spring also provides @Validator annotation and BindingResult class through which we can get the errors raised by Validator implementation in the controller request handler method.

Let’s create a simple Spring MVC project in Spring Tool Suite where we will use JSR-303 specs with it’s implementation artifact hibernate-validator. We will use annotation based form validation.

Step 1 :- Open Eclipse and Create Dynamic Web Project named SpringMVCFormSubmit

Step 2:- Make sure you use Target Runtime as Apache Tomcat 7.0 and Dynamic web module version as 3.0.

Step 3 :- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • hibernate-validator-4.3.1.Final.jar
  • jboss-logging-3.1.0.GA.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
  • validation-api-1.0.0.GA.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="com.tutorialsdesk.controller" />
 
 <mvc:annotation-driven />
 
 <bean id="viewResolver"
 class="org.springframework.web.servlet.view.UrlBasedViewResolver">
 <property name="viewClass"
 value="org.springframework.web.servlet.view.JstlView" />
 <property name="prefix" value="/WEB-INF/views/" />
 <property name="suffix" value=".jsp" />
 </bean>
 
 <bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
 <property name="basename" value="/WEB-INF/messages" />
 </bean>
 
 <!-- <context:property-placeholder
location="/WEB-INF/conf/messages.properties"/> -->
 
</beans>


STEP 5 :- Map Spring MVC in /WebContent/WEB-INF/web.xml file 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>SpringMVCExample</display-name>
 <welcome-file-list>
 <welcome-file>login.html</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>*.html</url-pattern>
 </servlet-mapping>
</web-app>


STEP 6 :- Create Controller Class.
  • Package: com.tutorialsdesk.controller
  • Filename: FormController.java
package com.tutorialsdesk.controller;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tutorialsdesk.model.User;

@Controller
public class FormController {
 
 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public String viewLogin(Map<String, Object> model) {
 User user = new User();
 model.put("userForm", user);
 return "LoginForm";
 }
 
 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public String doLogin(@Valid @ModelAttribute("userForm") User userForm,
 BindingResult result, Map<String, Object> model) {
 
 if (result.hasErrors()) {
 return "LoginForm";
 }
 
 return "LoginSuccess";
 }
}

Spring MVC will validate the model object annotated by the @Valid annotation after binding its properties with inputs from JSP form that uses Spring’s form tags. Any constraint violations will be exposed as errors in the BindingResult object, thus we can check the violation in the controller’s method.

First we need to annotate model object that we want to validate with @Valid annotation. Then we need to have BindingResult argument in the method, spring takes care of populating it with error messages. The handler method logic is very simple, if there are any errors we are responding with the same page or else we are redirecting user to the success page.

Another important point to note is that we are adding “userForm” attribute to the model, this is necessary to let Spring framework know which model object to use in the form page. If we won’t do it, object binding to form data will not take place and our form validation will not work.

STEP 7 :- Create Model Class.
  • Package: com.tutorialsdesk.model
  • Filename: User.java
package com.tutorialsdesk.model;

import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

public class User {

 @NotEmpty
 @Email
 private String email;
 
 @NotEmpty(message = "Please enter your password.")
 @Size(min = 6, max = 15, message = "Your password must between 6 and 15
characters")
 private String password;
 
 public String getEmail() {
 return email;
 }
 
 public void setEmail(String email) {
 this.email = email;
 }
 
 public String getPassword() {
 return password;
 }
 
 public void setPassword(String password) {
 this.password = password;
 }

}


STEP 8 :- Create LoginForm.jsp under WEB-INF/views folder.

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form"%>
 
<!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>Login</title>
<style>
 .error {
 color: red; font-weight: bold;
 }
</style>
</head>
<body>
 <div align="center">
 <h2>Spring MVC Form Validation Demo - Login Form</h2>
 <table border="0" width="90%">
 <form:form action="login.html" commandName="userForm">
 <tr>
 <td align="left" width="20%">Email: </td>
 <td align="left" width="40%"><form:input
path="email" size="30"/></td>
 <td align="left"><form:errors path="email"
cssClass="error"/></td>
 </tr>
 <tr>
 <td>Password: </td>
 <td><form:password path="password"
size="30"/></td>
 <td><form:errors path="password"
cssClass="error"/></td>
 </tr>
 <tr>
 <td></td>
 <td align="center"><input type="submit"
value="Login"/></td>
 <td></td>
 </tr>
 </form:form>
 </table>
 </div>
</body>
</html>

commandName="userForm" is used to set the name of the model attribute under which form object is exposed. It’s default value is “command” by default, hence we should set it to the model attribute name we are using in our controller classes.

form:errors is used to render the errors, if any, found when the page is rendered. path attribute is used to define the object property to be used for data binding. Rest of the code is standard HTML with some CSS for error messages styling.

STEP 9 :- Create LoginSuccess.jsp under WEB-INF/views 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>Welcome</title>
</head>
<body>
 <div align="center">
 <h2>Welcome ${userForm.email}! You have logged in successfully.</h2>
 </div>
</body>
</html>

STEP 10 :- Create messages.propreties under WEB-INF folder.

If you want to localize the message, specify a key in the properties file in the following convention:
ConstraintName.CommandName.propertyName=validation error message

We localize validation error messages for the email field, so put the following key=value pairs in messages.properties file:

NotEmpty.userForm.email=Please enter your e-mail. 
Email.userForm.email=Your e-mail is incorrect.

STEP 11 :- Run your project enter below URL in your browser

http://localhost:8080/SpringMVCFormSubmit/
OR
http://localhost:8080/SpringMVCFormSubmit/login.html

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC Form Submit and validation Example, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.

Printing Even and Odd using two Threads in Java

Write a java program to print even and odd values in sequence.
Expected result:
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9

Solution:
package com.tutorialsdesk.Thread;

public class PrintEvenOdd {

        public static void main(String ... args){
        Printer print = new Printer();
        Thread t1 = new Thread(new TaskEvenOdd(print, 10,  false));
        Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
        t1.start();
        t2.start();
    }
        
}

class TaskEvenOdd implements Runnable {
    private int max;
    private Printer print;
    private boolean isEvenNumber;

    TaskEvenOdd(Printer print, int max, boolean isEvenNumber){
        this.print = print;
        this.max = max;
        this.isEvenNumber = isEvenNumber;
    }

    @Override
    public void run() {
        int number = isEvenNumber == true ? 2 : 1;
        while(number<= max){
            if(isEvenNumber){
                print.printEven(number);
            }   
            else {
                print.printOdd(number);
            }
            number+=2;
        }
        }
}

class Printer {
    boolean isOdd= false;
    synchronized void printEven(int number) {
        while(isOdd == false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:"+number);
        isOdd = false;
        notifyAll();
    }
    synchronized void printOdd(int number) {
        while(isOdd == true){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:"+number);
        isOdd = true;
        notifyAll();
    }
}


Output :
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9
Even:10

3 threads to print alternate values in sequence in java

Write a java program to print 3 threads alternate values in sequence. 

Expected result: 
Thread[Thread1,5,main] 1
Thread[Thread2,5,main] 2
Thread[Thread3,5,main] 3
Thread[Thread1,5,main] 4
Thread[Thread2,5,main] 5
Thread[Thread3,5,main] 6
Thread[Thread1,5,main] 7
Thread[Thread2,5,main] 8
Thread[Thread3,5,main] 9

Solution :-
package com.tutorialsdesk.Thread;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreeThreadsOrderedLockLess {

        AtomicInteger sharedOutput = new AtomicInteger(0);
        private Object object = new Object();
        public static void main(String args[]) throws InterruptedException{
                ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();
                MyThread t1 = t.new MyThread(0);
                MyThread t2 = t.new MyThread(1);
                MyThread t3 = t.new MyThread(2);

        Thread ts1 = new Thread(t1);
        Thread ts2 = new Thread(t2);
        Thread ts3 = new Thread(t3);
        ts1.setName("Thread1");
        ts2.setName("Thread2");
        ts3.setName("Thread3");
        ts1.start();
        ts2.start();
        ts3.start();
                
        }


        private class MyThread implements Runnable{
                private final int threadPosition;
                public MyThread(int threadPosition) {
                        super();
                        this.threadPosition = threadPosition;
                }
        
                @Override
                public void run() {
                        while (sharedOutput.get() < 9) {

                synchronized (object) {

                    if (sharedOutput.get() % 3 == this.threadPosition) {

                        if(sharedOutput.get() < 9)
                        System.out.println(Thread.currentThread()+"  "+
sharedOutput.incrementAndGet());
                    }
                }
            }
                }
        }        
}

Output:
Thread[Thread1,5,main] 1
Thread[Thread2,5,main] 2
Thread[Thread3,5,main] 3
Thread[Thread1,5,main] 4
Thread[Thread2,5,main] 5
Thread[Thread3,5,main] 6
Thread[Thread1,5,main] 7
Thread[Thread2,5,main] 8
Thread[Thread3,5,main] 9

Print all combinations of balanced parentheses

Write java program to generate all possible n pairs of balanced parentheses. 

For example, if n=1
{}
for n=2
{}{}
{{}}

Solution :-:

package com.tutorialsdesk.algos;
public class ParanthesisCombination {
public static void main(String[] args) { 
printParenthesis(3); 
} 
static void printParenthesis(int n){ 
printParenthesis("",n,n); 
}

static void printParenthesis(String s,int open,int close){ 
if(open > close) 
return; 
if(open == 0 && close == 0){ 
System.out.println(s); 
return; 
} 
if(open < 0 || close<0) 
return;

printParenthesis(s + '{',open-1,close); 
printParenthesis(s + '}',open,close-1); 
}
}


Output :-

{{{}}}
{{}{}}
{{}}{}
{}{{}}
{}{}{}

Spring MVC Hello World Tutorial with Example


STEP 1:- Open Eclipse and Create Dynamic Web Project named SpringMVCExample

STEP 2:- Make sure you use Target Runtime as Apache Tomcat 7.0. 

STEP 3:- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="com.tutorialsdesk.controller" />
 
 <bean id="viewResolver"
 class="org.springframework.web.servlet.view.UrlBasedViewResolver">
 <property name="viewClass"
 value="org.springframework.web.servlet.view.JstlView" />
 <property name="prefix" value="/WEB-INF/views/" />
 <property name="suffix" value=".jsp" />
 </bean>
 
</beans>

In the above dispatcher-servlet.xml configuration file, we have defined a tag . This will allow Spring to load all the components from package com.tutorialsdesk.controller and all its child packages. This will load our SpringMVCHelloWorld.class . 

Also we have defined a bean viewResolver. This bean will resolve the view and add prefix string /WEB-INF/views/ and suffix .jsp to the view in ModelAndView. Note that in our SpringMVCHelloWorld.class, we have return a ModelAndView object with view name welcome. This will be resolved to path /WEB-INF/views/welcome.jsp . 

STEP 5 :- Map Spring MVC in /WebContent/WEB-INF/web.xml file 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>SpringMVCExample</display-name>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>*.html</url-pattern>
 </servlet-mapping>
</web-app>

One thing to note here is the name of servlet in tag in web.xml. Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. In this example, the framework will look for file called dispatcher-servlet.xml. 

STEP 6 :- Create Controller Class.
  • Package: com.tutorialsdesk.controller
  • Filename: SpringMVCHelloWorld.java
package com.tutorialsdesk.controller;

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

@Controller
public class SpringMVCHelloWorld {

 @RequestMapping("/index")
 public ModelAndView helloWorld(){
 String message = "<br><div style='text-align:center;'>"
 + "<h3>********** Hello World, Spring MVC Example by
TutorialsDesk**********</h3>This message is coming from
SpringMVCHelloWorld.java</div><br><br>";
 return new ModelAndView("welcome", "message", message);
 }
 
}

Note that we have annotated the SpringMVCHelloWorld class with @Controller and @RequestMapping("/index"). When Spring scans our package, it will recognize this bean as being a Controller bean for processing requests. The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /index in the URL path. That includes /index/* and /index.html. 

As we have declared index.html in web.xml as welcome-file, it will routed to our SpringMVCHelloWorld controller. 

The helloWorld() method returns ModelAndView object. The ModelAndView object tries to resolve to a view named “welcome” and the data model is being passed back to the browser so we can access the data within the JSP. The logical view name will resolve to /WEB-INF/views/welcome.jsp . Logical name “welcome” which is return in ModelAndView object is mapped to path /WEB-INF/views/welcome.jsp. The ModelAndView object also contains a message with key “message” and Detailed value. This is the data that we are passing to our view. Normally this will be a value object in form of java bean that will contain the data to be displayed on our view. Here we are simply passing a string. 

STEP 7 :- Create /WebContent/WEB-INF/views/welcome.jsp file.
<html>
<head>
<title>Spring MVC Example by TutorialsDesk - Hello World Spring MVC
 Example</title>

</head>
<body>${message}
 
 <br>
 <br>
 <div style="font-family: verdana; padding: 10px; border-radius: 10px;
font-size: 12px; text-align:center;">
 
 Spring MCV Tutorial by <a
href="http://www.tutorialsdesk.com/">TutorialsDesk</a>.
 Click <a
 href="http://www.tutorialsdesk.com/search/label/Java"
 target="_blank">here</a> for all Java and <a
 href="http://www.tutorialsdesk.com/search/label/Spring-MVC"
target='_blank'>here</a>
 for all Spring MVC, Web Development examples.<br>
 </div>
</body>
</html>

STEP 8 :- Run your project enter below URL in your browser 
http://localhost:8080/SpringMVCExample 
or 
http://localhost:8080/SpringMVCExample/index.html 

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC Hello World Example, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left). 

Please share us on social media if you like the tutorial.