SERVLET

PREVIOUS



JSDK - Java Servlet Developers Kit
Introduction:
          Servlets are Server Side Applets.  Applets are executed in Browsers while Servlets are executed in Web Servers.
Servlets are methods to:
1. Receive client request
2. Process the request
3. Response to client                      
1. Servlets receive the client request in the form of HTML using Protocol. (Most widely used Protocol is HTTP).
2. Servlets do the server-side programming with servlet APIs.
(APIs initiate the connection between servlets and the specific application)
3. Servlet sends the response to the client in the form of HTML.
Applications of Servlets:
1.      Servlets may handle multiple requests concurrently and synchronize the request. Therefore, it allows supporting systems such as on-line conferencing.
2.      It supports Forwarding requests to other Servlets. So it can be used to balance load among servers.
(Servlet forwards the request got from the client to another servlet)
3.      Servlets are effective replacement of CGI (Common Gateway Interface) Scripts to produce Dynamic documents.
Simple Servlet:
public class <class name> extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException
{
....
}
}

Starting Servletrunner:
The Servletrunner is in <jsdk>/bin directory.
c:\program files\apache tomcat 4.0\bin>startup
          Start servletrunner
It will open a window; keep it in open state until you invoke the servlet file using Browser.
To save the servlet programs:
c:\programfiles\apachetomcat4.0\webapps\examples\web-inf\classes>
To set the servlet path:
c:\ani\cla.bat
set classpath=%classpath%;c:\program files\apache tomcat 4.0\common \lib\servlet.jar;
Servlet is invoked by:
1. From Browser:

·                          http://machine-name:portno/foldername/servlet/filename
http://localhost:8080/examples/servlet/csc1
http://machine-name:portno/foldername\servlet/filename? Parameter name=parameter value

http://localhost:8080/examples/sevlet/csc?s1=anu&s2=20
Mainly used Properties:
          Parameter:
The syntax of a single parameter is
syntax:
parametername=parametervalue
A link:
1.
Eg:  <a href=’http://localhost:8080/examples/servlet/csc1’></a>
This link will call the Servlet program csc1.
          Life cycle of Servlet:
1.      A server loads and initializes the servlet
2.      A server handles client requests
3.      Process the server
4.      Response the server.



1. Initializing the Servlet:
·                          Initialization is obtained using servlet's init method. 
·                          Servlet completes the initialization before handling the request
·                          init method is called whenever the servlet is reloaded.
·                          init method is provided by HttpServlet class
·                          If an error occurs during initialization unavailableException is thrown
2. INTERACTING WITH CLIENTS:
1. Servlets handles client request through its method.
2. Service method dispatching each request to a method designed to handle that request.
3. Request & Response:
          The user request is represented by HttpServletRequest object.
          The response  represented by HttpServletResponse object.
4. Handling Requests:
          The following are the methods to which the service method delegates request.
·       doGet àreceive the info from client
·       doPostà to send the info to client.

HTTP HEADER DATA:
(Head contains information about the user protocol, contenttype, packet information...). In the header information, the user using setContentType method in the HttpServletResponse type object often changes the content type.
Handling Get Method:
          Servlet handles the GET request by overriding the servlet method doGet
Syntax:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
  ....
  ....
  ....
}



Starting Servletrunner:
2. From Html File : Servlet is called in a HTML file using any Tags that support URL attribute. Some of the tags:
<form action = “http://localhost:8080/examples/servlet/emp1”> </form>



