【问题标题】:Not able to send json data to service无法将 json 数据发送到服务
【发布时间】:2017-11-19 10:27:29
【问题描述】:

我最近开始研究微服务。 我创建了一个服务。使用邮递员对其进行了测试。

我得到一个成功的响应状态: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(),覆盖MimeType: .ajax/w.overrideMimeType(),状态码:.ajax/w.statusCode(),中止: .ajax/w.abort(),状态:.Deferred/d.state(),总是: .Deferred/d.always(),然后:.Deferred/d.then(),还有 11 个……}

请帮我找出问题。

【问题讨论】:

  • 请提供一些你正在使用的java代码。
  • Java 代码可在bytestree.com/spring/… 提到的链接上找到。它的代码相同。
  • 我创建了一个服务。使用 Postman 对其进行了测试,所以你得到了响应吗?
  • 是的。我得到了成功的回应。数据已插入我的数据库。
  • @TheHeadRush 对此感到抱歉。没有那样想。我会更新问题。

标签: java json spring jsp spring-boot


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您的页面是直接从文件系统在浏览器中打开的,并且浏览器会阻止向不同主机发送请求,并且正如您的错误消息所说,它与 CORS 有关。

    基本上,您有两种选择:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 2014-03-22
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      相关资源
      最近更新 更多