int commit
This commit is contained in:
5
template/common/README.md
Normal file
5
template/common/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
> 本模块存放公共组件
|
||||
``` \-- *.utils(工具类; package)
|
||||
\-- *.enums(公共枚举; package)
|
||||
\-- *.constants(公共常量; package)
|
||||
```
|
||||
12
template/common/pom.xml
Normal file
12
template/common/pom.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>{{ .groupId }}</groupId>
|
||||
<artifactId>{{ .artifactId }}</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<groupId>{{ .groupId }}</groupId>
|
||||
<artifactId>{{ .artifactId }}-common</artifactId>
|
||||
</project>
|
||||
@@ -0,0 +1,2 @@
|
||||
> 本模块存放公共常量
|
||||
``` \-- *Constant.java
|
||||
@@ -0,0 +1,2 @@
|
||||
> 本模块存放公共枚举
|
||||
``` \-- *Enum.java
|
||||
@@ -0,0 +1,57 @@
|
||||
package {{ .package }}.common.redis;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties({RedisPoolProperties.class})
|
||||
@ConditionalOnProperty(name = "redis-config.pool.hostAndPort", havingValue = "true")
|
||||
public class RedisPoolConfig {
|
||||
@Autowired
|
||||
private RedisPoolProperties redisPoolProperties;
|
||||
@Value("${redis-config.pool.password:}")
|
||||
private String password;
|
||||
|
||||
private JedisPoolConfig initPoolConfig() {
|
||||
JedisPoolConfig poolConfig = new JedisPoolConfig();
|
||||
poolConfig.setMaxTotal(redisPoolProperties.getMaxTotal());
|
||||
poolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());
|
||||
poolConfig.setMinIdle(redisPoolProperties.getMinIdle());
|
||||
poolConfig.setNumTestsPerEvictionRun(redisPoolProperties.getNumTestsPerEvictionRun());
|
||||
poolConfig.setTestOnBorrow(redisPoolProperties.isTestOnBorrow());
|
||||
poolConfig.setTestOnReturn(redisPoolProperties.isTestOnReturn());
|
||||
poolConfig.setTestWhileIdle(redisPoolProperties.isTestWhileIdle());
|
||||
poolConfig.setBlockWhenExhausted(redisPoolProperties.isBlockWhenExhausted());
|
||||
poolConfig.setJmxEnabled(redisPoolProperties.isJmxEnabled());
|
||||
poolConfig.setLifo(redisPoolProperties.isLifo());
|
||||
poolConfig.setNumTestsPerEvictionRun(redisPoolProperties.getNumTestsPerEvictionRun());
|
||||
poolConfig.setTestOnBorrow(false);
|
||||
return poolConfig;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* create jedis poll
|
||||
*
|
||||
*/
|
||||
@Bean
|
||||
public JedisPool getRedisPool() {
|
||||
String host = StrUtil.subBefore(redisPoolProperties.getHostAndPort(), ":", false);
|
||||
int port = Integer.parseInt(StrUtil.subAfter(redisPoolProperties.getHostAndPort(), ":", false));
|
||||
if(StrUtil.isNotEmpty(this.password)) {
|
||||
return new JedisPool(initPoolConfig(),host,port ,1000, password);
|
||||
}else{
|
||||
return new JedisPool(initPoolConfig(),host,port);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package {{ .package }}.common.redis;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "redis-config.pool")
|
||||
public class RedisPoolProperties {
|
||||
private String hostAndPort;
|
||||
private int maxTotal;
|
||||
private int maxIdle;
|
||||
private int minIdle;
|
||||
private Long maxWaitMillis;
|
||||
private Long timeBetweenEvictionRunsMillis;
|
||||
private Long minEvictableIdleTimeMillis;
|
||||
private Long softMinEvictableIdleTimeMillis;
|
||||
private boolean testOnBorrow;
|
||||
private boolean testOnReturn;
|
||||
private boolean testWhileIdle;
|
||||
private boolean blockWhenExhausted;
|
||||
private boolean jmxEnabled;
|
||||
private boolean lifo;
|
||||
private int numTestsPerEvictionRun;
|
||||
|
||||
public String getHostAndPort() {
|
||||
return hostAndPort;
|
||||
}
|
||||
|
||||
public void setHostAndPort(String hostAndPort) {
|
||||
this.hostAndPort = hostAndPort;
|
||||
}
|
||||
|
||||
public int getMaxTotal() {
|
||||
return maxTotal;
|
||||
}
|
||||
|
||||
public void setMaxTotal(int maxTotal) {
|
||||
this.maxTotal = maxTotal;
|
||||
}
|
||||
|
||||
public int getMaxIdle() {
|
||||
return maxIdle;
|
||||
}
|
||||
|
||||
public void setMaxIdle(int maxIdle) {
|
||||
this.maxIdle = maxIdle;
|
||||
}
|
||||
|
||||
public int getMinIdle() {
|
||||
return minIdle;
|
||||
}
|
||||
|
||||
public void setMinIdle(int minIdle) {
|
||||
this.minIdle = minIdle;
|
||||
}
|
||||
|
||||
public Long getMaxWaitMillis() {
|
||||
return maxWaitMillis;
|
||||
}
|
||||
|
||||
public void setMaxWaitMillis(Long maxWaitMillis) {
|
||||
this.maxWaitMillis = maxWaitMillis;
|
||||
}
|
||||
|
||||
public Long getTimeBetweenEvictionRunsMillis() {
|
||||
return timeBetweenEvictionRunsMillis;
|
||||
}
|
||||
|
||||
public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) {
|
||||
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
|
||||
}
|
||||
|
||||
public Long getMinEvictableIdleTimeMillis() {
|
||||
return minEvictableIdleTimeMillis;
|
||||
}
|
||||
|
||||
public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
|
||||
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
|
||||
}
|
||||
|
||||
public Long getSoftMinEvictableIdleTimeMillis() {
|
||||
return softMinEvictableIdleTimeMillis;
|
||||
}
|
||||
|
||||
public void setSoftMinEvictableIdleTimeMillis(Long softMinEvictableIdleTimeMillis) {
|
||||
this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
|
||||
}
|
||||
|
||||
public boolean isTestOnBorrow() {
|
||||
return testOnBorrow;
|
||||
}
|
||||
|
||||
public void setTestOnBorrow(boolean testOnBorrow) {
|
||||
this.testOnBorrow = testOnBorrow;
|
||||
}
|
||||
|
||||
public boolean isTestOnReturn() {
|
||||
return testOnReturn;
|
||||
}
|
||||
|
||||
public void setTestOnReturn(boolean testOnReturn) {
|
||||
this.testOnReturn = testOnReturn;
|
||||
}
|
||||
|
||||
public boolean isTestWhileIdle() {
|
||||
return testWhileIdle;
|
||||
}
|
||||
|
||||
public void setTestWhileIdle(boolean testWhileIdle) {
|
||||
this.testWhileIdle = testWhileIdle;
|
||||
}
|
||||
|
||||
public boolean isBlockWhenExhausted() {
|
||||
return blockWhenExhausted;
|
||||
}
|
||||
|
||||
public void setBlockWhenExhausted(boolean blockWhenExhausted) {
|
||||
this.blockWhenExhausted = blockWhenExhausted;
|
||||
}
|
||||
|
||||
public boolean isJmxEnabled() {
|
||||
return jmxEnabled;
|
||||
}
|
||||
|
||||
public void setJmxEnabled(boolean jmxEnabled) {
|
||||
this.jmxEnabled = jmxEnabled;
|
||||
}
|
||||
|
||||
public boolean isLifo() {
|
||||
return lifo;
|
||||
}
|
||||
|
||||
public void setLifo(boolean lifo) {
|
||||
this.lifo = lifo;
|
||||
}
|
||||
|
||||
public int getNumTestsPerEvictionRun() {
|
||||
return numTestsPerEvictionRun;
|
||||
}
|
||||
|
||||
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
|
||||
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package {{ .package }}.common.response;
|
||||
|
||||
import java.text.*;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class MyDateFormat extends DateFormat {
|
||||
private static final long serialVersionUID = -4580955831439573829L;
|
||||
private static final String customDateFormat = "yyyy-MM-dd HH:mm:ss";
|
||||
private DateFormat dateFormat;
|
||||
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
public MyDateFormat(DateFormat dateFormat) {
|
||||
this.calendar = Calendar.getInstance();
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
|
||||
return this.dateFormat.format(date, toAppendTo, fieldPosition);
|
||||
}
|
||||
|
||||
public Date parse(String source, ParsePosition pos) {
|
||||
Date date = null;
|
||||
if (source.length() == "yyyy-MM-dd HH:mm:ss".length()) {
|
||||
date = this.simpleDateFormat.parse(source, pos);
|
||||
} else {
|
||||
date = this.dateFormat.parse(source, pos);
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
public Date parse(String source) throws ParseException {
|
||||
Date date = null;
|
||||
if (source.length() == "yyyy-MM-dd HH:mm:ss".length()) {
|
||||
date = this.simpleDateFormat.parse(source);
|
||||
} else {
|
||||
date = this.dateFormat.parse(source);
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
public Object clone() {
|
||||
Object format = this.dateFormat.clone();
|
||||
return new MyDateFormat((DateFormat)format);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package {{ .package }}.common.response;
|
||||
|
||||
import com.vs.common.util.rpc.pub.FailData;
|
||||
import com.vs.ox.common.exception.ErrorCode;
|
||||
import com.vs.ox.common.exception.IgnoredException;
|
||||
import com.vs.ox.common.utils.ObjectMapperFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.http.server.ServletServerHttpResponse;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import javax.validation.Path;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
public class ResponseJsonExceptionResolver extends AbstractHandlerExceptionResolver implements InitializingBean {
|
||||
private HttpMessageConverter messageConverter;
|
||||
|
||||
public ResponseJsonExceptionResolver() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
if (messageConverter == null) {
|
||||
messageConverter = new MappingJackson2HttpMessageConverter(ObjectMapperFactory.getDefaultObjectMapper());
|
||||
}
|
||||
}
|
||||
|
||||
public static String getErrorInfoFromException(Exception e) {
|
||||
try {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
e.printStackTrace(pw);
|
||||
return "\r\n" + sw.toString() + "\r\n";
|
||||
} catch (Exception e2) {
|
||||
return "bad getErrorInfoFromException";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
|
||||
/**
|
||||
* web请求分页单独处理,应对antd框架
|
||||
*/
|
||||
FailData failData = new FailData();
|
||||
failData.setMessage(ex.getMessage());
|
||||
if (ex instanceof IgnoredException) {
|
||||
IgnoredException realEx = (IgnoredException) ex;
|
||||
failData.setCode(realEx.getErrorCode());
|
||||
failData.setData(realEx.getData());
|
||||
log.error("execute {} failed with exception", request.getRequestURL(), ex);
|
||||
} else if (ex instanceof ConstraintViolationException) {
|
||||
failData.setCode(ErrorCode.WRONG_PARAMETER);
|
||||
failData.setMessage(getMessage((ConstraintViolationException) ex));
|
||||
} else if (ex instanceof ErrorCode) {
|
||||
failData.setCode(((ErrorCode) ex).getErrorCode());
|
||||
} else {
|
||||
log.error("execute {} failed with exception", request.getRequestURL(), ex);
|
||||
}
|
||||
try {
|
||||
response.setCharacterEncoding("utf-8");
|
||||
messageConverter.write(failData, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
|
||||
} catch (IOException e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
return new ModelAndView();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
|
||||
public static String getMessage(ConstraintViolationException e) {
|
||||
List<String> msgList = new ArrayList<>();
|
||||
for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
|
||||
int i = 0;
|
||||
StringBuilder param = new StringBuilder();
|
||||
for (Iterator<Path.Node> iterator = constraintViolation.getPropertyPath().iterator(); iterator.hasNext(); i++) {
|
||||
Path.Node node = iterator.next();
|
||||
if (i == 0) {
|
||||
continue;
|
||||
}
|
||||
if (!param.toString().isBlank()) {
|
||||
param.append(".");
|
||||
}
|
||||
param.append(node.getName());
|
||||
}
|
||||
msgList.add("参数 [ " + param + " ] " + constraintViolation.getMessage());
|
||||
}
|
||||
return StringUtils.join(msgList.toArray(), ";");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package {{ .package }}.common.response;
|
||||
|
||||
import com.vs.common.util.rpc.pub.SuccessData;
|
||||
import com.vs.ox.common.utils.ObjectMapperFactory;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.http.server.ServletServerHttpResponse;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Collections;
|
||||
|
||||
/**
|
||||
* 处理 Controller 里的返回值,从 Object转为Json
|
||||
*/
|
||||
public class ResponseJsonMethodReturnValueHandler implements HandlerMethodReturnValueHandler, InitializingBean {
|
||||
private HttpMessageConverter messageConverter;
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
if (messageConverter == null) {
|
||||
messageConverter = new MappingJackson2HttpMessageConverter(ObjectMapperFactory.getDefaultObjectMapper());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsReturnType(MethodParameter returnType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
|
||||
mavContainer.setRequestHandled(true);
|
||||
Object result = returnValue;
|
||||
/**
|
||||
* Web分页请求的返回按照antd框架要求的格式,不转为SuccessData
|
||||
*/
|
||||
result = result == null ? new SuccessData(Collections.emptyMap()) : new SuccessData(returnValue);
|
||||
ServletServerHttpResponse response = new ServletServerHttpResponse(webRequest.getNativeResponse(HttpServletResponse.class));
|
||||
messageConverter.write(result, new MediaType(MediaType.APPLICATION_JSON, Collections.singletonMap("charset", "utf-8")), response);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package {{ .package }}.common.response;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.method.annotation.MapMethodProcessor;
|
||||
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ViewNameMethodReturnValueHandler;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
import java.text.DateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.vs.ox")
|
||||
public class
|
||||
WebMvcConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware {
|
||||
RequestMappingHandlerAdapter requestMappingHandlerAdapter;
|
||||
ApplicationContext applicationContext;
|
||||
|
||||
void init() {
|
||||
List<HandlerMethodReturnValueHandler> returnValueHandlers = this.requestMappingHandlerAdapter.getReturnValueHandlers();
|
||||
Iterator<HandlerMethodReturnValueHandler> iterator = returnValueHandlers.iterator();
|
||||
List<HandlerMethodReturnValueHandler> newProcessors = new ArrayList<>();
|
||||
while (iterator.hasNext()) {
|
||||
HandlerMethodReturnValueHandler next = iterator.next();
|
||||
//为了能在controller中直接返回map,不被默认的MapMethodProcessor拦截
|
||||
if (next instanceof MapMethodProcessor ||
|
||||
//为了能在controller中直接返回String,不被默认的ViewNameMethodReturnValueHandler拦截
|
||||
next instanceof ViewNameMethodReturnValueHandler) {
|
||||
continue;
|
||||
} else {
|
||||
newProcessors.add(next);
|
||||
}
|
||||
}
|
||||
this.requestMappingHandlerAdapter.setReturnValueHandlers(newProcessors);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
|
||||
ResponseJsonExceptionResolver responseJsonExceptionResolver = new ResponseJsonExceptionResolver();
|
||||
try {
|
||||
responseJsonExceptionResolver.afterPropertiesSet();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
exceptionResolvers.add(responseJsonExceptionResolver);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
|
||||
ResponseJsonMethodReturnValueHandler responseJsonMethodReturnValueHandler = new ResponseJsonMethodReturnValueHandler();
|
||||
responseJsonMethodReturnValueHandler.afterPropertiesSet();
|
||||
returnValueHandlers.add(responseJsonMethodReturnValueHandler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;
|
||||
|
||||
@Bean
|
||||
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
|
||||
ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
|
||||
DateFormat dateFormat = mapper.getDateFormat();
|
||||
mapper.setDateFormat(new MyDateFormat(dateFormat));
|
||||
MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(mapper);
|
||||
return mappingJsonpHttpMessageConverter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
ServletContextListener listener1() {
|
||||
return new ServletContextListener() {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
requestMappingHandlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
|
||||
init();
|
||||
ServletContextListener.super.contextInitialized(sce);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
ServletContextListener.super.contextDestroyed(sce);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package {{ .package }}.common.utils;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JavaType;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import com.vs.ox.common.utils.ObjectMapperFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
|
||||
public class JsonUtils {
|
||||
|
||||
private static final ObjectMapper objectMapper = ObjectMapperFactory.getDefaultObjectMapper();
|
||||
|
||||
static {
|
||||
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
|
||||
}
|
||||
|
||||
public static ObjectMapper getObjectMapper() {
|
||||
return objectMapper;
|
||||
}
|
||||
|
||||
public static String toJson(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("to Json error", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T readObject(String json, TypeReference<T> typeReference) {
|
||||
return readObject(json, objectMapper.getTypeFactory().constructType(typeReference));
|
||||
}
|
||||
|
||||
public static <T> T readObject(String json, Class<T> clazz) {
|
||||
return readObject(json, objectMapper.getTypeFactory().constructType(clazz));
|
||||
}
|
||||
|
||||
public static <T> T readObject(byte[] json, Class<T> clazz) {
|
||||
try {
|
||||
return objectMapper.readValue(json, clazz);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("read Json error", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T readObject(String json, JavaType javaType) {
|
||||
if (isBlank(json)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, javaType);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("read Json error", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonNode path(String json, String path) {
|
||||
if (isBlank(json)) {
|
||||
return MissingNode.getInstance();
|
||||
}
|
||||
try {
|
||||
String atPath = path;
|
||||
if (!path.startsWith("/")) {
|
||||
atPath = "/" + path;
|
||||
}
|
||||
return objectMapper.readTree(json).at(atPath);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("read Json error", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String str) {
|
||||
int strLen;
|
||||
if (str == null || (strLen = str.length()) == 0) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
if ((!Character.isWhitespace(str.charAt(i)))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static <T> Optional<T> readPath(String json, String path, TypeReference<T> typeReference) {
|
||||
return readPath(json, path, objectMapper.getTypeFactory().constructType(typeReference));
|
||||
}
|
||||
|
||||
public static <T> Optional<T> readPath(String json, String path, Class<T> clazz) {
|
||||
JsonNode jsonNode = path(json, path);
|
||||
if (jsonNode.isMissingNode()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
return Optional.of(objectMapper.treeToValue(jsonNode, clazz));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> Optional<T> readPath(String json, String path, JavaType javaType) {
|
||||
JsonNode jsonNode = path(json, path);
|
||||
if (jsonNode.isMissingNode()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(objectMapper.convertValue(jsonNode, javaType));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
> 本模块存放公共工具类
|
||||
``` \-- *Util.java
|
||||
```
|
||||
Reference in New Issue
Block a user