无法将json数据发送到服务 [英] Not able to send json data to service

查看:149
本文介绍了无法将json数据发送到服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始从事微服务工作. 我创建了一个服务.使用邮递员对其进行了测试.

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

我获得成功的响应状态:201. 数据已插入我的数据库中.

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/

现在我想将jsp的json数据对象发送到服务.

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

下面是我的jsp.它不在任何服务器上运行,并且是静态页面.

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>

员工实体

@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接收到服务的发布请求.

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

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

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

跨源请求被阻止:同源策略禁止阅读 位于 http://localhost:8080/rest/employee 的远程资源. (原因: CORS标头"Access-Control-Allow-Origin"丢失).

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).

错误:对象{readyState:0,getResponseHeader: .ajax/w.getResponseHeader(),getAllResponseHeaders: .ajax/w.getAllResponseHeaders(),setRequestHeader: .ajax/w.setRequestHeader(),overrideMimeType: .ajax/w.overrideMimeType(),statusCode:.ajax/w.statusCode(),中止: .ajax/w.abort(),状态:.Deferred/d.state(),始终: .Deferred/d.always(),然后:.Deferred/d.then(),还有11个…

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… }

请帮助我发现问题.

推荐答案

您的页面在浏览器中直接从文件系统直接打开,浏览器阻止将请求发送到其他主机,并且您的错误消息说它与 CORS .

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. 使用 CorsConfiguration .
  2. 为您的页面提供服务.

这篇关于无法将json数据发送到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