验证在Java Spring应用程序中不起作用。

huangapple go评论73阅读模式
英文:

Validation not working in Java Spring Application

问题

API 类

    @RestController
    @RequestMapping("/laptops")
    @Validated
    public class LaptopApi {
        @Autowired
        private LaptopService laptopService;

        @Autowired
        private Environment environment;

        @GetMapping("/{id}")
        public ResponseEntity<LaptopDTO> getLaptop(@PathVariable Integer id) {
            LaptopDTO laptop = laptopService.getLaptop(id);
            return new ResponseEntity<>(laptop, HttpStatus.OK);
        }

        @GetMapping("/")
        public ResponseEntity<List<LaptopDTO>> getLaptops() {
            List<LaptopDTO> laptops = laptopService.getLaptops();
            return new ResponseEntity<>(laptops, HttpStatus.OK);
        }

        @PostMapping("/")
        public ResponseEntity<LaptopDTO> addLaptop(@RequestBody @Valid LaptopDTO laptopDTO) {
            Integer laptopId = laptopService.addLaptop(laptopDTO);
            return new ResponseEntity<>(laptopDTO, HttpStatus.OK);
        }

        @PutMapping("/")
        public ResponseEntity<LaptopDTO> updateSpecs(@RequestBody @Valid LaptopDTO laptopDTO) {
            laptopService.updateSpecs(laptopDTO);
            return new ResponseEntity<>(laptopDTO, HttpStatus.OK);
        }

        @DeleteMapping("{id}")
        public ResponseEntity<String> deleteLaptop(@PathVariable Integer id) {
            laptopService.deleteLaptop(id);
            return new ResponseEntity<>(environment.getProperty("API.LAPTOP_DELETE_SUCCESS") + " " + id,
                    HttpStatus.OK);
        }
    }

DTO 类我在单元测试中运行了正则表达式检查正常工作

    public class LaptopDTO {
        private Integer id;

        @NotNull
        private String name;

        @NotNull
        @Pattern(regexp = "(Intel core i[3579] [0-9]{4,}[A-Za-z]*)|"
                + "(AMD Ryzen [3579] [0-9]{4,}[A-Za-z]*)",
                message = "microcenter.cpu.invalid")
        private String cpu;

        @NotNull
        @Min(value = 4)
        private Integer ram;

        @NotNull
        private Integer nvme;

        @NotNull
        private Integer ssd;

        @NotNull
        private Integer hdd;

        @NotNull
        @Pattern(regexp = "(Intel U?HD [56][23]0)|"
                + "([Nn]vidia Geforce [GR]TX [123][06][5678]0)(| super| Ti)",
                message = "microcenter.gpu.invalid")
        private String gpu;

       ... //构造函数和方法
      }

JSON 请求体:

{
    "name": "asegjbofld;bsgj",
    "cpu": "radhtrhsth",
    "ram": 2,
    "nvme": 512,
    "ssd": 1000,
    "hdd": 2000,
    "gpu": "newga"
}

基于 JSON 请求体中的无效 CPU 和 GPU 输入,应该出现错误,但请求却被处理了?对如何修复有什么想法吗?谢谢。

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.microcenter</groupId>
	<artifactId>MicroCenter</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>MicroCenter</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
    </dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
英文:

I added the correct validation annotations to my DTO and API class, but when I input bad data thru postman, it doesn't error.

API Class

