有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否可以在spring boot中验证用户的空输入?

我正在编写一个spring引导应用程序,在验证用户的空输入时遇到了一些问题。 是否有方法验证用户的空输入? 例如:

@PostMapping("/new_post/{id}")
public int addNewPost(@PathVariable("id") Integer id, @RequestBody Post post) {
    return postService.addNewPost(id, post);
}`

在这里,我只想在数据库中存在用户的情况下添加一个新帖子,但当我发送此帖子请求时,我会收到常规的404错误消息,并且我无法提供自己的异常,尽管在我的代码中,我验证id是否等于null

http://localhost:8080/new_post/

知道我能做什么吗

谢谢


共 (3) 个答案

  1. # 1 楼答案

    我认为你需要这样做:

    @PostMapping(value = {"/new_post/", "/new_post/{id}"})
    public int addNewPost(@PathVariable(value = "id", required = false) Integer id, @RequestBody Post post) {
    

    这样,当ID为null时,您也可以处理URL

  2. # 2 楼答案

    我认为这是另外两个更好的答案:

    @PostMapping("/new_post/{id}")
    public int addNewPost(@PathVariable("id") Integer id, @RequestBody Post post)
    {
        if(!ObjectUtils.isEmpty(post))
        {
           return postService.addNewPost(id, post);
        }
        else 
         return null; // You can throws an Exception or any others response
    }
    

    id:不需要检查“id”,因为没有id,请求的方法不会被调用

  3. # 3 楼答案

    你可以这样做

    @PostMapping(value = {"/new_post/{id}", "/new_post"})
    public int addNewPost(@PathVariable(required = false, name="id") Integer id, @RequestBody Post post) {
        return postService.addNewPost(id, post);
    }
    

    但是处理这个问题的理想方法是使用@RequestParam@RequestParam就是为了这个目的