无法将json数据发送到服务

时间:2017-06-16 15:15:52

标签: java json spring jsp spring-boot

我最近开始从事微服务工作。 我创建了一个服务。使用Postman测试它。

我获得了成功的回复状态:201。 数据将插入我的数据库中。

我在下面提到的服务代码网站。

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

现在我想从jsp向服务发送一个json数据对象。

以下是我的jsp。它没有在任何服务器上运行,而且是一个静态页面。

<!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>

员工实体

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

}

控制器

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

}

申请类

@SpringBootApplication
public class Application {

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

我无法从jsp收到Post请求到服务。

我在服务日志中没有看到任何例外。 我在Firefox的控制台上看到了异常。

  

阻止跨源请求:同源策略禁止读取   http://localhost:8080/rest/employee处的远程资源。 (原因:   缺少CORS标题“Access-Control-Allow-Origin”。

     

错误:对象{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(),状态:.Deferred / d.state(),总是:   .Deferred / d.always(),然后:.Deferred / d.then(),11 more ...}

请帮我找到问题。

2 个答案:

答案 0 :(得分:0)

请明确指定按钮的类型属性:

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

否则,浏览器默认情况下可能会将其设置为submit

答案 1 :(得分:0)

您的页面直接在浏览器中从文件系统和浏览器中打开,阻止向不同的主机发送请求,并且您的错误消息表明它与CORS相关。

基本上,您有两种选择:

  1. 使用CorsConfiguration设置CORS服务器端。
  2. 来自同一个Spring Boot应用程序的
  3. Serve your page