@RestController
@RequestMapping(&quot;/laptops&quot;)
@Validated
public class LaptopApi
{
@Autowired
private LaptopService laptopService;
@Autowired
private Environment environment;
@GetMapping(&quot;/{id}&quot;)
public ResponseEntity&lt;LaptopDTO&gt; getLaptop(@PathVariable Integer id)
{
LaptopDTO laptop = laptopService.getLaptop(id);
return new ResponseEntity&lt;&gt;(laptop, HttpStatus.OK);
}
@GetMapping(&quot;/&quot;)
public ResponseEntity&lt;List&lt;LaptopDTO&gt;&gt; getLaptops()
{
List&lt;LaptopDTO&gt; laptops = laptopService.getLaptops();
return new ResponseEntity&lt;&gt;(laptops, HttpStatus.OK);
}
@PostMapping(&quot;/&quot;)
public ResponseEntity&lt;LaptopDTO&gt; addLaptop(@RequestBody @Valid LaptopDTO laptopDTO)
{
Integer laptopId = laptopService.addLaptop(laptopDTO);
return new ResponseEntity&lt;&gt;(laptopDTO, HttpStatus.OK);
}
@PutMapping(&quot;/&quot;)
public ResponseEntity&lt;LaptopDTO&gt; updateSpecs(@RequestBody @Valid LaptopDTO laptopDTO)
{
laptopService.updateSpecs(laptopDTO);
return new ResponseEntity&lt;&gt;(laptopDTO, HttpStatus.OK);
}
@DeleteMapping(&quot;{id}&quot;)
public ResponseEntity&lt;String&gt; deleteLaptop(@PathVariable Integer id)
{
laptopService.deleteLaptop(id);
return new ResponseEntity&lt;&gt;(environment.getProperty(&quot;API.LAPTOP_DELETE_SUCCESS&quot;)+&quot; &quot;+id,
HttpStatus.OK);
}

DTO Class (I ran the regex checks on a unit test, which works correctly)

public class LaptopDTO
{
private Integer id;
@NotNull
private String name;
@NotNull
@Pattern(regexp = &quot;(Intel core i[3579] [0-9]{4,}[A-Za-z]*)&quot; +
&quot;|(AMD Ryzen [3579] [0-9]{4,}[A-Za-z]*)&quot;,
message = &quot;microcenter.cpu.invalid&quot;)
private String cpu;
@NotNull
@Min(value = 4)
private Integer ram;
@NotNull
private Integer nvme;
@NotNull
private Integer ssd;
@NotNull
private Integer hdd;
@NotNull
@Pattern(regexp = &quot;(Intel U?HD [56][23]0)|&quot; +
&quot;([Nn]vidia Geforce [GR]TX [123][06][5678]0)(| super| Ti)&quot;,
message = &quot;microcenter.gpu.invalid&quot;)
private String gpu;
... //constructors and methods
}

JSON Request Body:

{
&quot;name&quot;: &quot;asegjbofld;bsgj&quot;,
&quot;cpu&quot;: &quot;radhtrhsth&quot;,
&quot;ram&quot;: 2,
&quot;nvme&quot;: 512,
&quot;ssd&quot;: 1000,
&quot;hdd&quot;: 2000,
&quot;gpu&quot;: &quot;newga&quot;
}

Based on the invalid cpu and gpu input from the json request body, it is supposed to error, because of the gpu and cpu, but the request gets processed? Any ideas on how to fix? Thanks.

POM.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;parent&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
&lt;version&gt;2.3.3.RELEASE&lt;/version&gt;
&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
&lt;/parent&gt;
&lt;groupId&gt;com.microcenter&lt;/groupId&gt;
&lt;artifactId&gt;MicroCenter&lt;/artifactId&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;MicroCenter&lt;/name&gt;
&lt;description&gt;Demo project for Spring Boot&lt;/description&gt;
&lt;properties&gt;
&lt;java.version&gt;1.8&lt;/java.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;mysql&lt;/groupId&gt;
&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
&lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.validation&lt;/groupId&gt;
&lt;artifactId&gt;validation-api&lt;/artifactId&gt;
&lt;version&gt;1.1.0.Final&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;/project&gt;

答案1

得分: 9

The spring boot version,

    &lt;parent&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
            &lt;version&gt;2.3.3.RELEASE&lt;/version&gt;
            &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;

doesn't support validator-api,

    &lt;dependency&gt;
         &lt;groupId&gt;javax.validation&lt;/groupId&gt;
         &lt;artifactId&gt;validation-api&lt;/artifactId&gt;
         &lt;version&gt;1.1.0.Final&lt;/version&gt;
    &lt;/dependency&gt;

out of the box. Till Spring boot version 1.4.7, javax.validation had out-of-the-box support.

You need to add the dependency:

    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;
    &lt;/dependency&gt;

This will add the required support.

英文:

The spring boot version,

    &lt;parent&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
            &lt;version&gt;2.3.3.RELEASE&lt;/version&gt;
            &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;

doesn't support validator-api,

    &lt;dependency&gt;
         &lt;groupId&gt;javax.validation&lt;/groupId&gt;
         &lt;artifactId&gt;validation-api&lt;/artifactId&gt;
         &lt;version&gt;1.1.0.Final&lt;/version&gt;
    &lt;/dependency&gt;

out of the box. Till Spring boot version 1.4.7, javax.validation had out-of-the-box support.

You need to add the dependency:

    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;
    &lt;/dependency&gt;

This will add the required support.

huangapple
  • 本文由 发表于 2020年9月3日 14:06:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63717773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定