For Bsc(CS)TY Sub:- JSP and Servlet
Steps to create a servlet
The steps are as follows:
- Create
a directory structure
- Create
a Servlet
- Compile
the Servlet
- Create
a deployment descriptor
- Start
the server and deploy the project
- Access
the servlet
Create a directory structures
Create a Servlet
There
are three ways to create the servlet.
The HttpServlet class is widely used to create the
servlet because it provides methods to handle http requests such as doGet(),
doPost, doHead() etc.
|
In
this example we are going to create a servlet that extends the HttpServlet
class. In this example, we are inheriting the HttpServlet class and providing
the implementation of the doGet() method. Notice that get request is the
default request.
|
firstdemo.java
import javax.servlet.*;
import java.io.*;
public class firstdemo extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}
}
Compile the servlet
Jar file
|
Server
|
1)
servlet-api.jar
|
Apache Tomcat
|
Two
ways to load the jar file
- set classpath
- paste the jar file in JRE/lib/ext
folder
Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information about the servlet to be invoked.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet program.
web.xml file
<web-app>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>firstdemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Description of the elements of web.xml file
<web-app> represents
the whole application.
|
<servlet> is sub
element of <web-app> and represents the servlet.
|
<servlet-name> is sub
element of <servlet> represents the name of the servlet.
|
<servlet-class> is sub
element of <servlet> represents the class of the servlet.
|
<servlet-mapping> is sub
element of <web-app>. It is used to map the servlet.
|
<url-pattern> is sub
element of <servlet-mapping>. This pattern is used at client side to
invoke the servlet.
|
Start the Server and deploy the project
One
Time Configuration for Apache Tomcat Server
You
need to perform 2 tasks:- set JAVA_HOME in environment
variable (It is required to start server).
- Change the port number of tomcat
(optional). It is required if another server is running on same port
(8080).
How to deploy the servlet project
How to access the servlet
- http://localhost:8080/demo/hello
http://localhost ---Name of
server
8080
------ Connector port
demo
------- Context root
welcome -------
Url-pattern of servlet