sping interceptor以及获取ip地址等

1. interceptor 顺序
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**/*");
       // 当有多个interceptor时候,可以定义他们之间的顺序。还有Ordered.LOWEST_PRECEDENCE
       //registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**/*").order(Ordered.HIGHEST_PRECEDENCE);
   }
}
2.获取前端传递参数
// 对于rest request请求
//In the preHandle() method you can extract the various PathVariables by running the following code
HttpServletRequest request

Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
String pathVar1 = pathVariables.get("path_variables").toString();


String email = request.getParameter("email");
request.getParameterMap();//returns a map of key-values of the request parameters. 
3.获取请求的ip地址
public class IpUtils {

private static final String[] IP_HEADER_CANDIDATES = {
        "X-Forwarded-For",
        "Proxy-Client-IP",
        "WL-Proxy-Client-IP",
        "HTTP_X_FORWARDED_FOR",
        "HTTP_X_FORWARDED",
        "HTTP_X_CLUSTER_CLIENT_IP",
        "HTTP_CLIENT_IP",
        "HTTP_FORWARDED_FOR",
        "HTTP_FORWARDED",
        "HTTP_VIA",
        "REMOTE_ADDR"};

public static String getClientIpAddressIfServletRequestExist() {

    HttpServletRequest request = ((ServletRequestAttributes)    RequestContextHolder.getRequestAttributes()).getRequest();
    for (String header : IP_HEADER_CANDIDATES) {
        String ipList = request.getHeader(header);
        if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
            String ip = ipList.split(",")[0];
            return ip;
        }
    }

    return request.getRemoteAddr();
 }
 }
4.SimpleDateFormat注意线程安全问题

每一个使用SimpleDateFormat对象进行日期-时间进行format和parse方法的时候就创建一个新的SimpleDateFormat对象,用完就销毁即可!

5. 反射

Java反射操作私有成员变量 Class can not access a member with modifiers “private”

通过反射操作类的私有(private)成员变量时,需要通过field.setAccessible(true)将字段设置为可以访问的。

6.注解

AnnotationTest

public class AnnotationTest {

    @MyMessage(name="a", num = 10, desc = "参数a")
    private int a;

    @MyMessage(name = "test", desc = "测试方法test")
    public void test() {
        System.out.println("test");
    }

    public void setA(int a){
        this.a = a;
    }
}

MyMessage

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyMessage {

    String name() default "sam";

    int num() default 0;

    String desc();
}

MyMessageProcessor

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MyMessageProcessor {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        try {

            //加载annotationTest.class类
            Class clazz = MyMessageProcessor.class.getClassLoader().loadClass("com.xiaohongshu.fls.monkeyking.xh.AnnotationTest");

            //获取属性
            Field[] fields = clazz.getDeclaredFields();
            //遍历属性
            for (Field field : fields) {
                MyMessage myMessage = field.getAnnotation(MyMessage.class);
                System.out.println("name:" + myMessage.name() + "  num:" + myMessage.num() + "  desc:" + myMessage.desc());
                Class c =Class.forName("com.xiaohongshu.fls.monkeyking.xh.AnnotationTest");

                //利用反射获取value
                if(myMessage.name().equals("a")) {
                    AnnotationTest aaaaa = new AnnotationTest();
                    aaaaa.setA(1000);
                    Field field1 = aaaaa.getClass().getDeclaredField("a");
                    field1.setAccessible(true);
                    System.out.println(field1.get(aaaaa));
                }
            }

            //获取类中的方法
            Method[] methods = clazz.getMethods();
            //遍历方法
            for (Method method : methods) {

                //判断方法是否带有MyMessage注解
                if (method.isAnnotationPresent(MyMessage.class)) {
                    // 获取所有注解 method.getDeclaredAnnotations();
                    // 获取MyMessage注解
                    MyMessage myMessage = method.getAnnotation(MyMessage.class);
                    System.out.println("name:" + myMessage.name() + "  num:" + myMessage.num() + "  desc:" + myMessage.desc());
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

参考网址
1.https://www.cnblogs.com/softidea/p/5705297.html
2.https://stackoverflow.com/questions/22877350/how-to-extract-ip-address-in-spring-mvc-controller-get-call
3.https://blog.csdn.net/weixin_38810239/article/details/79941964

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值