Access Servlets.
Information
There are two methods to access servlets.
Operating system used
Windows XP Home Edition Version 5.1 SP 2
Software prerequisites
Tomcat 4.1.31.
Procedure
- First create a simple servlet HelloWorldServlet.java and deploy the HelloWorldServlet.class file
in:
..\Tomcat 4.1\webapps\<myapp>\WEB-INF\classes\com\mobilefish\main\servlets
Note: In this example <myapp> is the web application context name.
package com.mobilefish.main.servlets;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloWorldServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello World</h1>");
out.println("</body>");
out.println("</html>");
}
}
- Method 1: Edit file ..\Tomcat 4.1\webapps\<myapp>\WEB-INF\web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>Demo</display-name>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>com.mobilefish.main.servlets.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Restart Tomcat and access the servlet using url:
http://localhost:8080/<myapp>/hello
- Method 2: Edit file ..\Tomcat 4.1\webapps\<myapp>\WEB-INF\web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>Demo</display-name>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>com.mobilefish.main.servlets.HelloWorldServlet</servlet-class>
</servlet>
</web-app>
.. and edit file ..\Tomcat 4.1\conf\web.xml
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
:
:
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
Restart Tomcat and access the servlet using url:
http://localhost:8080/<myapp>/servlet/HelloWorldServlet
|