SpringSecurity短信验证码及图片验证码代码优化

1、优化思路

上节将到的短信验证码,图片验证码整个思路基本一样,代码也差不多,这节我们对相同的代码进行抽取处理,整个思路如下:
SpringSecurity短信验证码及图片验证码代码优化_第1张图片

ValidateCodeController 来接收验证码请求,通过参数type来区分,ValidateCodeProcessor 用来处理(交给子类),AbstractValidateCodeProcessor抽象类主要把生成验证码的通用步骤抽取出来,1.生成验证码 2.保存验证码,3发送验证码;
1.生成验证码教给ValidateCodeGenerator 的子类来实现;
2.保存验证码,都一样直接AbstractValidateCodeProcessor中实现
3.发送验证码AbstractValidateCodeProcessor的子类来实现

2.代码

ValidateCodeController
SpringSecurity短信验证码及图片验证码代码优化_第2张图片

ValidateCodeProcessorHolder

SpringSecurity短信验证码及图片验证码代码优化_第3张图片

ValidateCodeProcessor

SpringSecurity短信验证码及图片验证码代码优化_第4张图片
AbstractValidateCodeProcessor

public abstract class AbstractValidateCodeProcessor implements ValidateCodeProcessor{


   public final static String SESSION_KEY = "SESSION_KEY_FOR_CODE_";

    @Autowired
    private Map codeGenerator;


    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    public void create(ServletWebRequest request) throws Exception {
        //1.生成验证码
        T code = generator(request);

        //2.保存验证码
        save(request,code);

        //3.发送验证码

        send(request,code);

    }

    public abstract void send(ServletWebRequest request,T code) throws Exception;


    private void save(ServletWebRequest request,T code) {
        sessionStrategy.setAttribute(request,getSessionKey(request),code);
    }

    public String getSessionKey(ServletWebRequest request) {
        String type = getValidateCodeType(request).toString().toUpperCase();
        return SESSION_KEY + type;
    }

    private  T generator(ServletWebRequest request){
        ValidateCodeType validateCodeType = getValidateCodeType(request);
        String typeName = validateCodeType.toString().toLowerCase();
        String generatorName = typeName + "CodeGenerator";
        ValidateCodeGenerator generator = codeGenerator.get(generatorName);
        ValidateCode code = generator.createCode();
        return (T)code;
    };


    private ValidateCodeType getValidateCodeType(ServletWebRequest request){

        String type = StringUtils.substringBefore(this.getClass().getSimpleName(), "CodeProcessor");
        ValidateCodeType validateCodeType = ValidateCodeType.valueOf(type.toUpperCase());
        return validateCodeType;
    }


}

ImageCodeProcessor

SpringSecurity短信验证码及图片验证码代码优化_第5张图片

SmsCodeProcessor

SpringSecurity短信验证码及图片验证码代码优化_第6张图片

你可能感兴趣的:(springSecutiry)