标签: spring-restcontroller

如何在 Spring 中返回具有除 List<Entity> 之外的多个属性的自定义响应

我正在尝试从 Spring Rest 控制器返回给用户的自定义响应,其中包含所有注册用户的列表和其他键(例如成功等)。我尝试了以下方法,但 Json 数组完全转义为细绳...

@GetMapping(value = "/workers", produces = "application/json;charset=UTF-8")
public ResponseEntity<String> getAllWorkers() throws JSONException {
    JSONObject resp = new JSONObject();
    ObjectMapper objectMapper = new ObjectMapper();

    HttpStatus status;
    try {
        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        List<Worker> workers = workerservice.getAllworkers();
        String json = mapper.writeValueAsString(workers);
        
        resp.put("success", true);
        resp.put("info", json);
        status = HttpStatus.OK;
    } catch (Error | JsonProcessingException e) {
        resp.put("success", false);
        resp.put("info", e.getMessage());
        status = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    return new ResponseEntity<>(resp.toString(),status);
}
Run Code Online (Sandbox Code Playgroud)

我得到这样的东西

{
    "success": true,
    "info": "[ {\n  \"id\" : …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-restcontroller

2
推荐指数
1
解决办法
9796
查看次数

Jackson 是否序列化未定义字段的 getter 属性?

我有一个包含以下字段及其各自的 getter 的类,以及一个附加方法getTotalBalance,我没有任何字段,但有一个自定义实现。

    public class demo{
    private String balance;
    private String blockedBalace;
    private String futureBalance;
    private String availableBalance;
    //getters for previous fields
    public String getTotalBalance(){
    //something..
    }
Run Code Online (Sandbox Code Playgroud)

当我序列化此类的对象时,我得到以下 JSON 输出。

     {
      "balance": "12.30",
      "blockedBalance":"23.45",
      "futureBalance" :"56.22",
      "availableBalance" :"12.30",
      "totalBalance" : "34.11"
     }
Run Code Online (Sandbox Code Playgroud)

即使我没有声明 的字段totalBalance,我最终还是将其序列化了。这怎么可能?

java spring spring-mvc jackson spring-restcontroller

2
推荐指数
1
解决办法
3304
查看次数

Spring REST请求映射

我想配置Spring将所有请求重定向到特定的Controller,而不管URL(长度和参数).我应该如何在RequestMapping注释中提供URL模式/正则表达式.我尝试使用下面的代码,但它无法正常工作.在这方面的任何帮助深表感谢.

    @Controller
    @RequestMapping("/*")
    public class ServiceController {
        @RequestMapping( method = RequestMethod.GET, value = "*" )
        public void getProjectList(HttpServletRequest httpServletRequest,Model model){

        }
    }
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc restful-url spring-restcontroller request-mapping

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

Spring MVC - 使用x-www-form-urlencoded导致MissingServletRequestParameterException的@RequestParam

以下Spring MVC代码抛出MissingServletRequestParameterException,

@Controller
@RequestMapping("/users")
public class XXXXResource extends AbstractResource {

.....

 @RequestMapping(method = RequestMethod.PUT
            , produces = {"application/json", "application/xml"}
            , consumes = {"application/x-www-form-urlencoded"}
    )
    public
    @ResponseBody
    Representation createXXXX(@NotNull @RequestParam("paramA") String paramA,
        @NotNull @RequestParam("paramB") String paramB,
        @NotNull @RequestParam("paramC") String paramC,
        @NotNull @RequestParam("paramD") String paramD ) throws Exception {
   ...
   }
}
Run Code Online (Sandbox Code Playgroud)

日志中没有堆栈跟踪,只有来自Postman的请求返回HTTP 400错误.

spring-mvc spring-boot spring-restcontroller

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

如何通过在 Spring RestController 中使用 ResponseEntity 返回具有多个属性的 Json

我正在为 Spring 的学习编写休息服务。我想从控制器返回动态响应(具有多个属性的 Json)。例如,我有一个方法,默认情况下我返回产品列表和 Spring,使用消息转换器将其转换为 Json。它工作正常。

@RequestMapping(value = { "" }, method = RequestMethod.GET)
public ResponseEntity<?> greet(@PathVariable Optional<Integer> productId) {

    List<Products> products = productService.findAllCategories();
    int count = products.size(); // also want to include this as count like below response
    return new ResponseEntity<List<Products>>(products, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

现在我想要这样的回应 Json

{
  "count": 23,
  "products":[
     {..},
     {..}
   ]
}
Run Code Online (Sandbox Code Playgroud)

计数显示列表计数。我如何返回这样的响应。或者指导我了解返回具有多个属性的 Json 等场景的最佳实践。

spring spring-restcontroller

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

Spring MVC @Controller 拦截自己的请求

想象一下我们有一个这样的控制器:

@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,如何以与@ExceptionHandler工作类似的方式为这个特定控制器实现一些常见的前\后处理?例如,我想在控制器中有一个方法,它在处理程序方法之前接收请求,但只对这个特定控制器的请求。

我知道RequestBodyAdviceResponseBodyAdvice接口,但想要控制器本地的东西。

作为使用示例 - 我想parameter在每个处理程序之前对公共变量进行一些验证。

java spring spring-mvc spring-restcontroller

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

如何在spring boot中从同一个应用程序调用另一个api

我有两个RestController用户和公司。

  • CompanyControllercompanies使用服务和回购级别从公司信息中获取并将其存储到表中。

  • UsersController : 用于获取和存储用户。

  • 关系:每个用户都与公司相关联(用户有一个公司)。

当新人User注册时,我们需要通过 id 获取公司信息并与用户个人资料相关联。

为此,我在 中有一个端点CompanyController,名为getCompanyInfo。我必须在保存用户配置文件的同时调用该端点来获取公司数据。

如何在 Spring Boot 中从同一个应用程序调用另一个 API?

rest spring spring-boot spring-restcontroller

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

无法在Spring REST控制器中将Map用作JSON @RequestParam

这个控制器

@GetMapping("temp")
public String temp(@RequestParam(value = "foo") int foo,
                   @RequestParam(value = "bar") Map<String, String> bar) {
    return "Hello";
}
Run Code Online (Sandbox Code Playgroud)

产生以下错误:

{
    "exception": "org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'java.util.Map'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map': no matching editors or conversion strategy found"
}
Run Code Online (Sandbox Code Playgroud)

我要的是通过一些JSON与bar参数: HTTP://本地主机:8089 / TEMP富= 7&酒吧=%7B%22A%22%3A%22B%22%7D? ,哪里foo7bar{"a":"b"} 为什么春节不能够这个简单的转换吗?请注意,如果将地图用作请求中@RequestBody的一个,它将起作用POST

spring http-request-parameters spring-boot spring-restcontroller

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

基于休息的视频流

使用spring boot,我想制作基于RESTful的视频播放器.我的文件浏览器中有.mp4扩展视频.如何通过创建休息端点在前端端提供这些视频?

我试过这种方法.视频可以启动或停止.但它无法向后或向前完成.无法达到所需的时间并开始.

spring video-streaming html5-video spring-boot spring-restcontroller

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

在春天用相同的名称创建替换rest控制器会导致Bean名称冲突?

长话短说,我不希望在春季启动时更换现有的控制器。

因此,我创建了一个新的rest控制器类,并开始向其添加功能。我想维护较旧的控制器,直到将来可以删除它为止(一旦完全实施了较新的版本)

所以我实际上有两个同名的类。

新班

@RestController
@RequestMapping("/api/v2/parts")
public class PartController implements PartsApi {
...
Run Code Online (Sandbox Code Playgroud)

旧类

@RepositoryRestController
public class PartController {
Run Code Online (Sandbox Code Playgroud)

启动服务时,发生以下错误:

Annotation-specified bean name 'partController' for bean class [controller.v2.PartController] conflicts with existing, non-compatible bean definition of same name and class [controller.PartController]
Run Code Online (Sandbox Code Playgroud)

我尝试使用@Qualifier注释,但无法编译。

Spring Boot应用程序中如何有两个具有相同名称的Rest类?

注意:我讨厌尝试重命名 PartController2

java spring spring-restcontroller

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