Categories
java spring-boot

enable cors in spring boot rest API

In this post we will learn to enable cors in spring boot rest API

For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin.

While we facing cors issue, we need to enable cors in spring boot application explicitly

Enable for whole spring boot

We need to add below class in our spring boot application, this will enable cors for all endpoints

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/**");
			}
		};
	}

}
Enable for specific endpoint

Below snippet will enable cors only for endpoint which starts with /api


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/api/**");
			}
		};
	}

}
Enable for specific orgins

Below snippet will enable for orgin https://beginnersbug.com

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/api/**")
				.allowedOrigins("https://beginnersbug.com");
			}
		};
	}

}
Enable CORS with Annotation

we can enable cors by annotation. we need to mention @crossOrgin annotation in the controller class as like below


import java.util.List;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.beginnersbug.studentservice.dao.StudentDao;
import com.beginnersbug.studentservice.model.Student;

@RestController()
@CrossOrigin()
@RequestMapping("/api/student")
public class StudentController {

	@Autowired
	StudentDao studentsDao;

	@RequestMapping(method = RequestMethod.GET)
	public List<Student> getStudentsList() {
		return studentsDao.findAll();
	}
}
Github

https://github.com/rkumar9090/student-service/blob/master/src/main/java/com/beginnersbug/studentservice/CorsConfig.java

Related Articles

read value from application.properties spring boot

Categories
microservices spring-boot

how to create rest service using spring boot

In this post, we will learn how to create rest service using spring boot

What is Rest Service

REST is Web services which is lightweight, maintainable, and scalable in nature.
The underlying protocol for REST is HTTP, which is the basic web protocol. REST stands for REpresentational State Transfer

What You Will learn

End of this tutorial, you will learn to create a spring boot application with Rest service

Rest Service Annotation
// This annotation used to mention a class as Controller class
@RestController
// Here we are using this to retrieve value
@GetMapping
application.properties
server.port=8080
Dependency
<parent>                                                                    
  <groupId>org.springframework.boot</groupId>                               
  <artifactId>spring-boot-starter-parent</artifactId>                       
  <version>2.2.6.RELEASE</version>                                          
  <relativePath /> <!-- lookup parent from repository -->                   
</parent>

<dependency>                                                                
  <groupId>org.springframework.boot</groupId>                               
  <artifactId>spring-boot-starter-web</artifactId>                          
</dependency>

<dependencyManagement>                                                      
  <dependencies>                                                            
    <dependency>                                                            
      <groupId>org.springframework.cloud</groupId>                          
      <artifactId>spring-cloud-dependencies</artifactId>                    
      <version>${spring-cloud.version}</version>                            
      <type>pom</type>                                                      
      <scope>import</scope>                                                 
    </dependency>                                                           
  </dependencies>                                                           
</dependencyManagement> 
Sample Code
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

// This annotation used to mention a class as Controller class
@RestController
public class StudentController {

	// To Retrieve we can use Get method
	@GetMapping
	public String getName() {
		return "BeginnersBug";
	}
}

In above example we are using a simple method to retrieve a hard coded value from spring boot rest service

@RestController

This annotation is the combination of @Controller and @ResponseBody. Which will mention particular class as a Controller class

@GetMapping

This annotation for mapping HTTP GET requests onto specific handler methods.

@PostMapping

This annotation for mapping HTTP POST requests onto specific handler methods.
Note : Here we didn’t used this annotation

Time needed: 45 minutes

Steps

  1. Create Spring boot Project

    Follow this tutorial to create spring boot application
    https://beginnersbug.com/how-to-create-spring-boot-application/

  2. Create Controller Class

    Once you create and import the Spring boot application in eclipse
    Create a Class, Here I created as StudentController.java

  3. Add @RestController annotation

    Add @RestController annotation to the class level as like in the above sample code

  4. Create a method to return String

    Here I created a simple method with return type as String
    public String getName() {return “BeginnersBug”;}

  5. Add @GetMapping annotation

    Add @GetMapping(“/name”) annotation to the method level as like in the above sample code

  6. Edit application.properties

    Navigate to application.properties under src/main/resources/
    add this server.port=8080

  7. Run

    Navigate to main class. Right Click and click on RunAs –>JavaApplication

  8. Testing

    Open Browser http://localhost:8080/name . You can see the BeginnersBug in the browser

Github

https://github.com/rkumar9090/student

Related Articles

how to create spring boot application