0

I want to pass one DTO from Interceptor to Controller? How should I proceed? I have tried by define

a) Create one component(which needs to be transferred) b) In Interceptor, get the instance by auto-wiring, set data to auto-wired instance c) Get Auto-wired instance in controller, but this does not seems to work.

I always get the blank object in Controller?

Component

@RequestScope
@Component
public class UserLoginInfoDTO {

    private int userId;
    private String email;
    private String firstName;
    private String lastName;

    .. setters / getters


}

HandleInterceptor

@Component
public class Inter implements HandlerInterceptor {

    @Autowired
    private UserLoginInfoDTO user;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("After completion");
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Post Handle");

    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Pre Handle");
        user.setEmail("anki.vv");
        return true;
    }

}

In Controller, If I get autowired instance and prints it, blank object is getting returned.

I have registered by Handle Interceptor as

@Override
    public void addInterceptors(InterceptorRegistry arg0) {

           ApplicationContext ctx = new AnnotationConfigApplicationContext(Demo.class);
            Inter helloWorld = ctx.getBean(Inter.class);

        arg0.addInterceptor(helloWorld);
        // TODO Auto-generated method stub

    }

Demo is config class

@Configuration
public class Demo {

    @Bean
    public Inter inter() {
        return new Inter();
    }

    @Bean
    public UserLoginInfoDTO uu() {
        return new UserLoginInfoDTO();
    }
}
luboskrnac
  • 23,973
  • 10
  • 81
  • 92
Ankit Bansal
  • 2,162
  • 8
  • 42
  • 79

1 Answers1

0

I would suggest to encapsulate shared DTO into @RequestScrope bean. That seems to me as cleanest way to share request specific data.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92