Commit c29b9e57 authored by zhangc's avatar zhangc

添加全局日志切面方面

parent 2e7d4735
......@@ -96,6 +96,16 @@
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier><!-- jdk版本 -->
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.jz.dm.controller;
import com.jz.common.utils.Result;
import com.jz.dm.models.req.LogInfoDetailReq;
import com.jz.dm.models.req.LogInfoListReq;
import com.jz.dm.service.ApiLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import javax.validation.Valid;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.controller
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiLogController
* @DATE: 2020-12-25/14:25
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@RestController
@RequestMapping("api/logging")
@Api(tags = "授权认证Controller")
public class ApiLogController {
@Autowired
private ApiLogService apiLogService;
/**
* @Description:日志信息查询
* @return: 日志列表
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("日志列表查询")
@PostMapping(value = "/listApiLog")
public Mono<Result> getApiLogList(@RequestBody @Valid LogInfoListReq req) {
return Mono.fromSupplier(() -> Result.of_success(apiLogService.listApiLog(req)));
}
/**
* @Description:日志详情查询
* @return: 日志详情查询
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("日志详情查询")
@PostMapping(value = "/getReqDetail")
public Mono<Result> getApiLogDetail(@RequestBody @Valid LogInfoDetailReq req) {
return Mono.fromSupplier(() -> apiLogService.getApiLogDetail(req));
}
}
......@@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
* @Description: 授权controller
**/
@RestController
@RequestMapping("auth")
@RequestMapping("api/auth")
@Api(tags = "授权认证Controller")
public class AuthController {
......
......@@ -23,7 +23,7 @@ import java.util.Map;
* 网关请求
* @author zc
*/
@RestController
@RestController("/api")
public class GatewayController {
@Autowired
......
......@@ -9,10 +9,7 @@ import com.jz.dm.service.OrganizationManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import javax.validation.Valid;
......@@ -27,7 +24,7 @@ import javax.validation.Valid;
* @Description: 组织管理controller
**/
@RestController
@RequestMapping("organization")
@RequestMapping("api/organization")
@Api(tags = "组织管理Controller")
public class OrganizationManageController {
......@@ -76,4 +73,14 @@ public class OrganizationManageController {
public Mono<Result> update(@RequestBody @Valid OrganizationManageUpdateReq req) {
return Mono.fromSupplier(() -> organizationManageService.update(req));
}
/**
* @Description:删除组织
* @Author: Mr.zhang
* @Date: 2020-12-24
*/
@ApiOperation("删除组织")
@GetMapping(value = "/deleted")
public Mono<Result> delete(@RequestParam(name = "id")Long id) {
return Mono.fromSupplier(() -> organizationManageService.delete(id));
}
}
......@@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
* @Description:
**/
@RestController
@RequestMapping("producer")
@RequestMapping("api/producer")
@Api(tags = "Api制作Controller")
public class ProducerController {
......
......@@ -22,7 +22,7 @@ public class CheckArgsFilter extends AbstractFilter {
@Override
public int getOrder() {
return Constants.FILTER_ORDER_2;
return Constants.FILTER_ORDER_3;
}
@Override
......
......@@ -23,7 +23,7 @@ public class CheckTimestampFilter extends AbstractFilter {
@Override
public int getOrder() {
return Constants.FILTER_ORDER_3;
return Constants.FILTER_ORDER_4;
}
@Override
......
......@@ -18,7 +18,7 @@ public class VerifySignFilter extends AbstractFilter {
@Override
public int getOrder() {
return Constants.FILTER_ORDER_4;
return Constants.FILTER_ORDER_2;
}
@Override
......
......@@ -61,12 +61,6 @@ public class ApiReqLog extends BaseObject implements Serializable {
@TableField("request_method")
private String requestMethod;
/**
* 请求类型(方式)
*/
@TableField("request_type")
private String requestType;
/**
* 加密方式:MD5,RSA
*/
......
package com.jz.dm.models.req;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.req
* @PROJECT_NAME: jz-dm-parent
* @NAME: LogInfoDetailReq
* @DATE: 2020-12-25/15:18
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Data
@ApiModel("日志详情信息")
public class LogInfoDetailReq implements Serializable {
@ApiModelProperty(value = "id",required = true)
@NotNull(message = "id不能为空")
private Long id;
}
package com.jz.dm.models.req;
import com.jz.common.bean.BasePageBean;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.io.Serializable;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.models.req
* @PROJECT_NAME: jz-dm-parent
* @NAME: LogInfoListReq
* @DATE: 2020-12-25/14:59
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Data
@ApiModel("日志信息列表")
public class LogInfoListReq extends BasePageBean implements Serializable {
}
package com.jz.dm.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jz.common.utils.Result;
import com.jz.dm.models.domian.ApiReqLog;
import com.jz.dm.models.req.LogInfoDetailReq;
import com.jz.dm.models.req.LogInfoListReq;
import net.sf.json.JSONObject;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.service
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiLogService
* @DATE: 2020-12-25/14:29
* @DAY_NAME_SHORT: 周五
* @Description:
**/
public interface ApiLogService {
/**
* 查询日志列表
* @param req
* @return
*/
IPage<ApiReqLog> listApiLog(LogInfoListReq req);
/**
* 获取日志详情信息
* @param req
* @return
*/
Result getApiLogDetail(LogInfoDetailReq req);
/**
* 保存日志信息
* @param reqLog
*/
void insetLogInfo(ApiReqLog reqLog);
/**
* 根据id更新日志
* @param id
* @param jsonObject
*/
void updateLog(Long id, JSONObject jsonObject);
}
......@@ -45,4 +45,11 @@ public interface OrganizationManageService {
* @return
*/
Result update(OrganizationManageUpdateReq req);
/**
* 根据id删除组织
* @param id
* @return
*/
Result delete(Long id);
}
package com.jz.dm.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jz.common.utils.Result;
import com.jz.dm.mapper.ApiReqLogMapper;
import com.jz.dm.models.domian.ApiReqLog;
import com.jz.dm.models.req.LogInfoDetailReq;
import com.jz.dm.models.req.LogInfoListReq;
import com.jz.dm.service.ApiLogService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.service.impl
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiLogServiceImpl
* @DATE: 2020-12-25/14:29
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Service("apiLogService")
@Slf4j
public class ApiLogServiceImpl implements ApiLogService {
@Resource
private ApiReqLogMapper apiReqLogMapper;
/**
* 日志信息列表
* @param req
* @return
*/
@Override
public IPage<ApiReqLog> listApiLog(LogInfoListReq req) {
IPage<ApiReqLog> page = new Page<>(req.getPageNum(), req.getPageSize());
QueryWrapper<ApiReqLog> query = new QueryWrapper<>();
query.orderByDesc("create_date");
return apiReqLogMapper.selectPage(page, query);
}
/**
* 查询日志详情
* @param req
* @return
*/
@Override
public Result getApiLogDetail(LogInfoDetailReq req) {
return Result.of_success(apiReqLogMapper.selectById(req.getId()));
}
/**
* 保存日志
* @param reqLog
*/
@Override
public void insetLogInfo(ApiReqLog reqLog) {
apiReqLogMapper.insert(reqLog);
}
/**
* 根据id更新日志
* @param id
* @param jsonObject
*/
@Override
public void updateLog(Long id, JSONObject jsonObject) {
ApiReqLog apiReqLog = apiReqLogMapper.selectById(id);
if (null != apiReqLog){
ApiReqLog reqLog = new ApiReqLog();
reqLog.setId(id);
reqLog.setResponseParams(jsonObject.toString());
reqLog.setUpdateDate(new Date());
apiReqLogMapper.updateById(reqLog);
}else {
log.info("id为:{}",id+"-----------------日志信息不存在");
}
}
}
......@@ -12,6 +12,8 @@ import com.jz.dm.models.req.OrganizationManageDetailQueryReq;
import com.jz.dm.models.req.OrganizationManageListQueryReq;
import com.jz.dm.models.req.OrganizationManageUpdateReq;
import com.jz.dm.service.OrganizationManageService;
import com.jz.dm.web.annotation.ApiBeforeLog;
import com.jz.dm.web.annotation.ApiReturnLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
......@@ -57,6 +59,8 @@ public class OrganizationManageImpl implements OrganizationManageService {
* @return
*/
@Override
@ApiBeforeLog
@ApiReturnLog
public Result getOrganizationDetail(OrganizationManageDetailQueryReq req) {
return Result.of_success(apiOrgMapper.selectById(req.getId()));
}
......@@ -121,6 +125,23 @@ public class OrganizationManageImpl implements OrganizationManageService {
return Result.of_success(ResultMsg.UPDATE_FAIL);
}
/**
* 删除组织
* @param id
* @return
*/
@Override
public Result delete(Long id) {
ApiOrg apiOrg = apiOrgMapper.selectById(id);
if (null == apiOrg){
return Result.of_error(ResultMsg.DATA_NOT_EXIST);
}
if (apiOrgMapper.deleteById(id) >0){
return Result.of_success(ResultMsg.DELETE_SUCCESS);
}
return Result.of_success(ResultMsg.DELETE_FAIL);
}
/**
* 根据名称获取组织信息
* @param orgName 组织名称
......
package com.jz.dm.web.annotation;
import java.lang.annotation.*;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.web.annotation
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiBeforeLog
* @DATE: 2020-12-25/15:50
* @DAY_NAME_SHORT: 周五
* @Description: api全局切面日志
**/
@Target({ElementType.PARAMETER, ElementType.METHOD})//作用在参数和方法上
@Retention(RetentionPolicy.RUNTIME)//运行时注解
@Documented//表明这个注解应该被 javadoc工具记录
public @interface ApiBeforeLog {
String description() default "";
}
package com.jz.dm.web.annotation;
import java.lang.annotation.*;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.web.annotation
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiReturnLog
* @DATE: 2020-12-25/17:43
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Target({ElementType.PARAMETER, ElementType.METHOD})//作用在参数和方法上
@Retention(RetentionPolicy.RUNTIME)//运行时注解
@Documented//表明这个注解应该被 javadoc工具记录
public @interface ApiReturnLog {
String description() default "";
}
package com.jz.dm.web.aspect;
import com.jz.common.utils.IpUtils;
import com.jz.common.utils.JsonUtils;
import com.jz.common.utils.UrlUtil;
import com.jz.dm.common.util.SignType;
import com.jz.dm.models.domian.ApiReqLog;
import com.jz.dm.service.ApiLogService;
import com.jz.dm.web.annotation.ApiBeforeLog;
import com.jz.dm.web.annotation.ApiReturnLog;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.web.aspect
* @PROJECT_NAME: jz-dm-parent
* @NAME: SystemLogAspect
* @DATE: 2020-12-25/16:03
* @DAY_NAME_SHORT: 周五
* @Description:
**/
@Aspect
@Component
@SuppressWarnings({"unchecked", "unused", "rawtypes"})
@Slf4j
public class SystemLogAspect {
@Resource
private ApiLogService apiLogService;
//Service层切点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiBeforeLog)")
public void serviceAspect() {
}
//Controller层切点
@Pointcut("@annotation(com.jz.dm.web.annotation.ApiReturnLog)")
public void controllerAspect(){
}
@Before("serviceAspect()")
public void doBefore(JoinPoint joinPoint) {
//日志信息收集切面
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = IpUtils.getIpAddr(request);
//获取用户请求方法的参数并序列化为JSON格式字符串
String params ="";
if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
for (int i = 0; i < joinPoint.getArgs().length; i++) {
params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
}
}
//获取请求路径
String url = UrlUtil.getServerUrl(request);
// 访问项目名
String contextPath = request.getContextPath();
//JSONObject jsonObject = JSONObject.parseObject(params);
//String param = jsonObject.getString("params");
//JSONObject object = JSONObject.parseObject(param);
//String token = object.getString("token");
try {
log.info("~~~~~~~~~~~~~~~~~~~~~~~前置通知记录请求信息~~~~~~~~~~~~~~~~");
ApiReqLog reqLog = new ApiReqLog();
reqLog.setRequestIp(ip);
// reqLog.setApiKey(jsonObject.getString("apiKey"));
// reqLog.setRequestParams(params);
reqLog.setResponseParams("");//响应参数
reqLog.setRequestUrl(url);
reqLog.setRequestMethod(contextPath);
reqLog.setEncryMode(SignType.MD5.name()); //加密方式:MD5,RSA
reqLog.setTransMode(request.getMethod());//传输方式 GET POST
// reqLog.setRequestToken(token);
reqLog.setRequestTime(new Date());
reqLog.setRemark(getServiceMethodDescription(joinPoint));
System.out.println(reqLog);
//if (null != reqLog){
// // apiLogService.insetLogInfo(reqLog);
// //}
} catch(Exception e) {
log.error("~~~~~~~~~~~~~~~~~~~~~~~前置通知异常~~~~~~~~~~~~~~~~~~~~~~~");
log.error("异常信息{}",e.getMessage());
}
}
/**返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常
可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码
*/
@AfterReturning(value = "controllerAspect()",returning = "result")
public void afterReturn(JoinPoint joinPoint,Object result){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
log.info("~~~~~~~~~~~~~~~~~~~~~~最终通知执行~~~~~~~~~~~~~~~~~~~~~~~~");
String classType = joinPoint.getTarget().getClass().getName();
try {
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
// 拦截的方法名称。当前正在执行的方法
String methodName = joinPoint.getSignature().getName();
// 获取方法的参数
Object[] args = joinPoint.getArgs();
// 获取传入参数的键值对
Map<String, Object> map = (Map<String, Object>)
getFieldsName(this.getClass(), clazzName, methodName,
args);
// 将request中的参数转化为键值对,方便取出
// Map<String, Object> requestMap = (Map<String, Object>) map.get("request");
// 获取返回方法的参数
JSONObject jsonObject = JSONObject.fromObject(result);
Map mapResult = (Map) jsonObject;
//将返回的result参数取出
Map<String, Object> res = (Map<String, Object>) mapResult.get("data");
Long id = (Long)res.get("id");
apiLogService.updateLog(id,jsonObject);
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于service层注解
* @param joinPoint
* @return
* @throws Exception
*/
public static String getServiceMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(ApiBeforeLog.class).description();
break;
}
}
}
return description;
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
* @param joinPoint
* @return
* @throws Exception
*/
public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();//目标方法名
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method:methods) {
if (method.getName().equals(methodName)){
Class[] clazzs = method.getParameterTypes();
if (clazzs.length==arguments.length){
description = method.getAnnotation(ApiReturnLog.class).description();
break;
}
}
}
return description;
}
public static Map<String, Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args)throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
// exception
}
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < cm.getParameterTypes().length; i++) {
map.put(attr.variableName(i + pos), args[i]);// paramNames即参数名
}
return map;
}
}
......@@ -68,4 +68,8 @@ spring:
# - 192.168.31.167:6384
#使用redis管理session设置为redis,否则none
session:
store-type: none
\ No newline at end of file
store-type: none
#切面启用
aop:
proxy-target-class: true
auto: true
\ No newline at end of file
......@@ -80,18 +80,5 @@
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!--阿里云服务器短信平台-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.jz.common.utils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.common.utils
* @PROJECT_NAME: jz-dm-parent
* @NAME: IpUtils
* @DATE: 2020-12-25/16:53
* @DAY_NAME_SHORT: 周五
* @Description:
**/
public class IpUtils {
/**
* 获取当前网络ip
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
/**
* 获得MAC地址
* @param ip
* @return
*/
public static String getMACAddress(String ip){
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
break;
}
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
return macAddress;
}
}
package com.jz.common.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.common.utils
* @PROJECT_NAME: jz-dm-parent
* @NAME: JsonUtils
* @DATE: 2020-12-25/16:57
* @DAY_NAME_SHORT: 周五
* @Description:
**/
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param beanType 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.jz.common.utils;
import javax.servlet.http.HttpServletRequest;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.common.utils
* @PROJECT_NAME: jz-dm-parent
* @NAME: UrlUtil
* @DATE: 2020-12-25/17:03
* @DAY_NAME_SHORT: 周五
* @Description:
**/
public class UrlUtil {
/**
* 获取当前访问URL (含协议、域名、端口号[忽略80端口]、项目名)
* @param request
* @return: String
*/
public static String getServerUrl(HttpServletRequest request) {
// 访问协议
String agreement = request.getScheme();
// 访问域名
String serverName = request.getServerName();
// 访问端口号
int port = request.getServerPort();
// 访问项目名
String contextPath = request.getContextPath();
String url = "%s://%s%s%s";
String portStr = "";
if (port != 80) {
portStr += ":" + port;
}
return String.format(url, agreement, serverName, portStr, contextPath);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment