spring-data-jpa 如何处理此异常错误

mutmk8jj  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(124)

我在我的后台spring Boot 项目中实现了 searching。当我尝试搜索任何关键字时,它都能正常工作,但是当我搜索空关键字时,它会抛出异常。如何处理这个异常?
postman image
Postman error image

代码
存储库

public interface PostRepo extends JpaRepository<Post, Integer>{
List<Post> findByUser(User user);
List<Post> findByCategory(Category category);
    //seach
List<Post> findByTitleContaining(String title);
}

后续服务接口

//search
List<PostDto> searchPosts(String keyword);

PostServiceImpl类

// search
@Override
public List<PostDto> searchPosts(String keyword) {
    List<Post> posts = this.postRepo.findByTitleContaining(keyword);
    List<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(post, PostDto.class)).collect(Collectors.toList());
    return postDtos;
}

后置控制器

//search
@GetMapping("/posts/search/{keywords}")
public ResponseEntity<List<PostDto>> searchPostByTitle(@PathVariable("keywords") String keywords){
    List<PostDto> result = this.postService.searchPosts(keywords);
    return new ResponseEntity<List<PostDto>>(result, HttpStatus.OK);
}
nukf8bse

nukf8bse1#

正如您在stacktrace servlet调度程序中看到的,它无法处理变量“search”的输入值“\r\n”。发生这种情况是因为您使用了@PathVariable,servlet每次都在等待一致的url。在您的情况下,变量“search”的值在Windows中使用了“\r\n”一个换行符。您可以尝试设置此方法是@PathVariable(value="search",required = false)还是更可取的方法,使用@RequestParam代替@PathVariable

相关问题