How can I call a servlet from the form's action without using the web.xml deployment descriptor?
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.
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&user=myuser
The url becomes dirty though. But you needn't use the web.xml to invoke the servlet.