• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Enable CORS in Spring Restful Web Services | @CrossOrigin + XML Configuration + Filter

November 6, 2017 by javainterviewpoint Leave a Comment

CORS Stands for Cross-Origin Resource Sharing, As a security measure browsers will block AJAX request to the resource residing on a different origin. CORS is a W3 Specification, which is implemented by most of the browsers and lets us request for the resource on the different domain in a safer way. (Only when the other domain sends back the response with some special Access-control headers). In order to demonstrate how CORS works, we will be developing 2 web applications (Spring RESTful Web Services and an Angular Client) both runs on localhost but on different ports (8080,7070). In this article, we will be Enable CORS in Spring Restful Web Services using @CrossOrigin annotation, XML Configuration and Servlet Filter.

Folder Structure:

Enable CORS in Spring Restful Web Services

  1. Create 2 Maven Webapp project (maven-archetype-webapp) “SpringRestCORS” and “SpringRestCORSClient”
  2. In “SpringRestCORS” create a package for our source files “com.javainterviewpoint” under  src/main/java add the following dependency in the 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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
     
        <groupId>com.javainterviewpoint</groupId>
        <artifactId>SpringRestCORS</artifactId>
        <version>1.0.0</version>
        <packaging>war</packaging>
     
        <name>SpringRestCORS</name>
     
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <springframework.version>4.3.1.RELEASE</springframework.version>
            <jackson.library>2.7.5</jackson.library>
        </properties>
     
        <dependencies>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${springframework.version}</version>
            </dependency>
     
            <!-- Jackson libraries -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.library}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-xml</artifactId>
                <version>${jackson.library}</version>
            </dependency>
     
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
            </dependency>
        </dependencies>
     
        <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.2</version>
                        <configuration>
                            <source>1.7</source>
                            <target>1.7</target>
                        </configuration>
                    </plugin>         
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>2.4</version>
                        <configuration>
                            <warSourceDirectory>src/main/webapp</warSourceDirectory>
                            <warName>SpringRestCORS</warName>
                            <failOnMissingWebXml>false</failOnMissingWebXml>
                        </configuration>
                    </plugin>
                </plugins>
            <finalName>SpringRestCORS</finalName>
        </build>
    </project>
  3. Create the Java classes Student.java and StudentController.java under com.javainterviewpoint folder and add SpringCorsConfig-servlet.xml and web.xml under /webapp/WEB-INF directory (SpringRestCORS project)
  4. Create index.html file under /webapp folder of SpringRestCORSClient project

Other Posts which you may like …

  • Integrate Spring Data ElasticSearch in Spring Boot
  • Spring Boot – How to Change Embedded Tomcat default port
  • JAX-RS REST @Produces both XML and JSON Example
  • JAX-RS REST @Consumes both XML and JSON Example
  • RESTful Java Client With Jersey Client
  • RESTEasy Hello World Example with Apache Tomcat
  • RESTful Java client with RESTEasy client
  • Spring RESTful Web Services Hello World XML Example
  • Springfox Swagger 2 for Spring RESTful Web Services
  • Spring MVC Difference between context:annotation-config vs context:component-scan
  • Spring MVC BeanNameUrlHandlerMapping Example
  • Spring MVC ControllerClassNameHandlerMapping Example
  • Spring MVC SimpleUrlHandlerMapping Example
  • Spring MVC Flow Diagram
  • Spring MVC Multiple submit buttons in a single form
  • Spring MVC SimpleFormController Example
  • Spring 4 – Spring MVC Hello World Example
  • Spring REST Hello World Example – JSON and XML responses
  • Spring Boot Hello World Example with Maven
  • Spring Boot Hello World Example in Eclipse
  • Spring Boot RESTful Web Services Example
  • Spring Boot Kotlin RESTful Web Services CRUD Example
  • How to Create Deployable WAR | Spring Boot | SpringBootServletInitializer

Enable CORS in Spring Restful Web Services

When CORS is not enabled we will be getting the error like “Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource”

Enable CORS in Spring Restful Web Services 1

Basically in a Cross-Origin Resource Sharing there will be two types of request which will be sent pre-flight request and actual request. Before sending the actual request, the browser will send a pre-flight request to the resource on the other origin to check whether the actual request is safe to send. If the actual request which is about to send is GET, HEAD and POST then there will be no pre-flight request sent. In all other case there will be a pre-flight request sent with HTTP OPTIONS method.

