0

I started working on micro services recently. I created a Service. Tested it using Postman.

I get a successful response status : 201. Data is inserted in my DB.

I referred to the below mentioned site for the service code.

http://www.bytestree.com/spring/restful-web-service-crud-operation-spring-boot-example/

Now I want to send a json data object from a jsp to the service.

Below is my jsp. It is not running on any server and is a static page.

<!DOCTYPE HTML>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>Employee</title>

</head> 
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
function saveEmployee(){
    alert("Tushar");
    var employee = {}
    employee["firstname"] = $("#firstname").val();
    employee["lastname"] = $("#lastname").val();
    employee["designation"] = $("#designation").val();
    employee["salary"] = $("#salary").val();

    $.ajax({
        type : "POST",
        dataType : 'json',
        contentType : "application/json",
        url : "http://localhost:8080/rest/employee",
        data : JSON.stringify(employee),
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);

        },
        error : function(e) {
            console.log("ERROR: ", e);

        },
        done : function(e) {
            console.log("DONE");
        }
    });

}

</script>
<body>

<form name="EmployeeForm">

<div class="mainArea">

<label>Id:</label>
<input id="id" name="id" type="text" disabled />

<label>First Name:</label>
<input type="text" id="firstname" name="firstname" required>

<label>Last Name:</label>
<input type="text" id="lastname" name="lastname"/>

<label>Designation:</label>
<input type="text" id="designation" name="designation"/>

<label>Salary:</label>
<input type="text" id="salary" name="salary"/>


<button id="btnSave" onclick="saveEmployee()">Save</button>
<button id="btnDelete">Delete</button>

</div>

</form>

</body>
</html>

Employee Entity

@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {

    private static final long serialVersionUID = 4910225916550731446L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @Column(name = "firstname", length = 50)
    private String firstname;

    @Column(name = "lastname", length = 50)
    private String lastname;

    @Column(name = "designation", length = 20)
    private String designation;

    @Column(name = "salary")
    private Integer salary;

    public Employee() {
    }

    public Employee(Long id) {
        this.id = id;
    }

    public Employee(Long id, String firstname, String lastname, String designation, Integer salary) {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.designation = designation;
        this.salary = salary;
    }

    public Employee(String firstname, String lastname, String designation, Integer salary) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.designation = designation;
        this.salary = salary;
    }

    public Long getId() {
        return this.id;
    }

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

    public String getFirstname() {
        return this.firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return this.lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getDesignation() {
        return this.designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public Integer getSalary() {
        return this.salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Id: ").append(this.id).append(", firstName: ").append(this.firstname).append(", lastName: ")
                .append(this.lastname).append(", Designation: ").append(this.designation).append(", Salary: ")
                .append(this.salary);
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (id == null || obj == null || getClass() != obj.getClass())
            return false;
        Employee toCompare = (Employee) obj;
        return id.equals(toCompare.id);
    }

    @Override
    public int hashCode() {
        return id == null ? 0 : id.hashCode();
    }

}

Controller

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    final static Logger logger = Logger.getLogger(EmployeeController.class);

    @Autowired
    EmployeeService empService;

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee) {
        empService.save(employee);
        logger.debug("Added:: " + employee);
        return new ResponseEntity<Employee>(employee, HttpStatus.CREATED);
    }


    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<Void> updateEmployee(@RequestBody Employee employee) {
        Employee existingEmp = empService.getById(employee.getId());
        if (existingEmp == null) {
            logger.debug("Employee with id " + employee.getId() + " does not exists");
            return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
        } else {
            empService.save(employee);
            return new ResponseEntity<Void>(HttpStatus.OK);
        }
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<Employee> getEmployee(@PathVariable("id") Long id) {
        Employee employee = empService.getById(id);
        if (employee == null) {
            logger.debug("Employee with id " + id + " does not exists");
            return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
        }
        logger.debug("Found Employee:: " + employee);
        return new ResponseEntity<Employee>(employee, HttpStatus.OK);
    }


    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<Employee>> getAllEmployees() {
        List<Employee> employees = empService.getAll();
        if (employees.isEmpty()) {
            logger.debug("Employees does not exists");
            return new ResponseEntity<List<Employee>>(HttpStatus.NO_CONTENT);
        }
        logger.debug("Found " + employees.size() + " Employees");
        logger.debug(Arrays.toString(employees.toArray()));
        return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Void> deleteEmployee(@PathVariable("id") Long id) {
        Employee employee = empService.getById(id);
        if (employee == null) {
            logger.debug("Employee with id " + id + " does not exists");
            return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
        } else {
            empService.delete(id);
            logger.debug("Employee with id " + id + " deleted");
            return new ResponseEntity<Void>(HttpStatus.GONE);
        }
    }

}

Application class

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

I am not able to receive the Post request from jsp to service.

I don't see any exceptions in service logs. I see exceptions on the console of Firefox.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rest/employee. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

ERROR: Object { readyState: 0, getResponseHeader: .ajax/w.getResponseHeader(), getAllResponseHeaders: .ajax/w.getAllResponseHeaders(), setRequestHeader: .ajax/w.setRequestHeader(), overrideMimeType: .ajax/w.overrideMimeType(), statusCode: .ajax/w.statusCode(), abort: .ajax/w.abort(), state: .Deferred/d.state(), always: .Deferred/d.always(), then: .Deferred/d.then(), 11 more… }

Please help me find the problem.

Tushar Banne
  • 1,587
  • 4
  • 20
  • 38

2 Answers2

0

Please, specify button's type attribute explicitly:

<button type="button" onclick="saveEmployee()">Save</button>

Otherwise, Browsers might set it to submit by default.

Gurkan Yesilyurt
  • 2,635
  • 2
  • 20
  • 21
0

Your page is opened in the browser directly from the file system and browser prevents sending requests to different hosts and as your error message says it's related to CORS.

Basically, you have two options:

  1. Setup CORS server-side using CorsConfiguration.
  2. Serve your page from the same Spring Boot application.
ledniov
  • 2,302
  • 3
  • 21
  • 27