Custom converter for @RequestParam in Spring MVC

后端 未结 3 860
攒了一身酷
攒了一身酷 2021-02-07 20:20

I am getting an encrypted String as Query parameter to a Spring rest controller method.

I wanted to decrypt the string before it reaches the method based on some annotat

3条回答
  •  离开以前
    2021-02-07 21:07

    HandlerMethodArgumentResolver would be the best in this regard.

    1. Create your annotation:

    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Decrypt {
        String value();
    }
    
    1. Create your Custom HandlerMethodArgumentResolver:

    public class DecryptResolver implements HandlerMethodArgumentResolver {
    
        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            return parameter.getParameterAnnotation(Decrypt.class) != null;
        }
    
        @Override
        public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                WebDataBinderFactory binderFactory) throws Exception {
            Decrypt attr = parameter.getParameterAnnotation(Decrypt.class);
            String encrypted = webRequest.getParameter(attr.value());
            String decrypted = decrypt(encrypted);
    
            return decrypted;
        }
    
        private String decrypt(String encryptedString) {
            // Your decryption logic here
    
            return "decrypted - "+encryptedString;
        }
    }
    
    1. Register the resolver:

    @Configuration
    @EnableMvc // If you're not using Spring boot
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addArgumentResolvers(List argumentResolvers) {
              argumentResolvers.add(new DecryptResolver());
        }
    }
    
    1. Voila, you have your decrypted parameter. Note that you won't need to use @RequestParam anymore.

    @RequestMapping(value = "/customer", method = RequestMethod.GET)
    public String getAppointmentsForDay(@Decrypt("secret") String customerSecret) {
    System.out.println(customerSecret);  // Needs to be a decrypted value.
       ...
    }
    

提交回复
热议问题