1

I have following entry in my web.xml and I need instance of that class in my java file how do I do that?

<servlet>
    <servlet-name>DummyServlet</servlet-name>
    <servlet-class>javax.faces.webapp.Xxxx</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
kolossus
  • 20,559
  • 3
  • 52
  • 104
vinod
  • 1,178
  • 4
  • 16
  • 42
  • could you be more precise? What do you mean by "instance of that class in my java file"? – sschrass Jan 24 '13 at 12:49
  • 2
    This makes no utter sense. Whatever you think to solve with this approach should definitely be solved differently. [Try asking a question about the real problem instead](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – BalusC Jan 24 '13 at 12:57
  • Duplicate http://stackoverflow.com/q/4073013/1530938 – kolossus Jan 24 '13 at 12:58
  • 1
    Thanks For the suggestion may be i need to use different approach.. – vinod Jan 24 '13 at 13:04

2 Answers2

1

Currently I don't believe you can as the servlet container creates a single instance of any given servlets and spawns threads to cater for requests. It simply isn't in your interest to gain access to that one instance that is also being used by the container

There is also the (now deprecated) ServletContext.getServlet("yourClassName"). But don't do it I'm struggling to imagine under what circumstances you'll need to control a servlet instance that DI and good design can't help you avoid. What is the concrete problem?

kolossus
  • 20,559
  • 3
  • 52
  • 104
  • for instance for me the problem is that i need to access servlet before filterChain is all used in a first filter – Enerccio Sep 13 '21 at 10:35
0

You normally do not, the servlet container is responsible for instantiating a single Servlet instance for every servlet element in the web.xml and to use these to process requests and generate responses.

Otherwise, you probably need to parse the web.xml and get the servlet class using Class.forName(className) and then create an instance using clazz.newInstance() assming a default constructor exists (which it should, since this is a servlet).

dkateros
  • 1,574
  • 10
  • 14