【发布时间】:2017-04-07 13:42:16
【问题描述】:
我正在使用 spring boot、thymeleaf 和 angularjs 构建一个仪表板应用程序。目标是触发来自 ui 的请求,每次按下按钮时将获取另一个服务的状态。因为我想管理 java 中的逻辑,所以我正在向 api 发出服务器端请求。请注意,服务类所引用的 api 已启用 cors(为简单起见,此处省略了主机 'localhost:9090' 上的外部服务)。
这是一个人为的例子,展示了我想要做什么:
<!--index.html-->
<html lang="en" ng-app="myApp" xmlns:th="http://www.thymeleaf.org">
<head>
<!--missing html not relevant-->
<div class="content">
<div class="container-fluid">
<div class="row">
<form id="services" ng-controller="myController">
<div class="form-group" >
<button type="button" class="btn btn-outline-primary" ng-click="result()">Primary</button>
<div id='whatever' class='panel-body'>
<strong th:text='${responseBody}'></strong>
</div>
</div>
</form>
</div>
</div>
</div>
...
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
//Spring控制器和服务
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}
package quick.thymeleaf.template.services;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class SimpleService {
public ResponseEntity getResponse(){
RestTemplate restTemplate = new RestTemplate();
//this is the url for the other service in this example.
//calls to this service returns a json string.
String url = "http://localhost:9090";
return restTemplate.getForEntity(url, String.class);
}
}
package quick.thymeleaf.template.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import quick.thymeleaf.template.services.SimpleService;
@Controller
public class AnotherController {
@Autowired
private SimpleService simpleservice;
@GetMapping("/path/tosomethingelse")
public void doSomething(Model model){
ResponseEntity<String> response = simpleservice.getResponse();
model.addAttribute("responseBody", response.getBody().toString());
}
}
//app.js
var app = angular.module('myApp', []);
app.controller('myController', function request($scope, $http, $log){
$scope.result = function() { $http({
method: 'GET',
url: '/path/tosomethingelse'})
.then(function (response){
$scope.responseData = response.data;
$log.info(response);
}, function(reason){
$scope.error = reason.data;
$log.info(reason);
});
}
});
向 localhost:8080 发出请求并单击启动 api 调用的按钮会在服务器日志中获取 json,但它不会显示在 html 标记中。我确信该设计不是该应用程序的最佳设计,但现在的重点是让它作为学习过程的一部分发挥作用,以了解完整的技术堆栈。
【问题讨论】:
标签: java angularjs spring thymeleaf