If suppose a client www.javainterviewpoint.com want a resource from www.oracle.com then the pre-flight request will be like below

Request Header

Request URL:http://www.oracle.com
Request Method:OPTIONS
Status Code:200 OK
Referrer Policy:no-referrer-when-downgrade

If the resource at the other end accepts the request, then it will send back the below response header.

Response Header

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: https://www.javainterviewpoint.com/
Vary: Origin
Access-Control-Allow-Methods: POST,GET,PUT,DELETE,HEAD
Access-Control-Expose-Headers: Origin, Access-Control-Request-Method, Access-Control-Allow-Origin, Access-Control-Allow-Credentials
Access-Control-Max-Age: 1600
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH

CORS HTTP Response Header

Below are the HTTP Header which will be sent as response.

  1. Access-Control-Allow-Origin: This header specifies which orgin server can access the resource, if the header is not specified all the origin will be allowed. If (*) is used then it allows all the origins.
  2. Access-Control-Allow-Methods: This header specifies the list of all the HTTP methods allowed (GET, POST, PUT…), If (*) is used then it allows all the HTTP methods.
  3. Access-Control-Allow-Headers: This header specifies the all the list of request headers that can be used during the actual request. If (*) is used then it allows all the request headers.
  4. Access-Control-Expose-Headers: This header specifies the list of response headers that the browser will allow the client to access.  (*) is Not allowed
  5. Access-Control-Max-Age: This header specifies the maximum age in seconds for how long the response to the preflight request can be cached for without sending another preflight request.

Enable CORS using Spring @CrossOrigin annotation

Spring 4.2 has introduced @CrossOrigin annotation to handle CORS, this annotation can be used in both class level and method level of the Restful Web Services. @CrossOrigin annotation has the below attributes in it.

  1. origins – This attribute sets value for Access-Control-Allow-Origin in both the pre-fligh and actual response, by default all origins are allowed.
  2. allowedHeaders – This attribute controls the value of the pre-flight response’s Access-Control-Allow-Headers header
  3. exposedHeaders – This attribute sets the value for Access-Control-Expose-Headers.
  4. maxAge – This attribute sets value for Access-Control-Max-Age response header, the default value is 1800 seconds.
  5. methods – The Methods specified here override the methods specified in @RequestMapping.If this is not defined, methods defined by @RequestMapping annotation are used.

CORS Controller – @CrossOrigin annotation

package com.javainterviewpoint;

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

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@RestController
@CrossOrigin(origins="http://localhost:7070",
   maxAge=2000,allowedHeaders="header1,header2",
   exposedHeaders="header1",allowCredentials= "false")
public class StudentController
{
    @DeleteMapping(value="/students/{id}",produces=MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin(origins="http://localhost:8888",exposedHeaders="testheader")
    public List deleteStudent(@PathVariable Integer id)
    {
        //Create Student Objects
        Student s1 = new Student(1,"JIP1",11);
        Student s2 = new Student(2,"JIP2",22);
        Student s3 = new Student(3,"JIP3",33);
        
        //Add student object to studentList
        List studentList = new ArrayList();
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        
        //Remove the student with the mentioned id
        Iterator it = studentList.iterator();
        while(it.hasNext())
        {
            Student st = (Student)it.next();
            if(id==st.getId())
            {
                it.remove();
            }
        }
        
        return studentList;
    }
}

We have used the @CrossOrigin annotation in both class and method level, So the deleteStudent() method will have combined effect of both class and the method level @CrossOrigin annotation. It will allow origin “http://localhost:7070” and “http://localhost:8888” and exposeHeader will be “header1” and “testheader”

Student.java

package com.javainterviewpoint;

public class Student
{
    private int id;
    private String name;
    private int age;
    
