Skip to content

Commit

Permalink
🐛 修复当未依赖validation-api具体实现时报错的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
zidoshare committed Mar 25, 2021
1 parent 345985b commit 1e57da7
Show file tree
Hide file tree
Showing 11 changed files with 106 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import site.zido.coffee.mvc.rest.EnableGlobalResult;

@EnableGlobalResult
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnProperty(value = "spring.coffee.web.global-result", matchIfMissing = true, havingValue = "true")
@Import(JavaxExceptionEnablerConfiguration.class)
public class GlobalResultEnablerConfiguration {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package site.zido.coffee.autoconfigure.web;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;

/**
* @author zido
*/
@Configuration
@ConditionalOnClass(name = "javax.validation.ConstraintViolationException")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class JavaxExceptionEnablerConfiguration {
}
1 change: 1 addition & 0 deletions coffee-modules/coffee-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.jcip</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package site.zido.coffee.core.constants;

public class Patterns {
public static final String PHONE_PATTERN = "^1[123456789][\\d]{9}$";
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import static site.zido.coffee.core.constants.Patterns.PHONE_PATTERN;

/**
* @author zido
*/
public class PhoneValidator implements ConstraintValidator<Phone, String> {
private static final String PHONE_PATTERN = "^1[123456789][\\d]{9}";

@Override
public void initialize(Phone constraintAnnotation) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static site.zido.coffee.core.constants.Patterns.PHONE_PATTERN;

/**
* @author zido
*/
Expand All @@ -40,7 +42,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
HttpServletRequest request = (HttpServletRequest) req;
String phone = obtainPhone(request);
if (requireCreateCode(request)) {
if (phone == null || !phoneValidator.isValid(phone, null)) {
if (phone == null || !phone.matches(PHONE_PATTERN)) {
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad phone"));
Expand Down Expand Up @@ -86,7 +88,7 @@ public void setCodeParameter(String codeParameter) {
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String phone = obtainPhone(request);
if (phone == null) {
phone = "";
Expand Down
1 change: 1 addition & 0 deletions coffee-modules/coffee-webmvc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package site.zido.coffee.mvc.exceptions;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import site.zido.coffee.mvc.rest.JavaxValidationExceptionAdvice;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({JavaxValidationExceptionAdvice.class})
@Configuration
public @interface EnableJavaxException {
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,41 +30,14 @@
* @author zido
*/
public abstract class BaseGlobalExceptionHandler extends ResponseEntityExceptionHandler {
private final HttpResponseBodyFactory factory;
private final MessageSourceAccessor messages = CoffeeMessageSource.getAccessor();
protected final HttpResponseBodyFactory factory;
protected final MessageSourceAccessor messages = CoffeeMessageSource.getAccessor();

protected BaseGlobalExceptionHandler(HttpResponseBodyFactory factory) {
Assert.notNull(factory, "http response body factory cannot be null");
this.factory = factory;
}

protected ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e, WebRequest request) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
List<String> errors = new ArrayList<>();
while (iterator.hasNext()) {
ConstraintViolation<?> next = iterator.next();
Path propertyPath = next.getPropertyPath();
String name = "unknown";
//获取参数名
for (Path.Node node : propertyPath) {
name = node.getName();
}
//参数错误提示
String message = "[" + name + "] " + next.getMessage();
errors.add(message);
}
return handleExceptionInternal(
e,
factory.error(CommonErrorCode.VALIDATION_FAILED,
messages.getMessage("ValidationFailed", "Validation Failed"),
errors),
new HttpHeaders(),
HttpStatus.BAD_REQUEST,
request
);
}

@Override
protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,6 @@ public GlobalExceptionAdvice(HttpResponseBodyFactory factory) {
super(factory);
}

/**
* parameter参数校验异常处理
*
* @param e 校验异常
* @return result
*/
@ExceptionHandler(value = ConstraintViolationException.class)
@Override
public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e, WebRequest request) {
return super.handleConstraintViolationException(e, request);
}

@ExceptionHandler(CommonBusinessException.class)
@Override
protected ResponseEntity<Object> handleCommonBusinessException(CommonBusinessException e, WebRequest request, HttpServletResponse response) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package site.zido.coffee.mvc.rest;

import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import site.zido.coffee.mvc.CommonErrorCode;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
@Order
public class JavaxValidationExceptionAdvice extends BaseGlobalExceptionHandler {
public JavaxValidationExceptionAdvice(HttpResponseBodyFactory factory) {
super(factory);
}

/**
* parameter参数校验异常处理
*
* @param e 校验异常
* @return result
*/
@ExceptionHandler(value = ConstraintViolationException.class)
public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e, WebRequest request) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
List<String> errors = new ArrayList<>();
while (iterator.hasNext()) {
ConstraintViolation<?> next = iterator.next();
Path propertyPath = next.getPropertyPath();
String name = "unknown";
//获取参数名
for (Path.Node node : propertyPath) {
name = node.getName();
}
//参数错误提示
String message = "[" + name + "] " + next.getMessage();
errors.add(message);
}
return handleExceptionInternal(
e,
factory.error(CommonErrorCode.VALIDATION_FAILED,
messages.getMessage("ValidationFailed", "Validation Failed"),
errors),
new HttpHeaders(),
HttpStatus.BAD_REQUEST,
request
);
}
}

0 comments on commit 1e57da7

Please sign in to comment.