标签: spring-restcontroller

带有弹簧启动的无限循环,具有一对多的关系

在休息应用程序中,我使用jpa的spring boot.

我有一个Lodger班

谁有

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "lodger")
private List<Reference> referenceList;
Run Code Online (Sandbox Code Playgroud)

在我的班级参考中,我有

@ManyToOne
@JoinColumn(name = "lodgerId")
private Lodger lodger;
Run Code Online (Sandbox Code Playgroud)

当我称这种方法

@RequestMapping(value = "/lodgers/{lodgerId}", method = RequestMethod.GET)
public Lodger getLogderById(@PathVariable("lodgerId") long lodgerId) {
    return lodgerService.getLodger(lodgerId);
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: server.bean.Lodger["referenceList"]->org.hibernate.collection.internal.PersistentBag[0]->server.bean.Reference["lodger"]->server.bean.Lodger["referenceList"]->org.hibernate.collection.internal.PersistentBag[0]->server.bean.Reference["lodger"]->server.bean.Lodger["referenceList"]...
Run Code Online (Sandbox Code Playgroud)

spring spring-boot spring-restcontroller

5
推荐指数
3
解决办法
7319
查看次数

Spring Data mongodb聚合管道的分页结果

我在对聚合管道的结果进行分页时遇到了一些麻烦。在查看了In spring data mongodb 如何实现分页进行聚合后,我想出了一个感觉像 hacky 的解决方案。我首先执行匹配查询,然后按我搜索的字段分组,并对结果进行计数,将值映射到一个私有类:

private long getCount(String propertyName, String propertyValue) {
    MatchOperation matchOperation = match(
        Criteria.where(propertyName).is(propertyValue)
    );
    GroupOperation groupOperation = group(propertyName).count().as("count");
    Aggregation aggregation = newAggregation(matchOperation, groupOperation);
    return mongoTemplate.aggregate(aggregation, Athlete.class, NumberOfResults.class)
        .getMappedResults().get(0).getCount();
}

private class NumberOfResults {
    private int count;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,我就能够为我返回的页面对象提供一个“总”值:

public Page<Athlete> findAllByName(String name, Pageable pageable) {
    long total = getCount("team.name", name);
    Aggregation aggregation = getAggregation("team.name", name, pageable); …
Run Code Online (Sandbox Code Playgroud)

spring-data-mongodb spring-boot spring-restcontroller spring-rest

5
推荐指数
1
解决办法
5560
查看次数

使用 WebTestClient 和 ControllerAdvice 单元测试弹簧控制器

我正在尝试对我的控制器和特定情况进行单元测试:我的服务返回一个 Mono.Empty,我抛出一个 NotFoundException 并且我不想确保我收到 404 异常

这是我的控制器:

@GetMapping(path = "/{id}")
    public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) throws NotFoundException {

        return this.myService.getObject(id, JsonNode.class).switchIfEmpty(Mono.error(new NotFoundException()));

    }
Run Code Online (Sandbox Code Playgroud)

这是我的控制器建议:

@ControllerAdvice
public class RestResponseEntityExceptionHandler {

    @ExceptionHandler(value = { NotFoundException.class })
    protected ResponseEntity<String> handleNotFound(SaveActionException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
    }

}
Run Code Online (Sandbox Code Playgroud)

和我的测试:

@Before
    public void setup() {
        client = WebTestClient.bindToController(new MyController()).controllerAdvice(new RestResponseEntityExceptionHandler()).build();
    }
@Test
    public void assert_404() throws Exception {

        when(myService.getobject("id", JsonNode.class)).thenReturn(Mono.empty());

        WebTestClient.ResponseSpec response …
Run Code Online (Sandbox Code Playgroud)

junit spring-test spring-restcontroller spring-webflux

5
推荐指数
1
解决办法
3394
查看次数

GetMapping 使用 Spring Boot 生成 CSV 文件

我正在编写一个 spring rest 方法来从数据库中获取详细信息并将其设置在响应 POJO 中,然后返回它。目前,当使用 POSTMAN 或 RC(如带有数据的可下载 CSV 文件)命中 URL 时,我需要以 CSV 格式而不是默认 json 格式生成此响应。我用谷歌搜索了很多网站,但我不确定一些逻辑。

  1. 我们是否需要编写业务逻辑来将 pojo 类值转换为 csv 格式或者 spring 是否有任何转换机制?
  2. 许多地方都提到了 Produces = "text/csv",这是否正确转换了响应?

目前我还没有为 CSV 转换编写任何代码。

@GetMapping("/batch/export" , produces="text/csv")
public ResponseEntity<ApplicationResponse> getBatchDetails(
        HttpServletRequest request) {

    ApplicationRequest appRequest = ApplicationServiceMapper.mapRequestFromHttpRequest(request);
    ApplicationResponse response = appService.getDBDetails(appRequest);
    return new ResponseEntity<>(response, HttpStatus.OK);

}
Run Code Online (Sandbox Code Playgroud)

这里的响应是服务以 pojo 格式返回所有数据的响应,如果我们不在注释中给出产品,那么默认情况下 spring 将返回响应 json。有人可以指导我吗?提前致谢。

java csv spring spring-boot spring-restcontroller

5
推荐指数
1
解决办法
1万
查看次数

春季:自动生成CRUD Rest控制器

有没有一种方法可以为业务流程生成spring rest crontroller。
我想为给定的数据库对象生成CRUD服务。
例如,“ employee_mst”,自动生成CRUD服务代码。
这类似于我们过去在冬眠中或在loopback.io中对于节点所拥有的东西。
感谢周围的任何帮助。

spring spring-restcontroller spring-rest

5
推荐指数
1
解决办法
1648
查看次数

可以通过@RequestBody以外的方式弹出POST参数

我在@RestController一个应用程序中使用s,其中所有请求都是POST请求...正如我从这篇文章中了解到的那样,你不能将各个post参数映射到单个方法参数,而是需要将所有参数包装在一个对象中然后使用它object作为用@RequestBody这样注释的方法参数

@RequestMapping(value="/requestotp",method = RequestMethod.POST) 
    public String requestOTP( @RequestParam(value="idNumber") String idNumber , @RequestParam(value="applicationId") String applicationId) {
        return customerService.requestOTP(idNumber, applicationId);
Run Code Online (Sandbox Code Playgroud)

不适POST用于身体的要求{"idNumber":"345","applicationId":"64536"}

我的问题是,我有很多POST要求,每个只有一个或两个参数,这将是乏味的创建所有这些对象只是为了得到里面的请求......所以有相似的地方获得请求的方式任何其他方式参数(URL参数)处理?

spring spring-mvc spring-restcontroller

5
推荐指数
2
解决办法
2万
查看次数

Spring REST Controller没有响应Angular请求

我有一个应用程序来创建服务器证书请求,就像一个人使用java keytool或其他东西.我正在尝试将创建的证书请求和密钥返回到zip文件中,但对于我的生活,我无法让我的REST控制器响应http请求.更正:控制器响应,但方法中的代码永远不会执行.

服务器确实收到请求,因为我的CORS过滤器已执行.但是我在控制器方法中有一个调试集,它永远不会触发.方法的签名是否正确?我需要另一双眼睛吗?

这是我的控制器代码:

@RequestMapping(method = RequestMethod.POST, value = "/generateCert/")
public ResponseEntity<InputStreamResource> generateCert(@RequestBody CertInfo certInfo) {
    System.out.println("Received request to generate CSR...");

    byte[] responseBytes = commonDataService.generateCsr(certInfo);
    InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(responseBytes));

    System.out.println("Generated CSR with length of " + responseBytes.length);
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=certificate.zip")
            .contentType(MediaType.parseMediaType("application/zip"))
            .contentLength(responseBytes.length)
            .body(resource);
}
Run Code Online (Sandbox Code Playgroud)

这是Angular请求:

generateCertificate(reqBody: GenerateCert) {
   let headers = new Headers();
   headers.append('Content-Type', 'application/json');

   this.http.post(this.urlGenerateCert, JSON.stringify(reqBody), {headers: headers}).subscribe(
    (data) => {
        let dataType = data.type;
        let binaryData = [];
        binaryData.push(data);
        this.certBlob = new Blob(binaryData);
    });
    return …
Run Code Online (Sandbox Code Playgroud)

spring-mvc spring-boot spring-restcontroller

5
推荐指数
1
解决办法
1158
查看次数

如何验证非必需的 RequestParam 不为空?

我在我的弹簧控制器中使用验证器。如果@RequestParam需要没有问题,我可以用@NotBlank. 但是如果@RequestParam是可选的,我不能将它与 一起使用@NotBlank,因为这个参数是可选的,有时可以为空。我想验证@NotBlankString 是否不为空。有什么限制可以帮助我吗?

@RequestParam @NotBlank String name
Run Code Online (Sandbox Code Playgroud)

完美运行。我有问题,required=false 如果客户端不发送可选的描述参数,验证失败。

@PatchMapping("/role/{id}") 
public ResponseEntity<?> updateRole(HttpServletRequest request, @PathVariable @Positive Integer id,
                                   @RequestParam @NotBlank String name,
                                   @RequestParam(required = false) @NotBlank String description)
Run Code Online (Sandbox Code Playgroud)

我想验证@NotBlank描述是否不是null

`@RequestParam(required = false) @NotBlank String description`
Run Code Online (Sandbox Code Playgroud)

如果我这样使用,我会收到“输入验证失败!”。

java validation spring spring-restcontroller

5
推荐指数
1
解决办法
6216
查看次数

无需上网即可调用Spring控制器方法

tldr:有没有办法在不上网的情况下发出内部请求(使用方法的路径)?

——

为什么我需要它?我有一个接收许多事件的项目。谁将处理每个事件的决定由控制器做出。所以我有类似的东西:

@RestController
@RequestMapping("/events")
public class EventHandlerAPI {

    @Autowired 
    private EventAHandler eventAhandler;
    @Autowired 
    private EventBHandler eventBhandler;

    @PostMapping("/a")
    public void handleEventA(@RequestBody EventA event) {
       eventAhandler.handle(id, event);
    }

    @PostMapping("/b")
    public void handleEventB(@RequestBody EventB event) {
       eventBhandler.handle(id, event);
    }

}
Run Code Online (Sandbox Code Playgroud)

我们最近添加了通过队列服务接收事件的支持。它向我们发送有效载荷和事件类。我们的决定是让两个接口都工作(休息和排队)。避免代码重复的解决方案是让控制器选择哪个处理程序来处理事件。现在的代码类似于:

@Configuration
public class EventHandlerQueueConsumer {

    @Autowired 
    private EventHandlerAPI eventHandlerAPI;

    private Map<Class, EventHandler> eventHandlers;

    @PostConstruct 
    public void init() { 
        /* start listen queue */ 
        declareEventHandlers();
    }

    private void declareEventHandlers() {
        eventHandlers = new HashMap<>();
        eventHandlers.put(EventAHandler.class, (EventHandler<EventAHandler>) eventHandlerAPI::handleEventA);
        eventHandlers.put(EventBHandler.class, (EventHandler<EventBHandler>) eventHandlerAPI::handleEventB);
    } …
Run Code Online (Sandbox Code Playgroud)

java spring spring-restcontroller

5
推荐指数
1
解决办法
1068
查看次数

@RequestBody 未将 JSON 映射到 Java 对象 - Spring Boot

我无法将我的 JSON 从帖子的方法体转换为我的 POJO,@RequestBody在我的控制器类中。

我调试了错误,我看到某些字段被映射而其他字段没有。像这样(POJO)

name: null, typeOfPlan: null, Email: example@gmail.com, PhoneNum: 123456789, Website: test.org, Username: null, password: 1234,这很奇怪。

JSON:

{
    "confirmPassword": "1234",
    "email": "example@gmail.com",
    "password": "1234",
    "phoneNum": "123456789",
    "name": "Hello world",
    "typeOfPlan": "Test",
    "userName": "user",
    "website": "test.org"
}
Run Code Online (Sandbox Code Playgroud)

控制器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SomeController {

    @Autowired
    private Service foo;

    @CrossOrigin
    @PostMapping(value = "/create")
    private void createAccount(@RequestBody BigFoo bigFoo) {
        foo.createAccount(bigFoo);
    }
}
Run Code Online (Sandbox Code Playgroud)

从这里,我调用我的服务,然后调用 DAO 类。 …

java mapping json spring-boot spring-restcontroller

5
推荐指数
1
解决办法
1万
查看次数