    public Student()
    {
        super();
    }
    public Student(int id, String name, int age)
    {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    @Override
    public String toString()
    {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

Our Student class is a simple POJO class consisting getters and setters of Student properties id, name, age.

web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"	
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Enable CORS in Spring Restful Web Services</display-name>

	<servlet>
		<servlet-name>SpringCorsConfig</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringCorsConfig</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

SpringCorsConfig-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"	
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc	http://www.springframework.org/schema/mvc/spring-mvc.xsd  
  http://www.springframework.org/schema/beans	http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/util	http://www.springframework.org/schema/util/spring-util.xsd  
  http://www.springframework.org/schema/context	http://www.springframework.org/schema/context/spring-context.xsd">
	<mvc:annotation-driven />
	<context:component-scan base-package="com.javainterviewpoint" />

</beans>

index.html (SpringRestCORSClient project)
In our index.html we have created a angular client which calls our Student Restful Service using $http.

<!DOCTYPE html>
<html>
<head>
<script
	src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
	var app = angular.module('myapp', []);
	app.controller('mycontroller', function($scope, $http) {
		//$scope.id ='';
		$scope.removeStudent = function() {
			$http({
					url : 'http://localhost:8080/SpringRestCORS/students/'
							+ $scope.id,
					method : 'DELETE',
				 })
				 .then(function success(response) 
				 {
					$scope.data = response.data;
				 }, function error(response) 
				 {
					$scope.error = response;
			});
		}
	});
</script>
</head>
<body>
	<h2>CORS CLIENT</h2>
	<div ng-app="myapp" ng-controller="mycontroller">
		<form>
			Enter the id to remove: <input type="text" ng-model="id"><br>
			<button ng-click="removeStudent()">Remove</button>
		</form>
		<br></br>
		<table border="1">
			<tr ng-repeat="student in data">
				<td>{{student.id}}</td>
				<td>{{student.name}}</td>
			</tr>
		</table>
	</div>
</body>
</html>

Output

We will be running two Tomcat server instances one on 8080 port (StudentRestCORS) and other on 7070 port (StudentRestCORSClient).

Hit the url : http://localhost:7070/SpringRestCORSClient/index.html

Enable CORS in Spring Restful Web Services 2

Enter a id and hit on remove. In order to view the pre-flight request, open Developer tools (f12)  in chrome goto Network tab. You will find two request one of them is pre-flight request and the other is the actual request. Click on each request to view its headers headers.

pre-flight request

Enable CORS in Spring Restful Web Services 3

actual request

Enable CORS in Spring Restful Web Services 4

Enabling Global CORS using XML Configuration

We can enable Global CORS using the Spring MVC cors element. We need to add the cors element in our SpringCorsConfig-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"	
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc	http://www.springframework.org/schema/mvc/spring-mvc.xsd  
  http://www.springframework.org/schema/beans	http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/util	http://www.springframework.org/schema/util/spring-util.xsd  
  http://www.springframework.org/schema/context	http://www.springframework.org/schema/context/spring-context.xsd">
	<mvc:annotation-driven />
	<context:component-scan base-package="com.javainterviewpoint" />
	
	<mvc:cors>
		<mvc:mapping path="/students/**" 
			allowed-origins="http://localhost:7070"
			allowed-methods="POST, GET, PUT, DELETE,HEAD"
			allow-credentials="false"
			allowed-headers="Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization"
			exposed-headers="Origin,Access-Control-Request-Method,Access-Control-Allow-Origin,Access-Control-Allow-Credentials"
			/>
	</mvc:cors> 

</beans>

Enable CORS Using Filter

Alternatively we can enable CORS by simply using a servlet filter by adding the CORS header to the response in the doFilter() method. Create a Java class CORSFilter implementing the Filter interface.

package com.javainterviewpoint;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CORSFilter implements Filter
{
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:7070");
        response.setHeader("Access-Control-Allow-Credentials", "false");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers",
                "Origin, Content-Type, X-Requested-With, accept, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
        response.setHeader("Access-Control-Expose-Headers",
                "Origin, Access-Control-Request-Method, Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
        response.setHeader("Access-Control-Max-Age", "4000");
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

    @Override
    public void destroy()
    {
    }
}

Add the filter in our web.xml using the <filter> tag.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"	
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Enable CORS in Spring Restful Web Services</display-name>

	<servlet>
		<servlet-name>SpringCorsConfig</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringCorsConfig</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<filter>
		<filter-name>CORS</filter-name>
		<filter-class>com.javainterviewpoint.CORSFilter</filter-class>
	</filter>
	<filter-mapping>
	        <filter-name>CORS</filter-name>
	        <url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

Happy Learning!! 🙂

   Download Source Code

Filed Under: J2EE, Java, Spring, Spring Tutorial Tagged With: CORS, Emable CORS, RESTful Web Services, Spring RESTful Web Services

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·