【问题标题】:How to get information from my Frontend (Angular 2) in Spring Boot?如何在 Spring Boot 中从我的前端(Angular 2)获取信息?
【发布时间】:2018-02-27 14:27:44
【问题描述】:

嗯。我需要在我的后端创建函数来与我的前端进行通信。从我的后端获取信息的方法可以正常工作。但我不知道如何在我的后端读取 json 信息。

这是我的get方法:

 @RequestMapping("/hi")
 public @ResponseBody String getName(){
    UserInfo info = new UserInfo("Lucas Alves",21,"luke@email.com","99998888");
    Gson g = new Gson();
    return g.toJson(info);
 }

我正在使用 gson 库将我的对象 UserInfo 转换为 json 字符串。

现在我的问题是。如何获取从前端发送给我并在 UserInfo 中安全的 json 文本。

打字稿代码:

postUser(p: User){
   return this.http.post('http://localhost:8090/postUser', JSON.stringify(p), { headers: new Headers({ 'Content-Type': 'application/json' }) });
}

Java 代码:

@RequestMapping(value = {"/postUser"}, method = RequestMethod.POST)
public void createUser( What I need to have here? ) {
   //I Don't know what I need to do here.
}

【问题讨论】:

  • 你正在发送 json 所以,我认为,它应该是 @RequestBody UserInfo input,但如果你的 js User 不是一对一匹配,你可以创建一些 DTO 类

标签: json spring angular post spring-boot


【解决方案1】:

你的路不错。

可以实现一个User类,然后直接绑定它:

public class User {

    private String username;

}

还有你的服务

@RequestMapping(value = {"/postUser"}, method = RequestMethod.POST)
public void createUser( @RequestBody User user ) {
    user.username; // use it?
}

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2016-11-17
    • 2018-03-15
    • 1970-01-01
    相关资源
    最近更新 更多