【问题标题】:How to dynamically populate javascript file directly from spring boot java controller in json format?如何直接从spring boot java控制器以json格式动态填充javascript文件?
【发布时间】:2019-02-06 06:09:50
【问题描述】:

在我的 main.js 文件中,我想从 spring boot 控制器中获取某种特定 json 格式的数据。 例如。

var contactsJSON = [{"userId": "firstuser", "displayName": "firstuser"},
                    {"userId": "seconduser", "displayName": "seconduser"}];

现在在我的控制器“/users”中,我正在返回所有用户的列表。 我希望在应用程序加载时以所需的 json 格式动态填充contactsJSON 的值(我只需要用户名来创建 JSON)。

main.js

var contactsJSON = [{"userId": "firstuser", "displayName": "firstuser"
                    },
                   {"userId": "seconduser", "displayName": "seconduser"
                   },
                   {"userId": "thirduser", "displayName": "thirduser"
                   }
                  ];

UserController.java

 @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String viewUsers(Model model) {

       List<User> list = userService.getAllUsers();

       model.addAttribute("userList", list);

       return "welcome";
    }

List contains  private Long id;
    private String username;
    private String password;
    private String passwordConfirm;

我想在我的 javascript 文件中动态提供 contactsJSON 的值。我该怎么做?

【问题讨论】:

  • 您使用的是 Thymeleaf 之类的模板库吗? "welcome" 指的是什么?
  • 谢谢菲尔。但是这里欢迎的是 .jsp 文件,我在其中显示用户列表。例如。在我的welcome.jsp 文件中,我显示用户列表如下“查看用户

    ${listValue}

    " 同样,我想调用javascript文件中的代码。有什么办法吗?

标签: javascript java spring-boot jsp


【解决方案1】:

您可以将响应作为字符串返回,也可以使用 Spring 提供的 ResponseEntity 对象,如下所示。这样也可以返回Http状态码,对web服务调用更有帮助。

@RestController
@RequestMapping("/api")
public class MyRestController
    {

        @RequestMapping(value = "/users", method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<Object> viewUsers(Model model) {
        {
             //Get data from service layer into entityList.
            List<User> list = userService.getAllUsers();
            List<JSONObject> entities = new ArrayList<JSONObject>();
            for (Entity n : list) { // You can  iterate over the list and add in json format below is the example  for same 
                //JSONObject entity = new JSONObject();
                //entity.put("aa", "bb");
                //entities.add(entity);
            }
            return new ResponseEntity<Object>(entities, HttpStatus.OK);
        }
    }

【讨论】:

  • 谢谢莫汉。我将如何从我的 javascript 文件中调用此控制器?我想从js调用这段代码
  • 您可以以与之前调用类似的方式调用(从 javascript 文件调用 REST API 的一种方法是使用这样的 ajax)$.ajax({ url: 'localhost:8080/api/users' }) .then(function(data) { console.log(data); });如果需要,您还可以在 ajax 调用中设置标题
【解决方案2】:

首先,Thymeleaf 推荐

我强烈推荐 Thymeleaf 而不是 JSP 模板。一方面,它使内联对象到 JSON 表达式非常容易。比如……

<script th:inline="javascript">
const contactsJSON = [[${userList}]];
</script>

见https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#advanced-inlined-evaluation-and-javascript-serialization


如果您不想切换,我建议您添加一个 AJAX 调用来获取您的用户数据。在 Java 端,它可能看起来像这样

@GetRequest(path = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
    return userService.getAllUsers();
}

Spring 会自动将响应序列化为 JSON。

然后在你的welcome.jsp

<script>
// load the current URL (ie /users) but requesting JSON
fetch('', {
  headers: {
    Accept: 'application/json'
  }
}).then(res => res.json()).then(contactsJSON => {
  // you can now use contactsJSON here
})
</script>

【讨论】:

  • 谢谢菲尔 :-)
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
相关资源
最近更新 更多