Question

I am having this question can we specify the servlet path in the servlet itself something like

(path = /myServlet) public MyNormalServlet extends HttpServlet....{ . . . }

So If call from browser say "http://localhost:8080/myServlet" this servlet of mine will get called and it would also be an independent servlet in tomcat whose mapping cant be specified in tomcat's web.xml

Please if can anyone help me with this and provide the possible solution for it..

Thanks,

Was it helpful?

Solution

If you are running Tomcat, just edit the web.xml file:

(...)
<servlet>
    <servlet-name>TestingServlet</servlet-name>
    <servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>TestingServlet</servlet-name>
    <url-pattern>/servlet/TestingServlet</url-pattern>
</servlet-mapping>
(...)

Where: ... the name of your servlet. It can be anything you want, it just must match the inside the servlet-mapping ...the name of the class that will handle this servlet.

... anything you want, as long as it matches the same tag on ... the url path you want to respond to.. So in your example you would type '/myServlet' here

If you want to read more on the subject: http://javapapers.com/servlet/what-is-servlet-mapping/

OTHER TIPS

You can do that with the Servlet 3.0 @WebServlet annotation, if you are using a Servlet 3 container:

@WebServlet(urlPatterns={"/path1","/path2"[,...],}

You can also specify the description, init params, etc, this way. You don't need to write any XML at all. See the Servlet 3.0 Javadoc.

What you want is not supported in standard servlets. You can use something like Spring MVC with annotations to achieve the same.

http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html

e.g.

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public ModelAndView helloWorld() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("helloWorld");
        mav.addObject("message", "Hello World!");
        return mav;
    }
}

and if you deploy the web app with this Spring MVC controller to your root webapp context in Tomcat, accessing "http://localhost:8080/helloWorld" will execute the helloWorld method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top