1、参数校验工具:BeanValidator
package com.wgs.permission.util;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sun.tools.javac.code.Attribute;
import com.wgs.permission.exception.ParamException;
import org.apache.commons.collections.MapUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;
/**
* Created by wanggenshen
* Date: on 2019/7/1 22:38.
* Description: XXX
*/
public class BeanValidator {
private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
public static <T> Map<String, String> validate(T t, Class...groups) {
Validator validator = validatorFactory.getValidator();
Set validateResult = validator.validate(t, groups);
if (validateResult.isEmpty()) {
return Maps.newHashMap();
}
LinkedHashMap errors = Maps.newLinkedHashMap();
Iterator iterator = validateResult.iterator();
while (iterator.hasNext()) {
ConstraintViolation violation = (ConstraintViolation) iterator.next();
errors.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errors;
}
public static Map<String, String> validateList(Collection<?> collection) {
Preconditions.checkNotNull(collection, "collection should not empty");
Iterator iterator = collection.iterator();
Map errors = null;
while(iterator.hasNext()) {
Object object = iterator.next();
errors = validate(object, new Class[0]);
}
return errors;
}
public static Map<String, String> validateObject(Object first, Object...objects) {
if (objects != null && objects.length > 0) {
return validateList(Lists.asList(first, objects));
} else {
return validate(first, new Class[0]);
}
}
public static void check(Object param) {
Map<String, String> map = BeanValidator.validateObject(param);
if (MapUtils.isNotEmpty(map)) {
throw new ParamException(map.toString());
}
}
}
2、jackjson 工具类:
package com.wgs.permission.util;
import org.codehaus.jackson.map.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.TypeReference;
/**
* Created by wanggenshen
* Date: on 2019/7/2 17:54.
* Description: XXX
*/
@Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
// config
objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
}
public static <T> T str2Obj(String str, TypeReference typeReference) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
if (typeReference.getType().equals(String.class)) {
return (T) str;
}
return objectMapper.readValue(str, typeReference);
} catch (Exception e) {
log.error("json convert string to obj error, str:{}", str);
return null;
}
}
/**
* 对象转为字符串
*
* @param obj 源对象
* @param <T> 对象类型未知
* @return
*/
public static <T> String obj2String(T obj) {
if (obj == null) {
return null;
}
try {
if (obj instanceof String) {
return (String) obj;
}
return objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.error("json convert object to string error, obj:{}", obj);
return null;
}
}
}
3、Spring上下文:
package com.wgs.permission.util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Created by wanggenshen
* Date: on 2019/7/2 19:39.
* Description: XXX
*/
@Component("springContextHelper")
public class SpringContextHelper implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
if (clazz == null) {
return null;
}
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String className, Class<T> clazz) {
if (StringUtils.isBlank(className) || clazz == null) {
return null;
}
return applicationContext.getBean(className, clazz);
}
}
4、全局异常处理 SpringExceptionResolver
package com.wgs.permission.common;
import com.wgs.permission.exception.ParamException;
import com.wgs.permission.exception.PermisionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.ParameterExpression;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by wanggenshen
* Date: on 2019/7/1 00:10.
* Description: 全局异常处理
*/
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
String url = httpServletRequest.getRequestURL().toString();
String defaultMsg = "System error";
//.json .apge
// 所有数据以json结尾
if (url.endsWith(".json")) {
if (e instanceof PermisionException || e instanceof ParamException) {
Response response = Response.fail(e.getMessage());
modelAndView = new ModelAndView("jsonView", response.toMap());
} else {
log.error("unknown error, url:{}", url);
Response response = Response.fail(defaultMsg);
modelAndView = new ModelAndView("jsonView", response.toMap());
}
// 所有数据以.page结尾
} else if (url.endsWith(".page")){
Response response = Response.fail(defaultMsg);
modelAndView = new ModelAndView("exception", response.toMap());
} else {
Response response = Response.fail(defaultMsg);
modelAndView = new ModelAndView("jsonView", response.toMap());
}
return modelAndView;
}
}
5、Http interceptor处理:
package com.wgs.permission.interceptor;
import com.wgs.permission.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* Created by wanggenshen
* Date: on 2019/7/2 19:50.
* Description: XXX
*/
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
private static final String START_TIME = "requestStartTime";
private static final String END_TIME = "requestEndTime";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String url = request.getRequestURL().toString();
Map parameteraMap = request.getParameterMap();
log.info("receive request, url:{}, paramters:{}", url, JsonUtil.obj2String(parameteraMap));
long startTime = System.currentTimeMillis();
request.setAttribute(START_TIME, startTime);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
log.info("postHandle...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
Long startTime = (Long) request.getAttribute(START_TIME);
Long endTime = System.currentTimeMillis();
log.info("request completed, cost time:{}", endTime - startTime);
}
}
xml配置:
<mvc:interceptors>
<bean class="com.wgs.permission.interceptor.HttpInterceptor"/>
</mvc:interceptors>