标签: spring-restcontroller

Spring Jackson 数组代替列表

在我的 Spring Boot 应用程序中,我有以下@RestController方法:

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{decisionId}/decisions/{childDecisionId}/characteristics/{characteristicId}/values", method = RequestMethod.POST)
public ValueResponse create(@PathVariable @NotNull @DecimalMin("0") Long decisionId, @PathVariable @NotNull @DecimalMin("0") Long childDecisionId, @PathVariable @NotNull @DecimalMin("0") Long characteristicId,
        @Valid @RequestBody CreateValueRequest request, Authentication authentication) {
        ....
         request.getValue()
        ...
    }
Run Code Online (Sandbox Code Playgroud)

这是我的CreateValueRequest DTO:

public class CreateValueRequest implements Serializable {

    private static final long serialVersionUID = -1741284079320130378L;

    @NotNull
    private Object value;

...

}
Run Code Online (Sandbox Code Playgroud)

例如,该值可以是String, IntegerDouble以及相应的数组,例如String[], Integer[].. 等

如果是String, Integer, …

java spring jackson spring-restcontroller

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

如何从 Validated Spring RestController 获取多个缺失请求参数的详细信息?

我正在尝试使用 Spring 的两个验证@RequestParam,捕获@ControllerAdvice缺少参数时框架抛出的异常,并返回缺少参数的 400 错误。

所以,我的代码如下所示:

@RestController
@Validated
public class FooController {
  @RequestMapping(value = "/foo", method = RequestMethod.GET)
  @ResponseBody
  public Foo getFoo(@RequestParam LocalDate dateFrom, @RequestParam LocalDate dateTo) {
    // Do stuff
  }
}

@ControllerAdvice
public class ExceptionController {
  @ExceptionHandler(value = {MissingServletRequestParameterException.class})
  @ResponseStatus(value = HttpStatus.BAD_REQUEST)
  @ResponseBody
  public ErrorResponse handleMissingParameterException(MissingServletRequestParameterException ex) {
    return new ErrorResponse(ex.getMessage());
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我错过了一个参数,这将非常有效 - 我会得到一个很好的 JSON 响应,如下所示:

{
  "reason": "Required LocalDate parameter 'dateFrom' is not present"
}
Run Code Online (Sandbox Code Playgroud)

状态为 400。

但是,如果我错过了这两个参数,我会得到与上面相同的错误响应 - 即它只报告第一个缺失的参数,如果我可以列出所有参数,我会更喜欢它。

看看异常的方法,它似乎只打算处理单个参数 …

java spring spring-mvc spring-restcontroller

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

如何在 Spring boot Controller 中接受 GET 参数并返回适当的对象

我对 Spring Boot 非常陌生,我不知道该类@Controller。如果我在 Spring Boot 中找不到数据库中的特定对象,我应该传递什么?如果我将返回类型声明为Response Entity并发送 null User 对象,会更好吗?

//Get single user
@GetMapping("/users/{id}")
public User getUser(@PathVariable String id){
    try {
        Long i = Long.parseLong(id);
    } catch (NumberFormatException ex) {
        return ????    //Can't figure out what to return here. 
    }
    return userService.getUser(id);
}
Run Code Online (Sandbox Code Playgroud)

我希望消费者知道他们发送了无效的字符串。

2)此外,用户的变量id是类型LongLong那么我应该采用函数中的参数getUser还是采用字符串并解析它?Long如果在链接中发送字符串,则采取 a会使我的服务器崩溃。

spring-mvc spring-data-jpa spring-boot spring-restcontroller spring-rest

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

Spring 验证 @NotNull 不验证

我正在尝试使用 Spring Validator 验证 POST 请求。这是我要验证的对象:

@Validated
public class Request implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id1;
    private Long id2;   
    private String s;   
    private List<Mapping> mappings;

    public Request() {}
    public Request (Long id1, Long id2, String s, List<Mapping> mappings) {
        this.id1 = id1;
        this.id2 = id2;
        this.s = s;
        this.mappings = mappings;
    }

    //getter() and setter() methods.
}
Run Code Online (Sandbox Code Playgroud)

这是映射类:

