Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the format conversion of time parameters by Springboot+AOP

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

In this article Xiaobian for you to introduce in detail "Springboot+AOP how to achieve time parameter format conversion", the content is detailed, the steps are clear, the details are handled properly, I hope this "Springboot+AOP how to achieve time parameter format conversion" article can help you solve your doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.

Preface scene

The time parameters passed from the front end are converted into custom time formats in our backend, and can be converted to whatever you want.

In different business scenarios, docking with the frontend, the basic time parameters of a control are in a fixed format. In order to prevent the frontend from converting the format of the time parameters, make an agreement with the frontend and let them transmit a fixed format. The back end can use the conversion format according to the requirements.

Effect.

The conversion of ① from yyyy-MM-dd HH:mm:ss to yyyy-MM-dd uses:

The conversion of ② from yyyyMMddHHmmss to yyyy-MM-dd HH:mm:ss uses:

③ no longer gives examples, in fact, he can turn as much as he wants.

Actual combat

Pom.xml (aop dependency, lombok dependency):

Org.springframework.boot spring-boot-starter-web org.projectlombok lombok 1.18.20 compile org.springframework spring-aspects 5.2.7.RELEASE org.aspectj aspectjtools 1. 9.5 aopalliance aopalliance 1.0 org.aspectj aspectjweaver 1.9.0 cglib cglib 3.3.0

Core (Custom comments + interceptor):

Custom Note 1

DateField.java

Purpose: used to mark which field needs time format conversion, configure the old format, the new format (can write default values).

Import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target; / * * @ Author: JCccc * @ Date: 2022-4-11 18:45 * @ Description: * / @ Target ({ElementType.METHOD, ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) public @ interface DateField {String oldPattern () default DateUtil.YYYY_MM_DD_HH_MM_SS / / the new format can be written by default or not. If the business is relatively fixed, then both the new time format and the old time format can be fixed with String newPattern () default ";} Custom Note 2

NeedDateFormatConvert.java

Purpose: it is used to mark which interface needs to be converted in AOP mode.

Import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target; / * * @ Author: JCccc * @ Date: 2022-4-11 18:44 * @ Description: * / @ Target ({ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) public @ interface NeedDateFormatConvert {} interceptor

DateFormatAspect.java

Purpose: core transformation implementation logic.

Import com.jctest.dotestdemo.util.DateUtil;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.util.StringUtils; import java.lang.reflect.Field;import java.util.Objects / * * @ Author: JCccc * @ Date: 2022-4-11 18:57 * @ Description: * / @ Aspect@Componentpublic class DateFormatAspect {private static Logger log = LoggerFactory.getLogger (DateFormatAspect.class); @ Pointcut ("@ annotation (com.jctest.dotestdemo.aop.dateFormat.NeedDateFormatConvert)") public void pointCut () {} @ Around ("pointCut ()") public Object around (ProceedingJoinPoint joinPoint) throws Throwable {/ / convert dateFormat (joinPoint) Return joinPoint.proceed ();} public void dateFormat (ProceedingJoinPoint joinPoint) {Object [] objects = null; try {objects = joinPoint.getArgs (); if (objects.length! = 0) {for (int I = 0; I < objects.length) Currently, only convertObject (objects [I]);} catch (Exception e) {e.printStackTrace (); throw new RuntimeException ("parameter exception") are supported. }} / * the value in the conversion object * * @ param obj * @ throws IllegalAccessException * / private void convertObject (Object obj) throws IllegalAccessException {if (Objects.isNull (obj)) {log.info ("the object to be converted is null"); return } Field [] fields = obj.getClass (). GetDeclaredFields (); for (Field field: fields) {boolean containFormatField = field.isAnnotationPresent (DateField.class); if (containFormatField) {/ / get access field.setAccessible (true); DateField annotation = field.getAnnotation (DateField.class) String oldPattern = annotation.oldPattern (); String newPattern = annotation.newPattern (); Object dateValue = field.get (obj); if (Objects.nonNull (dateValue) & & StringUtils.hasLength (oldPattern) & & StringUtils.hasLength (newPattern)) {String newDateValue = DateUtil.strFormatConvert (String.valueOf (dateValue), oldPattern, newPattern) If (Objects.isNull (newDateValue)) {log.info ("date data conversion failure for current conversion dateValue = {}", dateValue.toString ()); throw new RuntimeException ("parameter conversion exception");} field.set (obj, newDateValue) }} tool class

DateUtil.java

Purpose: time format conversion function, define various time formats.

Import lombok.extern.slf4j.Slf4j;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter; / * * @ Author: JCccc * @ Date: 2022-4-1 14:48 * @ Description: * / @ Slf4jpublic class DateUtil {public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; public static final String YYYY_MM_DD = "yyyy-MM-dd"; public static final String YYYY_MM = "yyyy-MM" Public static final String YYYY = "yyyy"; public static final String MM = "MM"; public static final String DD = "dd"; public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static final String YYYYMMDD = "yyyyMMdd" / * * specified date format conversion * * @ param dateStr * @ param oldPattern * @ return * / public static String strFormatConvert (String dateStr, String oldPattern,String newPattern) {try {DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern (oldPattern); DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern (newPattern); return LocalDateTime.parse (dateStr, oldFormatter) .format (newFormatter) } catch (Exception e) {log.error ("strToDate is Exception. E: ", e); return null;} use

UserQueryVO.java

Import com.jctest.dotestdemo.aop.dateFormat.DateField;import com.jctest.dotestdemo.util.DateUtil;import lombok.Data; import java.io.Serializable; / * * @ Author: JCccc * @ Date: 2022-4-1 14:48 * @ Description: * / @ Datapublic class UserQueryVO implements Serializable {/ * * start time * / @ DateField (oldPattern = DateUtil.YYYY_MM_DD_HH_MM_SS, newPattern = DateUtil.YYYY_MM_DD) private String startDate / * * end time * / @ DateField (oldPattern = DateUtil.YYYY_MM_DD_HH_MM_SS,newPattern = DateUtil.YYYY_MM_DD) private String endDate;} Interface import com.jctest.dotestdemo.aop.dateFormat.NeedDateFormatConvert;import com.jctest.dotestdemo.vo.UserQueryVO;import org.springframework.web.bind.annotation.* / * * @ Author: JCccc * @ Date: 2022-4-18 11:52 * @ Description: * / @ RestControllerpublic class UserController {@ NeedDateFormatConvert @ PostMapping ("/ test") public String test (@ RequestBody UserQueryVO userQueryVO) {System.out.println ("time format conversion completed:"); System.out.println (userQueryVO.getStartDate ()); System.out.println (userQueryVO.getEndDate ()) Return userQueryVO.toString ();}} call

Read this, the "Springboot+AOP how to achieve time parameter format conversion" article has been introduced, want to master the knowledge of this article also need to practice and use in order to understand, if you want to know more related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report