2

At the moment, I am try to integrate Confident CAPTCHA into my JSF project. The constructor of the class ConfidentCaptchaClient is as following:

public ConfidentCaptchaClient(String settingsXmlFilePath, HttpServletRequest request, javax.servlet.ServletConfig servletConfig)

This requires a ServletConfig argument. How do I get it inside a managed bean?

kolossus
  • 20,559
  • 3
  • 52
  • 104
Mr.J4mes
  • 9,168
  • 9
  • 48
  • 90
  • @BalusC: Oh, I thought I need to some how get the current Servlet instance that is serving the request. I will try to instantiate an `Servlet` object and see how it goes. Thanks! :D – Mr.J4mes Apr 05 '13 at 17:42
  • @BalusC: :P At the moment, I am actually using PrimeFace's Captcha. However, my application would be used in China and Captcha does not work very nicely over there. Hence, my boss asked me to look for an alternative. :) I believe you must have worked with many captcha solutions. Do you mind recommending a solution or two for me :D – Mr.J4mes Apr 05 '13 at 17:45
  • @BalusC: Yes, it is not a `Servlet`. It just requires access to the `ServletConfig`. That's why I want to get access to a `Servlet` inside my Managed bean so that I can access the `ServletConfig`. – Mr.J4mes Apr 05 '13 at 17:46

1 Answers1

1

This is a hack. What ServletConfig is, is basically an object containing parameters of a Servlet. You'll find practically the same methods and info in the ServletRegistration interface. So it's all the same if you pull the config params off the ServletContext itself and populate in a custom implementation of ServletConfig. Try this:

  1. Retrieve the ServletContext object

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ServletContext servletContext =  (ServletContext) context.getExternalContext(); // Your servlet context here
    
  2. From the servlet context, get the servlet registration object for the servlet you desire

    ServletRegistration reg =   servletContext.getServletRegistration("theServlet"); //ServletRegistration contains all the info you'll need to populate a custom ServletConfig object
    
  3. Use the information you've derived from (2) to populate a custom impl of ServletConfig

    ServletConfig myServletConfig = new MyCustomServletConfig();
    myServletConfig.setInitParams(reg.getInitParameters()); //do a simple transfer of content
    

The last step is an oversimplification, but you'll get the idea.

If you were running a previous version of Java EE (pre 3.0), you'll have had access to the ServletContext#getServlet() which is now deprecated.

kolossus
  • 20,559
  • 3
  • 52
  • 104