I'm using IBM WebSphere as my servlet container. My application has several servlets and Java classes. My intent is to call one of those servlets directly from a Java class. Doing some research I figured out that is possible to use the RequestDispatcher interface to achieve this. But it is necessary to pass the objects ServletRequest and ServletResponse as arguments to the method forward(). There is some way to bypass this safely and "nicely"? By "nicely" I meant to say preserving good programming and design patterns.
The only way to do this nicely is to decouple the desired logic from the servlets. This requirement is a sign that the servlets are too tight coupled with business/domain code logic which apparently needs to be used as well outside the webapplication context.
Refactor the original servlet code into reuseable Java class(es) and method(s) (which in turn does not use anything from the javax.servlet
package) so that you can finally import and invoke it from both the servlet class and the "plain vanilla" Java class.
You could write a filter that stores the current request and response in static ThreadLocal
, so that you can use them later from within the same request. You can then implement your own static method forward
that uses them and dispatch to another page.
This is somehow the approach taken in JSF where FacesContext.getCurrentInstance
can be accessed anytime.
But I wouldn't qualify that as an elegant design. Rather try to follow @BalusC advice and refactor your logic.
It would help to get some more background as to why you are trying to do this. I am assuming you want to invoke some piece of business logic in the servlet. This is a sign that the application is poorly designed.
Are you familiar with MVC architecture? If your "model" code was loosely coupled, you would be able to call it directly.