标签: spring-restcontroller

将参数映射为 Spring REST 控制器中的 GET 参数

如何将 Map 参数作为 url 中的 GET 参数传递给 Spring REST 控制器?

spring spring-mvc spring-restcontroller

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

Spring RestController POST 400 Bad Request

我有一个Spring RestController,尽管在Chrome开发者工具中发现了正确的数据,但任何尝试发布到它都会返回400 Bad Request.@Valid注释正在将其踢出,因为根本没有填充ParameterDTO对象.

我的控制器

@RestController
@RequestMapping(path = "/api/parameters", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public class ParameterResource {

    private final ParameterService parameterService;

    @Autowired
    public ParameterResource(ParameterService parameterService) {
        this.parameterService = parameterService;
    }

    @GetMapping
    public ResponseEntity<?> getParameters(@RequestParam(value = "subGroupId", required = false) Integer subGroupId) {
        if (subGroupId != null) {
            return ResponseEntity.ok(parameterService.getParameters(subGroupId));
        }
        return ResponseEntity.ok(parameterService.getParameters());
    }

    @PostMapping
    public ResponseEntity<?> createParameter(@Valid ParameterDTO parameterData) {
        int id = parameterService.saveParameter(parameterData);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(id).toUri();
        return ResponseEntity.created(uri).build();
    }

    @GetMapping(path = "/levels")
    public ResponseEntity<?> getParameterLevels() …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-restcontroller spring-rest

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

Spring MVC 控制器单元测试:如何设置私有实例布尔字段?

我有一个 Spring MVC REST 控制器类,它有一个通过 @Value 注入的私有实例布尔字段,

@Value("${...property_name..}")
private boolean isFileIndex;
Run Code Online (Sandbox Code Playgroud)

现在要对这个控制器类进行单元测试,我需要注入这个布尔值。

我该如何做到这一点MockMvc

我可以使用反射,但MockMvc实例没有给我传递给Field.setBoolean()方法的底层控制器实例。

测试类运行时无需模拟或注入此依赖项,其值始终为false。我需要将其设置true为覆盖所有路径。

设置如下所示。

@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {

    @Autowired
    private MockMvc mockMvc;
 ....
}
Run Code Online (Sandbox Code Playgroud)

java unit-testing spring-mvc spring-restcontroller

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

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

Jackson 还需要 getter 方法来使用 @JsonCreator 正确序列化 bean 属性

我在使用 Spring Boot 1.5 的应用程序中使用 Jackson 将一些 bean 序列化为 JSON。

我注意到要@JsonCreator正确使用 序列化 bean ,我必须为每个属性声明 getter 方法,以及@JsonProperty注释。

public class Person {
    private final String name;
    private final int age;

    @JsonCreator
    public Person(@JsonProperty("name") String name, 
                  @JsonProperty("age") int age) {
       this.name = name;
       this.age = age;
    }

    public String getName() {
        return this.name;
    }
    public int getAge() {
        return this.age;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我删除方法getName并且getAge,Jackson 没有序列化相关的属性。为什么 Jackson 还需要 getter 方法?

java json jackson spring-boot spring-restcontroller

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

是否可以在 Spring 控制器中拆分请求参数?

我有一个请求,例如:

example.com/search?sort=myfield1,-myfield2,myfield3
Run Code Online (Sandbox Code Playgroud)

我想拆分这些参数以List<String>在控制器中绑定排序,或者具有以下字段的类List<SortParam>在哪里:(字符串)和(布尔值)。SortParamnameask

所以最终的控制器看起来像这样:

@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(@RequestParam List<String> sort) {

    //...
}
Run Code Online (Sandbox Code Playgroud)

或者

@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(@RequestParam List<SortParam> sort) {

    //...
}
Run Code Online (Sandbox Code Playgroud)

有办法制作吗?

更新:

标准的参数传递方式不能满足我的要求。即我无法使用sort=myfield1&sort=-myfield2&sort=myfield3. 我必须使用逗号分隔的名称。
另外,我确实明白我可以@RequestParam String sort在控制器中接受,然后在控制器内分割字符串sort.split(","),但它也不能解决上述问题。

java spring spring-mvc spring-restcontroller spring-rest

4
推荐指数
2
解决办法
9926
查看次数

如何以 JSON 格式发送整数值并在 REST Controller 中接收?

我有一个 REST 控制器,我在其中编写了此代码

@PostMapping(value = "/otp")
public void otp(@RequestBody Integer mobile) {

    System.out.println(" Mobile = "+mobile);
}
Run Code Online (Sandbox Code Playgroud)

我使用以下输入从 Postman 调用此方法

URL : localhost:8080/otp

Body

{
    "mobile":123456
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下异常

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of java.lang.Integer out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
Run Code Online (Sandbox Code Playgroud)

如果我将 String 作为这样的参数

@PostMapping(value = "/otp")
public void otp(@RequestBody String mobile) {

    System.out.println(" Mobile = "+mobile);
}
Run Code Online (Sandbox Code Playgroud)

并将输入作为

{
    "mobile":123456
}
Run Code Online (Sandbox Code Playgroud)

现在它在控制台中打印如下

 Mobile …
Run Code Online (Sandbox Code Playgroud)

java spring json spring-boot spring-restcontroller

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

Spring ControllerAdvice - 无法覆盖 ResponseEntityExceptionHandler 中的 handleHttpRequestMethodNotSupported()

以下是我目前面临的情况的一些事实

  1. 我最近为 Spring RestController构建了一个RestControllerAdvice具有各种ExceptionHandler全局异常处理程序的函数。

  2. 由于我想返回我的自定义响应 json 以处理 中指定的预定义 HTTP 错误ResponseEntityExceptionHandler,因此我的RestControllerAdvice类继承了,并且覆盖了, 之类的ResponseEntityExceptionHandler方法。handleHttpRequestMethodNotSupported()handleHttpMessageNotReadable()

  3. 我已经成功覆盖handleHttpMediaTypeNotSupported()handleHttpMessageNotReadable()但是当涉及到时handleHttpRequestMethodNotSupported(),我没有这样做。

这是我的代码的摘录:

@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice(annotations=RestController.class)
public class TestRestExceptionHandler extends ResponseEntityExceptionHandler{

    @Override
    protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request){
        BaseResponseJson response = new BaseResponseJson();
        response.setRespCode(BaseResponseJson.JSON_RESP_CODE_ERROR);
        response.setRespMsg("Request Method Not Supported");
        return handleExceptionInternal(ex, response, headers, status, request);
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request){
        BaseResponseJson response = …
Run Code Online (Sandbox Code Playgroud)

api spring spring-mvc microservices spring-restcontroller

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

在 REST 控制器中使用 AtomicLong

以下代码段中的原子整数是否在不同的 REST 调用之间共享?如果它是静态的怎么办?

public class GreetingController {

    private static final String template = "Hello Docker, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", 
        defaultValue="World") String name) {

        return new Greeting(counter.incrementAndGet(),
          String.format(template, name));
    }
}
Run Code Online (Sandbox Code Playgroud)

java spring-mvc spring-restcontroller

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

如何配置 @PreAuthorize 来识别登录用户的 ID?

我正在尝试创建一个 Spring Boot 2.1 应用程序。我创建了以下休息控制器......

@RestController
@RequestMapping("/api/users")
public class UserController {
...

    @PutMapping("/{id}")
    @PreAuthorize("authentication.principal.id == #id")
    public ResponseEntity<User> update(@RequestBody User user, @PathVariable UUID id) {
        final User updatedUser = userService.update(id, user);
        if (updatedUser == null) {
            return ResponseEntity.notFound().build();
        } else {
            return ResponseEntity.ok(updatedUser);
        }
    }
Run Code Online (Sandbox Code Playgroud)

唯一能够访问此端点的人应该登录,并且他们的 ID 应与参数的 ID 匹配。但是,上面的操作失败并出现以下错误......

org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'id' cannot be found on object of type 'org.springframework.security.core.userdetails.User' - maybe not public or not valid?
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:217) ~[spring-expression-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104) ~[spring-expression-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:51) ~[spring-expression-5.2.7.RELEASE.jar:5.2.7.RELEASE] …
Run Code Online (Sandbox Code Playgroud)

authorization annotations spring-security spring-boot spring-restcontroller

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