michael99man
michael99man

Reputation: 75

Changing servlet location on Init()

Is it possible to change the init parameters so that the servlet is created at a different path? I need to create a servlet at a certain path. Furthermore, would it be possible to artificially pass the path inside the init parameters?

Upvotes: 0

Views: 75

Answers (3)

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

As already shown in other answers, the servlet mapping is not controlled by the servlet, therefore you can't change that from within a servlet instance.

However, you can work around this by introducing a level of indirection (something like a "dispatcher" servlet): map your servlet to a wildcard pattern (like /app/*) and inside your servlet decide the actual action based on the request url path: /app/X will trigger some X action, while /app/Y will trigger Y.

Lots of web frameworks will provide the full functionality out of the box: you can have a look at Spring MVC's DispatcherServlet and its HandlerMapping concept, for instance.

Upvotes: 1

jdevelop
jdevelop

Reputation: 12296

Short answer - you can't change anything related to servlet path mapping in init, since servlet container has already read mapping from web.xml.

Longer answer - you may want to look at servlet loader in Tomcat for example, perhaps it's possible to either invoke it's methods through JMX or do something else.

If you just want to have several mappings and choose which one to serve depending on configuration - use Servlet Filter

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279890

Servlets aren't created at a certain path. They are Java objects that the servlet container Java application creates. If you are running Tomcat, for example, your application will run from the /webapps directory. The most you can do is change the Tomcat configuration to run it from some other path, but you'll have to do this before actually starting the application.

Upvotes: 0

Related Questions