Web service using Java Servlets

author-image
CIOL Bureau
Updated On
New Update

Rajesh Devadas, Nandhini
Arumugam
& Sujata De

Advertisment

Servlet is a Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web applications using a request-response paradigm. Creating a Web service from a servlet involves deploying the servlet in
Weblogic. The example of HelloWorld Servlet is given below.


import javax.servlet.ServletContext;


import javax.servlet.ServletException;


import
javax.servlet.http.HttpServletRequest;


import
javax.servlet.http.HttpServletResponse;


import javax.servlet.http.HttpServlet;


import java.io.IOException;


import java.io.*;

public class HelloWorldServlet extends HttpServlet


{

Advertisment

public void doGet(HttpServletRequest request,HttpServletResponse response) throws
IOException, ServletException

{

response.setContentType("text/html");


PrintWriter out =
response.getWriter();


out.println("HelloWorld");


out.close();

}

public void doPost(HttpServletRequest request,HttpServletResponse response) throws
IOException, ServletException

{

doGet(request,response);

}

}


HelloWorldServlet.java



Advertisment

Copy the HelloWorldServlet.java into HelloWorldServlet directory. Compile the java file into HelloWorldServlet/Web-inf/classes directory. Make sure that Servlet.jar is there in the CLASSPATH before compiling. The deployment descriptor needed for Servlet deployment is Web.xml. It is given below.


Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/Web-app_2_3.dtd">



HelloWorldServlet



HelloWorldServlet


HelloWorldServlet




HelloWorldServlet


/ HelloWorldServlet /*




Web.xml



In case of parameters you can also set these tags in Web.xml


name


nandhu


Advertisment

The directory structure that is needed for deploying a servlet is as follows:

HelloWorldServlet


Web-Inf


Classes


HelloWorldServlet.class


Web.xml

Advertisment


In the Weblogic administration console, select Web Application Modules under Deployment and select Deploy a new Web Application Module. Select the directory HelloWorldServlet and click Target Module. Click Deploy. Wait for few seconds till the success message gets displayed. Now the servlet is deployed. It can be tested with the URL : http://hostname:port/HelloWorldServlet/HelloWorldServlet . "Hello world" will be displayed in the browser.

    **Watch out for the next tutorial,
    which will cover creating
    a Web
    service from JSP and HTML
    **

    Advertisment

    The authors are working as Software
    Engineers with Hewlett-Packard India Software Operations Ltd., in Bangalore and
    have expertise in the areas of Web services and other J2EE technologies.

    Advertisment

     


     


     


     


    tech-news