@Validated
public class Mapping implements Serializable {
    private static final long serialVersionUID = 1L;
    @JsonProperty(value="id") …
Run Code Online (Sandbox Code Playgroud)

java spring spring-validator spring-boot spring-restcontroller

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

无法将数组传递给 Spring 启动 Java

我正在尝试向 Sprin boot 发送一个 POST 请求,其中包含正文中的自定义对象列表。我在请求正文中的 JSON 是这样的:

[{"name":"name1","icon":"icon1"},
{"name":"name2","icon":"icon2"},
{"name":"name3","icon":"icon3"}]
Run Code Online (Sandbox Code Playgroud)

我得到这个错误

Cannot construct instance of `io.wedaily.topics.models.Topic` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
Run Code Online (Sandbox Code Playgroud)

我的控制器:

@PostMapping
public void createTopics(@RequestBody List<Topic> topics) {
    System.out.println(topics);
}
Run Code Online (Sandbox Code Playgroud)

我的主题模型:

public class Topic {

    private Long id;
    private String name;
    private String icon;
    private Date createdAt;
// Constructor
// Getters
// Setters
}
Run Code Online (Sandbox Code Playgroud)

java spring-boot spring-restcontroller

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

如何在 Spring boot 中发送图像作为响应?

我是 Spring Boot (restController) 和 Angular 的初学者,我想用以下方法将图像发送到我的客户端(Angular):

@RestController public class ProductRestController { 
    @Autowired private ProductRepository pr;
    @GetMapping (path = "/ photoProduit / {id}", produces = org.springframework.http.MediaType.IMAGE_PNG_VALUE)
     public byte [] getPhoto (@PathVariable Long id) throws IOException { 
        Product p = pr.findById (id) .get (); return Files.readAllBytes (Paths.get (System.getProperty ("user.home") + "/ ecom / produits /" + p.getPhotoName ()));
        
    }
 }

Run Code Online (Sandbox Code Playgroud)

但 URL 返回代码500并出现此错误

There was an unexpected error 
(type = Internal Server Error, status = 500). C: \ Users …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-restcontroller

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

如何在 Spring Boot REST 控制器中使用请求和路径参数?

我有以下上传控制器,它有两个不同类型的参数:1 用于保存文件的路径,2 用于文件本身。我正在寻找正确的方法定义,而不是 2 个在 STS 中给出错误的 @Requestparam。

@PostMapping("/{path}/")
public String handleFileUpload(@RequestParam("path"), @RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    
    filesStorageService.store(file);
    redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
    
    return "redirect:/";
}
Run Code Online (Sandbox Code Playgroud)

rest spring-boot spring-restcontroller

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

收到的文件比发送的文件大

这是发送文件的代码:

byte[] data = FileUtils.readFileToByteArray(new File("my_file.docx"));

System.out.println(data.length); // prints 6408

ResponseEntity<byte[]> responseEntity = makeResponse(data, HttpStatus.OK, DOCX);

return responseEntity;


private <T> ResponseEntity<T> makeResponse(T responseParameter, HttpStatus httpStatus,
                                           DocumentFormat documentFormat) {
    HttpHeaders headers = new HttpHeaders();

    String filename;

    switch (documentFormat) {
        case PDF:
            headers.setContentType(MediaType.parseMediaType("application/pdf"));
            filename = "output.pdf";
            break;
        case DOCX:
            headers.setContentType(MediaType.parseMediaType("application/docx"));
            filename = "output.docx";
            break;
        default:
            throw new IllegalArgumentException(documentFormat.name() + "is not supported");
    }

    headers.setContentDispositionFormData(filename, filename);
    return new ResponseEntity<>(responseParameter, headers, httpStatus);
}
Run Code Online (Sandbox Code Playgroud)

收到的文件大小为8546字节.发送的文件大小为6408字节.即使编码在某种程度上是错误的,接收的文件应该是相同的大小,对吧?接收文件的内部看起来像两个随机字符的两页,"UEsDBBQACAgIANqVt0YAAAAAAAAAAAAA"< - 像这样.

我尝试将我从my_file.docx读取的字节数组写入本地磁盘上的文件,然后再发送响应,它可以正常工作.

我也尝试setHtentLength我正在发送的标题,但它产生相同的结果 - 接收文件的内容错误,即使大小正确.

想知道额外的2Kb来自哪里?我该如何解决这个错误?

java file spring-restcontroller

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

Spring Boot @RestController拒绝POST请求

POST请求

http:// localhost:9278 / submitEnrollment

封装外部SOAP调用的Spring Boot应用程序执行以下操作:

{
  "timestamp": 1439480941381,
  "status": 401,
  "error": "Unauthorized",
  "message": "Full authentication is required to access this resource",
  "path": "/submitEnrollment"
}
Run Code Online (Sandbox Code Playgroud)

这似乎不是正常现象,我想知道我需要放松/禁用哪些Spring Boot配置才能阻止此客户端身份验证。

以下是相关的代码段:

应用程序的配置(需要通过SSL发送安全的SOAP调用所需的所有必要操作,并会影响网络层):

