我正在开发一个基于 Spring Data REST 的服务。由于我们使用 swagger(通过 SpringFox 生成)创建前端代码,因此我必须停用 HAL 格式的返回,该格式工作正常,但有一个例外。
如果请求的结果是空列表,则响应如下所示
{
"links": [
{
"rel": "self",
"href": "http://localhost:9999/users"
},
{
"rel": "profile",
"href": "http://localhost:9999/profile/users"
}
],
"content": [
{
"rel": null,
"collectionValue": true,
"relTargetType": "com.example.User",
"value": []
}
]
}
Run Code Online (Sandbox Code Playgroud)
如何获取空列表作为内容?
我想默认禁用 HAL 格式。
流文档,我设置了这个属性。
spring.hateoas.use-hal-as-default-json-media-type=false
Run Code Online (Sandbox Code Playgroud)
然后测试一下:
1. 带 header 的请求Accept: application/json。
标题:Content-Type: application/json;charset=UTF-8
回复:
{
"links": {}
}
Run Code Online (Sandbox Code Playgroud)
2. 带标头Accept: */*或不带Accept标头的请求。
标题:Content-Type: application/hal+json;charset=UTF-8
回复:
{
"_embedded": {},
"_links": {}
}
Run Code Online (Sandbox Code Playgroud)
版本spring-boot是1.5.3,我用的是spring-boot-starter-hateoas.
无论如何,在没有指定 header 的情况下,是否让 hatoas 在没有 HAL 的情况下响应 json?
多谢。
更新:
请求地址:http://localhost:8080/greeting
带有 header 的请求Accept: */*。
HTTP/1.1 200
Content-Type: application/hal+json;charset=UTF-8
{
"content":"Hello, World!",
"_links":{
"self":{
"href":"http://localhost:8080/greeting?name=World"
}
}
}
Run Code Online (Sandbox Code Playgroud)
带有 header 的请求 …
我想spring-data-rest通过API. URL 是根据域名生成的。这些 URL 是驼峰化的。
例如,考虑名为 的域名EntityA,关联的url和rel将为entityA(采用驼峰式命名)。
我如何配置spring-data-rest(或者我必须覆盖什么)才能kebab-case默认获得?(例如,entity-a代替entityA)
我知道我可以使用 @RestRepository 并提供每个存储库的 URL。但我正在寻找更好的解决方案。我想对实体和搜索方法使用kebak-case。
我一直在努力寻找任何示例来说明如何覆盖默认的 Spring Boot Data Rest JpaRepository 行为以返回 HAL 响应以外的其他内容。我发现 Siren 和 Json-LD 都可以满足要求,但没有任何如何让它与 spring 一起工作的示例。我正在使用 Spring 5、Spring Data Rest 2.0.4.RELEASE。请注意,我不想为自定义休息控制器执行此操作,而是为通过扩展 JpaRepository 提供的默认存储库执行此操作。这是我第一次发帖,因此对于我可能无意中违反的任何规则,我深表歉意。
更新:我能够找到一个具有 SirenMessageConverter 的库 Hydra-Spring,按照存储库上的示例,我能够执行以下操作:
@Configuration
@EnablePluginRegistries(RelProvider.class)
public class Config implements WebMvcConfigurer {
private static final boolean EVO_PRESENT =
ClassUtils.isPresent("org.atteo.evo.inflector.English", null);
@Autowired
private PluginRegistry<RelProvider, Class<?>> relProviderRegistry;
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(sirenMessageConverter());
converters.add(hydraMessageConverter());
converters.add(halConverter());
converters.add(uberConverter());
converters.add(xhtmlMessageConverter());
converters.add(jsonConverter());
}
@Bean
public RepositoryRestConfigurerAdapter repositoryRestConfigurer() {
return new RepositoryRestConfigurerAdapter() {
@Override
public void configureHttpMessageConverters(
List<HttpMessageConverter<?>> messageConverters) {
messageConverters.add(0, sirenMessageConverter());
} …Run Code Online (Sandbox Code Playgroud) 我正在使用 Spring Boot 2、Spring Data REST、Spring HATEOAS 创建一个 Spring REST 应用程序。
我创建了这个控制器:
@Api(tags = "City Entity")
@RepositoryRestController
@RequestMapping(path = "/api/v1")
@PreAuthorize("isAuthenticated()")
public class CityController {
@Autowired
private LocalValidatorFactoryBean validator;
@Autowired
private PagedBeanResourceAssembler<City> pagedBeanResourceAssembler;
@Autowired
private CityService cityService;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(validator);
}
@GetMapping(path = "/cities/search/autocomplete")
public ResponseEntity<?> autocomplete(@RequestParam(name = "city") String city, @RequestParam(name = "country", required = false) String country, Pageable pageable, Locale locale) {
return new ResponseEntity<>(pagedBeanResourceAssembler.toResource(cityService.autocomplete(city, country, pageable)), HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
服务方式为:
@Transactional(readOnly = true) …Run Code Online (Sandbox Code Playgroud) 我正在尝试将 HATEOAS 应用于现有应用程序,但在对由 API 响应驱动的表单输入进行建模时遇到问题。
\n\n该应用程序允许搜索和预订两个地方之间的连接。第一个端点允许搜索连接GET /connections?from={lat,lon}&to={lat,lon}&departure={dateTime}并返回以下有效负载(响应正文)。
[\n {\n "id": "aaa",\n "carrier": "Fast Bus",\n "price": 3.20,\n "departure": "2019-04-05T12:30"\n },\n {\n "id": "bbb",\n "carrier": "Airport Bus",\n "price": 4.60,\n "departure": "2019-04-05T13:30"\n },\n {\n "id": "ccc",\n "carrier": "Slow bus",\n "price": 1.60,\n "departure": "2019-04-05T11:30"\n }\n]\nRun Code Online (Sandbox Code Playgroud)\n\n为了对其中一个连接下订单,客户端需要POST /orders使用以下有效负载之一(请求正文)发出请求:
{\n "connectionId": "aaa",\n "email": "passenger@example.org"\n}\nRun Code Online (Sandbox Code Playgroud){\n "connectionId": "bbb",\n "email": "passenger@example.org",\n "flightNumber": "EA1234"\n}\nRun Code Online (Sandbox Code Playgroud){\n "connectionId": "ccc",\n "phoneNumber": "+44 111 222 333"\n}\nRun Code Online (Sandbox Code Playgroud)我正在关注 Spring RESTfull API 教程。本教程要求在某些时候使用 Spring HATEOAS。但是,我的 IDE STS找不到方法 linkTo 和 methodOn 的引用。
@GetMapping("/employees/{id}")
Resource<Employee> one(@PathVariable Long id) {
Employee emp = repository.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
return new Resource<>(emp,
linkTo(methodOn(EmployeeController.class).one(id)).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees")
);
}
Run Code Online (Sandbox Code Playgroud)
Spring HATEOAS 依赖也在这里:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我尝试过的事情:
我正在读《春天在行动》第五期。并添加 hatoas 超链接。这个类正在扩展org.springframework.hateoas.ResourceSupport,但我找不到它。我正在使用 Spring Boot 版本2.2.5.RELEASE
import org.springframework.hateoas.ResourceSupport;
import tacos.Taco;
@Relation(value = "taco", collectionRelation = "tacos")
public class TacoResource extends ResourceSupport {
private static final IngredientResourceAssembler ingredientAssembler = new IngredientResourceAssembler();
@Getter
private final String name;
Run Code Online (Sandbox Code Playgroud)
那么这个版本中这个类的名称是什么,因为源代码使用的是较旧的版本,我认为是 2.0.2 M1
如何使用Spring Data Rest启用缓存?
其背后的原因是,一旦应用程序启动,存储库列表和搜索方法就不会改变.此外,如果其余API背后的数据仅通过rest API进行更改,那么它也会启用缓存数据.
我相信某些级别是缓存发生在REST API框架中,如果缓存发生在最终响应阶段,即json响应(以避免将对象编组到json的开销),这将是理想的
思想/评论?
我有以下控制器方法:
@RequestMapping(method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity list(Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {
Page<Customer> customers = customerRepository.findAll(pageable);
return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler));
}
@RequestMapping(value = "/search", method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity search(@RequestParam("q") String q, Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {
Specification spec = where(..some specs..);
Page<Customer> customers = customerRepository.findAll(spec, pageable);
return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler));
}
Run Code Online (Sandbox Code Playgroud)
第一种方法将所有客户资源作为页面返回.
第二个也返回分页结果,但可以选择提供q要过滤的查询参数.
搜索方法的JSON HATEOAS响应包含下一页链接,如:
{
"rel": "next",
"href": "http://localhost:8080/api/customers/search?page=1&size=10{&sort}"
}
Run Code Online (Sandbox Code Playgroud)
问题是这里q查询参数丢失了.
我应该在PagedResourcesAssembler这里使用不同的吗?
spring-hateoas ×10
spring ×6
spring-boot ×4
java ×3
json-ld ×2
spring-data ×2
caching ×1
eclipse ×1
hal-json ×1
hateoas ×1
hydra-core ×1
json-api ×1
maven ×1
rest ×1