2

I want to inject the Servlet Context to the Validator placed in the Entity. But null is returned...

Example:

@Entity
class Test{
@TestValidator()
int something;
}

TestValidator implements ConstraintValidator{
@Context ServletContext ctx
}

The scenario is that the action is from the facelet. Then the managed bean's action is invoked based on the user's action. I want to pass the ServletContext of that action to the Validator annotated in the Entity class but null is return.. I thought that Servlet Context is application scoped.

Question: Is there a way to access that Servlet Context in the validator?

Thanks!

ton
  • 355
  • 3
  • 13
  • 1
    I created a class named ContextListener which implements ServletContextListener and i created a static field and method to access the ServletContext in the validator But please do share any elegant answer. Thanks – ton Sep 21 '12 at 07:40

2 Answers2

1

I created a class named ContextListener which implements ServletContextListener

and i created a static field and method to access the ServletContext in the validator

 public class ContextListener implements ServletContextListener {
        @Override
        public void contextInitialized(ServletContextEvent sce) { 
            sc = sce.getServletContext();
        }
        @Override
        public void contextDestroyed(ServletContextEvent sce) { 
        }
        private static ServletContext sc;

        public static ServletContext getServletContext(){
            return sc;
        }
    }


    TestValidator implements ConstraintValidator{ 
     ServletContext sc = ContextListener.getServletContext(); 
    } 

But please do share any elegant answer. Thanks

ton
  • 355
  • 3
  • 13
0

Not a real answer, but too much for a comment:

Your code example looks a bit fragmented. Are you sure that you created a validator? That would result in code that looks rather like this:

public class MyClass {

@Inject
MyValidator validator;

...

}

Also, you have to be careful with entity beans - they have their own independent life-cycle and its rather discouraged to use injection there.

Jan Groth
  • 14,039
  • 5
  • 40
  • 55
  • 1
    Thanks for sharing that they have a different life cycle.... I have a work around to get the ServletContext. – ton Sep 26 '12 at 07:55