views:

103

answers:

2

How can I call a servlet from the form's action without using the web.xml deployment descriptor?

+2  A: 

Upgrade to Java EE 6 / Servlet 3.0, then you'll be able to register the servlet by the @WebServlet annotation.

package com.example;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet(urlPatterns={"/myServlet/*"})
public class MyServlet extends HttpServlet {
    // ...
}

No need for web.xml anymore. The above does basically the same as following:

<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/myServlet/*</url-pattern>
</servlet-mapping>

As far now you can choose from under each Glassfish v3 and Tomcat 7 as Servlet 3.0 implementations.


Prior to Servlet 3.0 your best bet is likely the front controller pattern. Have a single servlet in web.xml which delegates requests/actions to domain objects based on the request parameters and/or pathinfo. This is also used in the average MVC framework.

BalusC
+1 - Nice. How on earth do you keep up with all of this so well? Most impressive.
duffymo
@duffy: by reading and playing a lot :)
BalusC
My reading and playing aren't nearly as effective as yours. Maybe I need to read less and play more.
duffymo
@duffy: yes, playing helps definitely more than just reading. Own experience is the best knowledge source.
BalusC
Great answer but the reason why I'm without a web.xml is because the company I work for hasn't upgraded our webserver since early 2000 and probably won't for a while. http://stackoverflow.com/questions/3397798/sun-one-web-server-configuration
jeff
Sorry, I can't be of help for you here. This is a server-specific problem and I have never used that server.
BalusC
A: 

You can directly use the class name to invoke the servlet in the webserver.
If your url is http://myurl.com/
Then, appending the full class name to the url will invoke the servlet.

Eg:
If my servlet is com.my.package.servlet.MyServlet
Then, you can use http://myurl.com/com.my.package.servlet.MyServlet
To pass parameters, http://myurl.com/com.my.package.servlet.MyServlet?name=myname&amp;user=myuser
The url becomes dirty though. But you needn't use the web.xml to invoke the servlet.

aNish
Is this really true?
EJP
Extremely bad advice. First, it works only on Tomcat and certain derived containers (the feature is exposed via the Invoker Servlet functionality). Second, there has been atleast one security bug in this area. More info at http://wiki.apache.org/tomcat/FAQ/Miscellaneous#Q3
Vineet Reynolds
@EJP: Yes, it's true.@Vineet: It was not an advice to use it. Just an information that there is such a possibility to do without using web.xml.
aNish