我有一個從AbstractWebSocketHandler處理文本訊息繼承的網路套接字處理程式。我的 DTOjavax.validation.constraints用于驗證。因此,在我的 REST 端點中,我可以簡單地使用@Valid注釋來呼叫驗證器。但是,據我所知,此注釋在我的 Web 套接字處理程式中不可用。如何在沒有此注釋的情況下以編程方式呼叫 SpringBoot 驗證器?
此外,是否可以將 SpringBoot 反序列化器用于訊息而不是JSON.parseObject?
例子:
import javax.validation.constraints.NotBlank;
import lombok.Data;
@Data
class CustomMessage {
@NotBlank
private String text;
}
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {
@Override
protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
// Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
log.debug("Received valid message {}", customMessage)
}
}
uj5u.com熱心網友回復:
您將使用Validator來填充 的串列ConstraintViolation。一個例子可能是這樣的:
public abstract class GenericService<T> {
protected Validator validator;
protected void validateDomainRecord(T object, String message) {
Set<ConstraintViolation<T>> violations = validator.validate(object);
if(!violations.isEmpty()) {
throw new ConstraintViolationException(message, violations);
}
}
}
在您的情況下,您的代碼將如下所示:
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {
private Validator validator;
@Override
protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
// Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<CustomMessage>> violations = validator.validate(customMessage);
if(!violations.isEmpty()) {
throw new ConstraintViolationException(message, violations);
}
log.debug("Received valid message {}", customMessage)
}
}
看看這個很好的教程了解更多細節。我想也可以自定義您的驗證和您的例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365059.html
標籤:爪哇 春天 弹簧靴 验证 spring-websocket
