+ All Categories
Home > Documents > Servlet Are Java Programs

Servlet Are Java Programs

Date post: 10-Apr-2018
Category:
Upload: masoomreza
View: 224 times
Download: 0 times
Share this document with a friend

of 27

Transcript
  • 8/8/2019 Servlet Are Java Programs

    1/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 1

    Servlet are Java programs, which resides on the Web Server.With Servlet, Web developers can create fast and efficient server-side applications inJava instead of using CGI and Perl. A Servlet can be thought of as a server side

    applet. Servlets are loaded and executed by a web server in the same manner in whichapplets are loaded and executed by a web browser. Thus, we can say that Servlet is aserver side software component, written in Java, that dynamically extends thefunctionality of a server. A servlets work is done behind the scene on the server.The results of the Servlet are returned to the client usually in the form of HTML.

    In designing an Internet based Application , the intermediate server run on a program to

    offers user full middle ware services between the client and the servers. They are called servlets in

    java.

    Or simply say, servlets are modules that extends request /response oriented servers. Such as java

    enabled web server.

    What is World Wide Web?

    The World Wide Web (WWW) popularly known as the web, is a network ofcomputers all over the world. All computers in the web can communicate with eachother. Normally, all computers use a uniform communication standard which is a

    protocol called HTTP.

    How does the WWW work?Web information is stored in documents called web pages. Web pages are files storedin computers called web servers. Computers reading the pages are called web clients.Web clients view the pages with a program called web browser.

    Web Browser:

    A web browser is a client application that requests, receives and displays HTML

    pages. However, current browsers do much more than just rendering HTML pages.

    computerHttp Server

    DatabaseOrder entry

    Client

  • 8/8/2019 Servlet Are Java Programs

    2/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 2

    Todays browser can display animated images, play sound and video, provide secure

    connection and much more. Currently, two browsers command the majority of thebrowser market: Netscape NavigatorandMicrosoft Internet Explorer.

    Web Server:

    A web server responds to requests from a web browser by returning HTML pages,images, applets, or other data. The web server is also responsible for enforcingsecurity policies, storing frequently requested files in cache, logging request andmuch more. Web server remains behind the screens waiting to fulfill any validrequest.

    Servlets can be embedded in different servers because the servlet API, which is usedto write servlets, assumes nothing about the server's environment or protocol. Servlets

    are widely used within HTTP servers. Many commonly used web servers support theservlet technology. JIGSAW, Java Web Server and JRUN are only a few.

    We have seen that Web Servers areresponsible for returning certain

    resources like HTML file, graphicsetc. But, they cannot perform anykind of processing. Here in comes

    the scope of Servlet.

  • 8/8/2019 Servlet Are Java Programs

    3/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 3

    A Servlets Job

  • 8/8/2019 Servlet Are Java Programs

    4/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 4

    The Advantages of using servlet are:

    It is capable of in-process running

    It is available in the compiled byte-code forms.

    The servlet application is much more crash-proof.

    It is platform independent.

    The servlet applications are durable i.e. the application occupies the memory location

    until the destroy() method is called. It can be dynamically loaded across a network.

    The servlet applications are protocol independent. Though it is commonly used to

    extend the HTTP server functionality, it can make use of SMTP, Telnet, NNTP andFTP as well.

    Extensible.

    The servlet is secure as it makes use of the servers security manager. The most important of its advantage is the servlet codes are written using java.

    The Servlet Life Cycle :

  • 8/8/2019 Servlet Are Java Programs

    5/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 5

    The HTTP Basics

    The hypertext Transfer Protocol (HTTP) is a stateless TCP/IP based protocol used for

    communicating on the World Wide Web. HTTP defines the manner in which webclients communicate with web servers. Today, the most common version of this is

    HTTP/1.0.HTTP also called a connectionless protocol.

    A protocol is said to be stateless if it has no memory of prior connections and cannot

    distinguish one clients request from that of another. The stateless nature of HTTP isboth its strength and weakness. The strength is that its stateless nature keeps theprotocol simple and straightforward. The disadvantage is in the overhead required tocreate a new connection with each request and the inability to track a single user.

    That is, using HTTP, a client opens a connection with the server, and sends requests,receives a response and closes the connection. Each request requires its ownconnection.

  • 8/8/2019 Servlet Are Java Programs

    6/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 6

    Now let us take a close look how HTTP helps to communicate between a web serverand a web browser. There are generally four stages of a simple web transaction:

    1. The client opens a connection to the server:

    First, the client opens a TCP/IP connection to the server. By default, the connectionon the server is made to port 80, unless or otherwise specified.

    2. The client makes a request to the server:

    Let us assume that the web browser makes a request to retrieve an HTML file. Forthis, the user enters the required URL into the web browser. This request is brokeninto three parts: the request method, the source name, and the protocol.

    3. The server responds to the request:The server gets the request from the browser. The server responds with a status code,various header files and if possible, contents of the request.

    4. Connection is closed

    Either the server or the client may close the connection. The server generallyterminates the connection after the response has been sent. Similarly, a browser oftencloses the connection once the complete response has been received.

    When a client connects to a server and makes an HTTP request, the request can be ofseveral different types called methods. The most important and frequently usedmethods are GET method and POST method.

    GET is the most common HTTP method. It is used to request a resource from theserver. That means, the GET method is designed for getting different information like

    a document, chart or the result from a database query. The GET method should not beused to place an order, update a database or serve an explicit client action in any way.

    A drawback of using the GET method for login transactions is that the informationentered by the user is appended to the URL and displayed in plain text by thebrowser. This method is normally used to request static data. Response to GETrequest is cached by the proxy server for use in further requests.

    POST is an HTTP method commonly used for passing user input to the server. This

  • 8/8/2019 Servlet Are Java Programs

    7/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 7

    means that the POST method is designed for passing information (like information

    that is to be stored in a database etc).

    The POST method uses different techniques to send information to the server, as in

    that case, it may need to send megabytes of information.

    In the POST method, the parameter information is stored in the body of the requestrather than in URL portion, as compared to the GET method. This approach has

    advantages, because there is no limit to the amount of information that can be passedwhen it is stored in the body of the request. Moreover, the information submitted bythe user is not visible in the URL.

    The Servlet APIServlets use classes and interfaces from two packages:

    javax.servlet package

  • 8/8/2019 Servlet Are Java Programs

    8/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 8

  • 8/8/2019 Servlet Are Java Programs

    9/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 9

  • 8/8/2019 Servlet Are Java Programs

    10/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 10

    Types of Servlets

    Generic Servlet:- Protocol independent Servlet. Extends the javax.servlet.GenericServlet class.Should override its service() method to handle requests appropriate for the Servlet.The service() method accepts two parameters:

    (i) A request object(ii) A response object

    HTTP Servlet: Have HTTP functionality. Extends the javax.servlet.http.HttpServlet class.Usually does not override the service() method. It overrides the doGet() and thedoPost() methods.

    The HTTPServlet Class

  • 8/8/2019 Servlet Are Java Programs

    11/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 11

    How to Run the Servlet

    1. Install Jdk1.3 and java webserver 2.0 or servletrunner.

    2. Compile the Servlet(make sure that servlet.jar included in your classpath;

    How to set Classpath :

    Set the environment variable (System variable :- new ->

    Variable name :classpathValue :c:\webserver 2.0\bin;c:\jdk1.3\bin;c:\webserver\lib\servlet.jarGo on path click-editAfter the end append : ;c:\webserver 2.0\bin;c:\jdk1.3\bin

    Ok-apply ok

    Reboot the machine.

    Open command Prompt :C:\md testCd testC:\>test> notepad HelloServlet.java

    import java.io.*;importjavax.servlet.*;public class HelloServlet extends GenericServlet{public void service (ServletRequest request,ServletResponse response) throws ServletException,IOException{response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("Hello!");pw.close();}

  • 8/8/2019 Servlet Are Java Programs

    12/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 12

    }

    C:\>test>javac HelloServlet.javaC:\> test> copy HelloServlet.class c:\java webserver 2.0\servlets

    ThenStart-run ->type(http://localhost:8080/servlet/HelloServlet

    How to work with HTML page

    (The next Hello.java )

    import java.io.*;importjavax.servlet.*;importjavax.servlet.http.*;public class Hello extends HttpServlet{public void doGet(HttpServletRequestreq,HttpServletResponse res)throwsServletException,IOException{res.setContentType("text/html");if(req.getMethod().equals("HEAD"))return;

    PrintWriter out=res.getWriter();String name=req.getParameter("Tua");out.println("");out.println("Hello," + name +"

  • 8/8/2019 Servlet Are Java Programs

    13/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 13

    public void doPost(HttpServletRequestreq,HttpServletResponse res)throwsServletException,IOException{doGet(req,res);}}

    The Parameterized Servlet

    Data can be sent from the HTML form as parameters to the Servlet to be processed.

    The ACTION attribute of the tag is used to point to the destination Servlet.When the user clicks the submit button of the HTML form, the data is sent to the

    servlet set using the ACTION attribute.

    The GET method is used by the form to append the data to the request URL as aquery string.

    Create the following HTML form.Parameterized Servlet testPlease enter the name:

    Create the servlet as:

    import java.io.*;importjavax.servlet.*;importjavax.servlet.http.*;public class Hello extends HttpServlet {public void doGet(HttpServletRequestreq, HttpServletResponseres)throwsServletException, IOException {res.setContentType(text/html);PrintWriter out = res.getWriter();

  • 8/8/2019 Servlet Are Java Programs

    14/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 14

    String name = req.getParameter (name);out.println ();out.println(Hello, +name + );out.println();out.println(Hello, + name);out.println();}public String getServletInfo() {return A Servlet that says hello;}}

    Define a CookieA Cookie is a simple mechanism used to store and retrieve user-specific informationon the web.

    When an HTTP server receives a request, in addition to the requested document, theserver may choose to return some state information that is stored by a cookie-enabled

    client. This state information includes an URL range within which the informationshould be returned to the server.

    The HTTP header syntax for setting a cookie is as follows:Set-Cookie: = ; expires = ; domain =; path = ; secure

    The Set-Cookie instruction is included in the header of the servers HTTP response to

    instruct the client to store a cookie.

    Multiple Set-Cookie headers can be included in a single HTTP response.

    Enter any value for the cookie:The servlet code is as follows:

  • 8/8/2019 Servlet Are Java Programs

    15/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 15

    // the program shows the implementation of theaddCookie() method

    import java.io.*;importjavax.servlet.*;importjavax.servlet.http.*;public class addCookieServlet extends HttpServlet{public void doPost(HttpServletRequestreq,HttpServletResponse res)throwsServletException, IOException{//Get parameter from Http requestString data = req.getParameter("cookiedata");//Create cookieCookie cook = new Cookie("Cookie",data);//Add cookie to Http responseres.addCookie(cook);//write output to browser

    res.setContentType("text/html");PrintWriter pw = res.getWriter();pw.println("Cookie has been sent to");pw.println(data);pw.close();}}

    Session Management

    HTTP defines the manner in which web clients communicate with each other. HTTPis a stateless protocol. A protocol is said to be stateless if it has no memory of prior

    connections and cannot distinguish one clients request from that of other. Thestateless nature of HTTP keeps the protocol simple and straightforward.

    What is a Session?

    A session is a persistent network connection between two hosts (usually a client and a

    server) that facilitates the exchange of information. When the connection is closed,the session is over.

    What is HTTP Session?

    HTTP session involves a virtual connection between a client and a server rather than

    a physical one for the exchange of information. This type of session is also known asvirtual session.

    Lifecycle of an HTTP Session:

    In an HTTP session, each connection between the client and the server is very brief.An HTTP lifecycle consists of following events: -

    y The client requests a resource from the server.

    y The server returns an authentication challenge.

    y The client returns a valid user name and password.

  • 8/8/2019 Servlet Are Java Programs

    16/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 16

    y The server returns a valid session ID that allows this client to be uniquely identified.

    y The client issues any number of requests to the server. The server is able to identifythe client based on the session ID.

    What is the need of Session Management?

    We already know that HTTP is a stateless protocol. Though stateless protocols havemany advantages over stateful, they have some technical drawbacks. Because of thestateless nature of the HTTP protocol, the server cannot distinguish one user from theanother. So, security policy cannot be enforced if the server does not know who is

    requesting particular resources. But each session has its unique session ID. Thissession ID uniquely identifies each client by the server. Session management is usefulfor storing large amount of state information because only a session ID is passedbetween client and server. Session management can also be used to enforce security

    policies, as the client can be identified with every request.

    Session Management methods:

    There are many methods to facilitate the exchange of session ID between the clientand the server. In this section, we will explain three of the most commonly usedtechniques.

    Storing Session Information in the URL Path: -

    This method of managing session accomplishes two-way communication byembedding a session ID (or other information) in the URL path. In this case, theclient requests the document. The screen includes an HTML form that allows theclient to submit a name and password.

    Upon receiving a valid name and password, the server generates an unique session IDand immediately redirects the client to his desired page. The server then parses the

    path portion of all requested URLs for a valid session ID. From this point, the

    hyperlinks which all documents return to the client, use only relative URLs.

    This method has both advantages and disadvantages. The advantage is that, no specialbrowser features are required. This method works with any browser, including those,

    which do not support cookies.

    There are also disadvantages to this approach. Firstly, the requirement of using onlyrelative URLs throughout an entire web site can be limiting. Secondly, the clients

    unique session ID is visible on the browser, which can present a security risk.

    Rewritten URLs: -

  • 8/8/2019 Servlet Are Java Programs

    17/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 17

    Another popular method of sharing state information between the client and server

    involves the use of rewritten URLs. Rewritten URLs pass state information betweenthe client and server by embedding information in the URL of all hyperlinks withinan HTML document. It should be noted that we cannot use URL rewriting with static

    HTML pages. It is because of the fact that URL must be encoded for each user toinclude the session ID. The way in which the URL is encoded is server specific.

    Hidden Variables: -One way to support anonymous session tracking is to use hidden variables. A hidden

    variable operates like an HTML form (including text box, check boxes, radiobuttons). So that when the page is submitted, the client transmit the fields name/value pair to the server.

    We include hidden form files with HTML:.

    .

    Session Management with Cookies

    Advantages of using cookies for Session Management:

    y

    Cookies need to be stored only once. It is not require to return the information tothe client.

    yCookies do not require parsing of the requested URL or the HTML document.

    yCookie information can be extracted from the client request using a very simple

    Servlet API method i.e. the getCookies() method of the HttpServletRequest).

    Disadvantages of using cookies for Session Management:

    yAll browsers do not support cookies.

    The lack of cookie support can result from:

    yThe clients using old browsers that do not recognize cookies.

    yThe users instruction to the browser not to accept cookies.

    // the program shows the implementation of theaddCookie() method

    import java.io.*;importjava.util.*;importjavax.servlet.*;importjavax.servlet.http.*;public class DateShow extends HttpServlet{public void doGet(HttpServletRequestreq,HttpServletResponse res)

  • 8/8/2019 Servlet Are Java Programs

    18/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 18

    throwsServletException, IOException{//Get Http session objectHttpSessionses = req.getSession(true);//Get writerres.setContentType("text/html");PrintWriter pw = res.getWriter();pw.print("");//display date/time of last acccessDate date = (Date)ses.getValue("date");if(date!=null){pw.print("Last accessed:" + date +"
    ");}//display current date/timedate = new Date();ses.putValue("date",date);pw.print("Current date is:" + date);}

    }

    Database Connection

    importjavax.servlet.*;

    importjavax.servlet.http.*;import java.io.*;importjava.io.PrintWriter.*;importjava.sql.*;public class Studentjdbc extends HttpServlet{Connection dbConn;public void init(ServletConfigconfig)throws ServletException{super.init(config);try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    dbConn=DriverManager.getConnection("jdbc:odbc:sush");}catch(ClassNotFoundException e){System.out.println("JDBC-ODBC bridge not found");return;}catch(SQLException e){

  • 8/8/2019 Servlet Are Java Programs

    19/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 19

    System.out.println("Exception thrown in init");return;}}public void doGet(HttpServletRequestrequest,HttpServletResponse response) throwsServletException,IOException{try{response.setContentType("text/html");PrintWriter out =response.getWriter();Statement st1=dbConn.createStatement();ResultSet rs1=st1.executeQuery("select * fromstudent ");out.println("");out.println("Student

    list");out.println("");out.println("STUDENTDETAILS");out.println("");out.println("reg_no");out.println("Fname");out.println("Lname");out.println("address ");while(rs1.next()){out.println(""+rs1.getString("reg_no")+""+rs1.getString("Fname")+""+

    rs1.getString("Lname")+""+rs1.getString("address")+"");}out.println("");out.println("");out.close();}catch(Exception e){e.printStackTrace();}}}

    prepareStatement( ) statement :

    The SQL statement needs to be compiled every time when it is executed. Toovercome this compilation problem, JDBC provides a prepared statement, which isidentified by the java.sql.PreparedStatement interface. The advantages of this

    statement over a regular Statement is that it is created with a parameterized SQL

    statement. Each PreparedStatements SQL command parameter is indicated by aquestion mark (?) in the SQL String and represents an input (IN) variable that can be

  • 8/8/2019 Servlet Are Java Programs

    20/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 20

    dynamically set before the statement is executed. The values of each parameter need

    to be set after the statement is created, so that it can compile when the statement iscreated. A PreparedStatement is created with the prepareStatement() method on theConnection object as shown here:

    PreparedStatement statement = connection.prepareStatement(select * from customer where employee _id =?);

    import java.io.*;importjava.sql.*;importjava.util.*;importjavax.servlet.*;importjavax.servlet.http.*;public class jdbcservlet extends HttpServlet{PreparedStatementst;

    Connection cn=null;public void init(ServletConfig s) throwsServletException{super.init();}public void doGet(HttpServletRequestrq,HttpServletResponsers) throwsServletException,IOException{doPost(rq,rs);

    }public void doPost(HttpServletRequestrq, HttpServletResponsers) throwsServletException,IOException{rs.setContentType("text/html");PrintWriter p=rs.getWriter();p.println("");p.println(" Response from the server");p.println(" data has been saved ");p.println("");try{

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");cn=DriverManager.getConnection("jdbc:odbc:md");if(cn!=null){int flag=0;//String query="insert into Employee values";String s1=(String)rq.getParameter("empid");String s2=(String)rq.getParameter("name");String s3=(String)rq.getParameter("add");

  • 8/8/2019 Servlet Are Java Programs

    21/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 21

    String s4=(String)rq.getParameter("design");String s5=(String)rq.getParameter("basic");String s6=(String)rq.getParameter("salary");String s7=(String)rq.getParameter("phone");st=cn.prepareStatement("insert into Employee values(?,?,?,?,?,?,?)");System.out.println(s1+s2+s3+s4+s5+s6+s7);st.setString(1,s1);st.setString(2,s2);st.setString(3,s3);st.setString(4,s4);st.setString(5,s5);st.setString(6,s6);st.setString(7,s7);int n=st.executeUpdate();}}catch(SQLException s)

    {System.out.println("message:"+s.getMessage());}catch(ClassNotFoundExceptioncf){System.out.println("message:"+cf.getMessage());}catch(Exception e1){System.out.println("message:"+e1.getMessage()); {System.out.println("message:"+e1.getMessage());}

    Finally{try{if(cn!=null)cn.close();p.close();}catch(SQLExceptionsq){System.out.println("message:"+sq.getMessage());}}

    }}

    createStatement( ) statement

    Java String objects containing SQL commands are passed to JDBC calls. Invoking

    createStatement() on a Connection object, we can obtain regular Statement object.Such nonprepared types of statements are useful for infrequent queries because theyare not precompiled for efficiency, as are PreparedStatement objects. You can create

  • 8/8/2019 Servlet Are Java Programs

    22/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 22

    a Statement object as:

    Statement st = connection.createStatement ();

    The Statement object is then called upon to execute an actual SQL command using one ofthe three basic methods:

    1. ResultSetexecuteQuery(String sql) allows one to execute SQL queries and obtain aResultSet object.

    For example:ResultSetrs = statement.executeQuery(SELECT * FROMEMPLOYEE);

    2. intexecuteUpdate(String sql) allows us to execute SQL inserts, deletes, updates and

    then obtain a count of updated rows.

    For exampleintnValues = st.executeUpdate(INSERT INTO EMPLOYEE VALUES+(129,Sam,Cheng,s,123Sam St.,12,Baltimore,MD,+ 20222, (410)444-4444,[email protected]) );

    boolean execute(String sql) is the most generic type of execute call allowing one toexecute SQL DDL commands and then obtain a boolean value indicating whether aResultSet was returned or not.

    booleanreturnValue = statement.execute(SELECT * FROM CUSTOMER );

    importjavax.servlet.*;importservlet.http.*;import java.io.*;import.sql.*;importjava.util.*;public class jdbcservlet2 extends HttpServlet{Statement st;

    Connection cn=null;public void init(ServletConfig s) throwsServletException{super.init(s);}public void doPost (HttpServletResquestrq,HttpServletResponsers) ThrowsServletException,IOException

  • 8/8/2019 Servlet Are Java Programs

    23/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 23

    {rs.setContentType("text/html");PrintWriter p=rs.getWriter();p.println("");p.println(" Response from the server");p.println(" data has been saved ");p.println("");try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");cn=DriverManager.getconnection("jdbc:odbc:md");if(cn!=null){intflaf=0;String query="insert into employee values( ";String s1=(String)rq.getParameter("empid");

    String s2=(String)rq.getParameter("name");String s3=(String)rq.getParameter("add");String s4=(String)rq.getParameter("design");String s5=(String)rq.getParameter("basic");String s6=(String)rq.getParameter("salary");String s7=(String)rq.getParameter("phone");query+="'"+s1+","+s2+","+s3+",","+s4+","+s5","+s6","+s7+"'")";int n=st.executeUpdate(query);}}catch(SQLException s){System.out.println("Message:"+s.getMessage);

    }catch(ClassNotFoundExceptioncf){System.out.println("Message:"+cf.getMessage);}catch (Exception e1){System.out.println("Message:"+e1.getMessage);}finally{try{

    if(cn!=null)cn.close();p.close();}catch(SQLExceptionsq){System.out.println("message:"+sq.getMessage());}}

  • 8/8/2019 Servlet Are Java Programs

    24/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 24

    }}* * * * * * * *

  • 8/8/2019 Servlet Are Java Programs

    25/27

    Introduction to Servlet

    JahiruddinAhamed (Lecturer of Information Technology) Page 25

    The above figure depicts the steps required to perform applet to Servlet

    communication. It comprises of two steps:

    yThe applet opens a DataOutputStream and sends an HTTP request to the Server,

    invoking the Servlet.

    yThe applet opens an InputstreamReader to the Server and retrieves the results of

    the Servlet.

    Lets try to understand this with the help of an example

    Create the Appletimportjava.applet.*;

    importjava.awt.*;importjava.awt.event.*;import java.io.*;import java.net.*;public class AppletServlet extends Applet implementsActionListener{TextFieldtxtQuery;TextAreatxtResult;Button bExecute;public void init(){Panel p1=new Panel();

    p1.setLayout(new FlowLayout(FlowLayout.LEFT));p1.add(new Label("Enter the Query:"));txtQuery=new TextField("", 50);p1.add(txtQuery);bExecute=new Button("Execute");bExecute.addActionListener(this);p1.add(bExecute);add("North",p1);txtResult=new TextArea(10,80);

  • 8/8/2019 Servlet Are Java Programs

    26/27

  • 8/8/2019 Servlet Are Java Programs

    27/27


Recommended