我想验证我的控制器中的请求参数之一。请求参数应该来自给定值列表之一,如果不是,则应该抛出错误。在下面的代码中,我希望请求参数 orderBy 来自@ValuesAllowed 中存在的值列表。
@RestController
@RequestMapping("/api/opportunity")
@Api(value = "Opportunity APIs")
@ValuesAllowed(propName = "orderBy", values = { "OpportunityCount", "OpportunityPublishedCount", "ApplicationCount",
"ApplicationsApprovedCount" })
public class OpportunityController {
@GetMapping("/vendors/list")
@ApiOperation(value = "Get all vendors")
public ResultWrapperDTO getVendorpage(@RequestParam(required = false) String term,
@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size,
@RequestParam(required = false) String orderBy, @RequestParam(required = false) String sortDir) {
Run Code Online (Sandbox Code Playgroud)
我编写了一个自定义 bean 验证器,但不知何故这不起作用。即使我为查询 param 传递了任何随机值,它也不会验证并抛出错误。
@Repeatable(ValuesAllowedMultiple.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {ValuesAllowedValidator.class})
public @interface ValuesAllowed {
String message() default "Field value should …Run Code Online (Sandbox Code Playgroud) validation controller spring-annotations http-request-parameters spring-boot
我使用Spring Boot设置了一个非常简单的文件上传。我想知道当超过最大文件大小时是否有一种简单的方法来显示错误页面。
我已经上传了一个非常简单的示例,说明了我想在github上实现的目标。
基本上,这个想法是在全局Spring异常处理程序中捕获MultipartException:
@ControllerAdvice
public class UploadExceptionHandler {
@ExceptionHandler(MultipartException.class)
public ModelAndView handleError(MultipartException exception) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error", exception.getMessage());
modelAndView.setViewName("uploadPage");
return modelAndView;
}
}
Run Code Online (Sandbox Code Playgroud)
处理文件上传的控制器非常简单:
@RequestMapping("/")
public String uploadPage() {
return "uploadPage";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String onUpload(@RequestParam MultipartFile file) {
System.out.println(file.getOriginalFilename());
return "uploadPage";
}
Run Code Online (Sandbox Code Playgroud)
还有与之关联的uploadPage.html百里香模板:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Upload</title>
</head>
<body>
<div style="color: red" th:text="${error}" th:if="${error}">
Error during upload
</div>
<form th:action="@{/}" method="post" enctype="multipart/form-data">
<input type="file" id="file" …Run Code Online (Sandbox Code Playgroud)