Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a servlet without mapping in web.xml?

How to invoke a simple servlet using the following URL: http://localhost:8080/servlet/MyServlet

I placed it in the folder: tomcat\webapps\ROOT\WEB-INF\classes

I've read there is no need to mention the servlet in web.xml. I did the same. Still, I'm unable to invoke it.

like image 642
Faisal Avatar asked Feb 17 '11 15:02

Faisal


2 Answers

I've read there is no need to mention the servlet in web.xml.

You're probably confusing with the legacy Tomcat-builtin InvokerServlet which was present in older versions of Apache Tomcat (and still mentioned in poor and outdated tutorials/books). It indeed allowed to invoke servlets like that without the need to map anything. However, it was later confirmed that it was a security hole and vulrenable to attacks. It was disabled and deprecated on Tomcat 5.0 and removed on Tomcat 7.0. In such case, you really need to map your servlet in web.xml (and put it in a package!).

Another source of confusion may be the new Servlet 3.0 @WebServlet annotation. When you're already using a Servlet 3.0 container like Tomcat 7.0, then you could use this annotation to map the servlet without the need to fiddle with web.xml.

package com.example;

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {

    // ...

}

Then you'll be able to access it the way you want.

See also:

  • Our Servlets wiki page
like image 167
BalusC Avatar answered Oct 07 '22 09:10

BalusC


your web.xml file has to be like this

<web-app>

<servlet>
    <servlet-class>mypackage.myservlet</servlet-class> 
            <!--  the full name of your class  -->
    <servlet-name>name</servlet-name>
            <!-- name has be the same in servlet and servlet-mapping -->
</servlet>

<servlet-mapping>
    <servlet-name>name</servlet-name>
    <url-pattern>/servlet/MyServlet</url-pattern>
</servlet-mapping>

like image 42
Mansuro Avatar answered Oct 07 '22 10:10

Mansuro