Handling POST method :  
          Servlet handles the POST request by overriding the doPost method
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
  ....
  ....
  ....     
}
Methods Used in Request & Response Methods:
          // Set content-type using :
          res.setContentType(“text/html”);

          // To access the Writer :(Writer is used to response to the client:
          PrintWriter out=res.getWriter();

          // To Get a Argument from request :
          String s= req.getParameter();
         
          //To close the writer :
          out.close();



 (E.g. If the database servlet connected to a real database, its initial arguments look like
servlet.name.initargs=\
User=<name>,\
Password=<pswd>,\
URL=<databaseurl>
Properties are stored in a text file with a default name of servlet.properties. You can specify another property file name when you start servletrunner.
          Start servletrunner -s <property-filename>
          Eg. : start servletrunner -s test. properties (Where test is a property file)
emp,emp1, postser,flow1
flow colorser




PROGRAMS

program :1(simple pro using httpservlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<head>");
        out.println("<title>Hello World!</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello World!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

program :2(GenericServlet àservice( ) )

import javax.servlet.*;
import java.io.*;

public class csc1 extends GenericServlet
{
public void service(ServletRequest rq,ServletResponse rs)throws ServletException,IOException
{
rs.setContentType("text/html");
PrintWriter p=rs.getWriter();
p.println("<html><body bgcolor='gold' text='blue'>");
p.println("<h1>Welcome World</h1></body></html>");
p.println("<img src='e:/p1.jpg'>");
}
}


program :3 (passing parameter to the servlet)

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class csc extends HttpServlet
{
public void doGet(HttpServletRequest rq,HttpServletResponse rs)throws ServletException,IOException
{
rs.setContentType("text/html");
PrintWriter p=rs.getWriter();

p.println("<html><body bgcolor='gold' text='blue'>");

p.println("<h1>Hello World</h1></body></html>");

String s,age;
s=rq.getParameter("s1");
age=rq.getParameter("s2");

p.println("<h2>"+s+"</h2>"+"<h3>"+age+"</h3>");

}
}










Programs 4: using methods(get,post)

(HTML)

<html>
<body>
<center>
<form name="form1" method="post" action="http://localhost:8080/examples/servlet/emp1">
<table>
<tr>
<td><b>Employee</td>
<td><input type="textbox" name="Employee" size="25">
</td>
<td><b>Phno Number</td>
<td><input type="textbox" name="phone number" size="25">
</td>
</tr>
</table>
<input type=submit value="submit">
</body>
</html>


program 4: Servlet program:

import java.io.*;
import java.util.*;
import javax.servlet.*;

public class emp1 extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException
{
PrintWriter out=response.getWriter();
Enumeration e=request.getParameterNames();

while(e.hasMoreElements())
{
String parameterName=(String)e.nextElement();
out.print(parameterName + "=");
String parameterValue=request.getParameter(parameterName);
out.println(parameterValue);
}
out.close();
}
}        




Program 5: (html)

<html>
<body background="d:\images\aa.jpg">
<center>
<form name="form1" method="post" action="http://localhost:8080/examples/servlet/postser">
<B>subjects :</B>

<select name="subject" size="1">
<option value="java">java</option>
<option value=".net">.net</option>
<option value="linux">linux</option>
</select>
<br>
<br>
<input type=submit value="submit">
</form>
</body>
</html>

Program 5: (servlet for above html)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class postser extends HttpServlet
{
public void doPost(HttpServletRequest rq, HttpServletResponse rs)throws ServletException,IOException
{
String s=rq.getParameter("subject");
rs.setContentType("text/html");
PrintWriter o=rs.getWriter();
o.println("<b> the selected sub is: ");
o.println(s);
o.close();
}
}



Program 6:

import javax.servlet.*;
import java.io.*;

public class eni extends GenericServlet
{
public void service(ServletRequest a, ServletResponse b)throws ServletException,IOException
{
b.setContentType("text/html");
PrintWriter w=b.getWriter();

w.println("<html><body bgcolor='yellow' text='yellow'><marquee behavior='alternate' bgcolor='pink'><font size=20 face='script' color='yellow'>welcome</font></marquee>");
w.println("<a href='http://localhost:8080/examples/servlet/csc?s1=hello&s2=100'>hai</a></body>");
w.println("</html>");
}
}




Cookies:

* The cookies formulate the customer-related information as cookies, send such information to a client and instruct it to store that information in it.

* In later the server shall retrieve such information from the client

·       servlets send cookies to clients by adding them to http request
·       client return the cookies by adding them to http request

Cookies have the two processes they are name, value

A server can send one or more cookies to a client, client software such as web browser will support around 20 cookies per host.

Program:1 (html program)

<html>
<body>
<form name="form1" method ="post" action="http://localhost:8080/examples/servlet/cooke">

<b>Name of first cookie:</b>
<input type=textbox  name="nam" size=25 value= " "><br>

<b>Value of first cookie:</b>
<input type=textbox  name="val" size=25 value= " "><br>

<b>Name for second cookie:</b>
<input type=textbox  name="nam1" size=25 value= " "><br>

<b>Value for second cookie:</b>
<input type=textbox  name="val1" size=25 value= " "><br>

<input type=submit value="submit">
</form>
</body>
</html>


Program:1 (cookie program)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class cooke extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException
{

//value for the cookie is retrived

String nam=req.getParameter("nam");
String val=req.getParameter("val");

//first cookie is created

Cookie cookie1=new Cookie(nam,val);
res.addCookie(cookie1);

String nam1=req.getParameter("nam1");
String val1=req.getParameter("val1");

Cookie cookie2=new Cookie(nam1,val1);
res.addCookie(cookie2);

res.setContentType("text/html");

PrintWriter out=res.getWriter();

out.print("<b>Name of first cookie:</b>");
out.println(nam);
out.println("<br>");

out.print("<b>value of first cookie:</b>");
out.println(val);
out.println("<br>");

out.print("<b>Name of second cookie:</b>");
out.println(nam1);
out.println("<br>");

out.print("<b>value of second cookie:</b>");        
out.println(val1);
out.println("<br>");
out.close();
 }
}


program :2(html)

<html>
<body>
<form name="form1" method="post" action="http://localhost:8080/examples/servlet/priya">
<b> Choose one color:</b>
<select name="val" size="1">
<option value="pink">pink</option>
<option value="orange">orange</option>
<option value="red">red</option>
<option value="green">green</option>
<input type=submit value="submit">
</form>
</body>
</html>

program :2(cookie for above html)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.*;

public class priya extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{

//name for the cookie is retrived

String nam="choose one color";
String val=req.getParameter("val");
//first cookie is created

Cookie coo = new Cookie(nam,val);
res.addCookie(coo);
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println(nam);

if(val.equals("red"))
out.println("<html><body bgcolor='red'></body></html>");
if(val.equals("orange"))
out.println("<html><body bgcolor='orange'></body></html>");
if(val.equals("green"))
out.println("<html><body bgcolor='green'></body></html>");
if(val.equals("pink"))
out.println("<html><body bgcolor='pink'></body></html>");
out.close();
 }
}

No comments:

Post a Comment