    @Configuration
@ComponentScan({"a.b.c.d", "com.submit.enrollment"})
@PropertySource("classpath:/submit-enrollment.properties")
public class SubmitEnrollmentConfig {

    @Value("${marshaller.contextPaths}")
    private String[] marshallerContextPaths;

    @Value("${default.Uri}")
    private String defaultUri;

    @Bean
    public FfmSoapClient connectivityClient() throws Throwable {
        FfmSoapClient client = new FfmSoapClient();
        client.setWebServiceTemplate(webServiceTemplate());
        return client;
    }

    @Bean
    public KeyStore keyStore() throws Throwable {
        KeyStoreFactoryBean keyStoreFactory = new KeyStoreFactoryBean();
        keyStoreFactory.setPassword("!zxy!36!");
        keyStoreFactory.setLocation(new ClassPathResource("zxy.jks"));
        keyStoreFactory.setType("jks");
        keyStoreFactory.afterPropertiesSet();
        return …
Run Code Online (Sandbox Code Playgroud)

security configuration web spring-boot spring-restcontroller

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

@RequestBody和@RequestParam都不起作用

我想在春天做一个PUT电话.

这是我的控制器代码:

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestBody String id){
        return service.magic(id);
    }
Run Code Online (Sandbox Code Playgroud)

因为我想在通话中传递一个id字符串.

问题是,我收到了这个

{
  "timestamp": 1486644310464,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "java.lang.NullPointerException",
  "message": "{\n\t\"id\":\"589c5e322abb5f28631ef2cc\"\n}",
  "path": "/api/todo/magic"
}
Run Code Online (Sandbox Code Playgroud)

如果我改变这样的代码:

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestParam(value = "id") String id){
        return service.magic(id);
    }
Run Code Online (Sandbox Code Playgroud)

我收到

{
  "timestamp": 1486644539977,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
  "message": "Required String parameter 'id' is not present",
  "path": "/api/todo/magic"
}
Run Code Online (Sandbox Code Playgroud)

我做了同样的电话,一个PUT在链接http:// localhost:8080/api/todo/magic with body

{
    "id":"589c5e322abb5f28631ef2cc"
}
Run Code Online (Sandbox Code Playgroud)

这是我的数据库中一个对象的id. …

java spring spring-mvc spring-restcontroller

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

如何限制@RequestBody中映射的字段

我正在尝试实现一个非常基本的 Spring Boot Web 应用程序。我在@RequestBody.

addCustomer方法中,我只想绑定/映射firstNamelastName字段并忽略Id字段,即使客户端响应JSON 具有该字段也是如此。

updateCustomer方法中,我需要映射包括Id在内的所有字段,因为我需要Id字段来更新实体。

我怎样才能忽略@RequestBody.

@RestController
@RequestMapping("/customer-service")
public class CustomerController {
    @Autowired
    CustomerServiceImpl customerService; 

    //This method has to ignore "id" field in mapping to newCustomer
    @PostMapping(path = "/addCustomer")
    public void addCustomer(@RequestBody Customer newCustomer) {
        customerService.saveCustomer(newCustomer);
    }

    //This method has to include "id" field as well to updatedCustomer
    @PostMapping(path = "/updateCustomer")
    public void updateCustomer(@RequestBody Customer updatedCustomer) {
        customerService.updateCustomer(updatedCustomer);
    }
} …
Run Code Online (Sandbox Code Playgroud)

jackson spring-boot spring-restcontroller

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

从@RestController返回@Entity而不是DTO时有什么陷阱吗?

从 @RestController 返回 @Entity 而不是 DTO 时是否有任何陷阱?像这样:

    @RestController
    public class EmployeeRestController {
    
        @Autowired
        private EmployeeRepository repository;
        
        @GetMapping("/rest/employee/get/{id}")
        public Employee getEmployeeByID(@PathVariable("id") int id) {
            return repository.retrieve(id);
        }

@Entity
public class Employee {
...
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-boot spring-restcontroller

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

@Autowired 在同一控制器的其他方法中无法在一个控制器中正常工作

当我将新的 @RequestMapping 方法添加到控制器时,@Autowired 突然停止工作。为什么我不明白。当我尝试使用这个新方法时,所有 @Autowired 接口都变为空。当我将其他 @RequestMapping 用于其他方法时,一切正常。

在此处输入图片说明

当我尝试使用新的@RequestMapping 时,第一张图片显示所有@Autowired 类为空。

在此处输入图片说明

这我使用其他@RequestMapping 都可以完美运行。这是 spring Rest Api 应用程序。我以前没有遇到过这些事情。什么可能是这样的应用程序。

java spring autowired spring-restcontroller

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