Department of Master of Computer Applications

download Department of Master of Computer Applications

of 26

Transcript of Department of Master of Computer Applications

  • 8/14/2019 Department of Master of Computer Applications

    1/24

    DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

    IV SEMESTER

    MCA07MCA46-JAVA and J2EE LABORATORY

    LAB MANUAL

  • 8/14/2019 Department of Master of Computer Applications

    2/24

    JAVA/J2EE LAB Department of MCA,

    PROGRAM 1

    (a)Write a java program to demonstrate constructor overloading and methodoverloading:

    **********************************************************************************************************class

    MyClass{ int height;

    MyClass() { System.out.println("Planting a seedling"); height = 0;}

    MyClass(int i) { System.out.println("Creating new Tree that is " + i + " feet tall"); height = i; }

    void info() { System.out.println("Tree is " + height + " feet tall"); }

    void info(String s) { System.out.println(s + ": Tree is " + height + " feet tall"); }}//end of main class

    public class MainClass { public static void main(String[] args) { MyClass t = new MyClass(0); t.info();

    t.info("overloaded method"); // Overloaded constructor: new MyClass(); }}

    PROGRAM 2(a)Write a java program to implement inheritance

    *********************************************************************************************class A {

    int i, j;

    void showij() {System.out.println("i and j: " + i + " " + j);

    }}

    // Create a subclass by extending class A.class B extends A {

    int k;

    void showk() {System.out.println("k: " + k);

    }void sum() {System.out.println("i+j+k: " + (i+j+k));

    }}

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    3/24

    JAVA/J2EE LAB Department of MCA,

    class SimpleInheritance {

    public static void main(String args[]) {A superOb = new A();B subOb = new B();

    // The superclass may be used by itself.

    superOb.i = 10;superOb.j = 20;System.out.println("Contents of superOb: ");superOb.showij();System.out.println();

    /* The subclass has access to all public members ofits superclass. */

    subOb.i = 7;subOb.j = 8;subOb.k = 9;System.out.println("Contents of subOb: ");subOb.showij();subOb.showk();System.out.println();

    System.out.println("Sum of i, j and k in subOb:");subOb.sum();

    }}

    (b)Write a java program to implement Exception Handling (using Nested try catchand finally).

    ***********************************************************************************

    ****************class FinallyDemo {// Through an exception out of the method.static void procA() {try {System.out.println("inside procA");throw new RuntimeException("demo");

    } finally {System.out.println("procA's finally");

    }}

    // Return from within a try block.

    static void procB() {try {System.out.println("inside procB");return;

    } finally {System.out.println("procB's finally");

    }}

    // Execute a try block normally.static void procC() {try {System.out.println("inside procC");

    } finally {System.out.println("procC's finally");

    }}

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    4/24

    JAVA/J2EE LAB Department of MCA,

    public static void main(String args[]) {try {procA();

    } catch (Exception e) {System.out.println("Exception caught");

    }

    procB();procC();

    }}

    PROGRAM 3:(a)Write a java program to create an interface and implement it in class

    **********************************************************************************************************

    interface Area{

    final static float pi=3.14F;float compute(float x, float y);}

    class Rectangle implements Area{public float compute(float x, float y){return(x*y);}

    }

    class Circle implements Area

    {

    public float compute(float x, float y){return(pi*x*y);

    }}

    class InterfaceTest{public static void main(String args[]){Rectangle rect=new Rectangle();

    Circle cir=new Circle();Area area;area rect;System.out.println("Area of Rectangle = " +area.compute(10,20));area=cir;System.out.println("Area of Circle = " +area.compute(10,0));}

    }

    (b)Write a java program to create a class (extending thread) and use methodsthread class to change name, priority, --- of the current thread and display the

    same.

    **********************************************************************************************************class clicker implements Runnable {

    int click = 0;

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    5/24

    JAVA/J2EE LAB Department of MCA,

    Thread t;private volatile boolean running = true;

    public clicker(int p) {t = new Thread(this);t.setPriority(p);

    }

    public void run() {while (running) {click++;

    }}

    public void stop() {running = false;

    }

    public void start() {t.start();

    }}

    class HiLoPri {public static void main(String args[]) {Thread.currentThread().setPriority(Thread.MAX_PRIORITY);clicker hi = new clicker(Thread.NORM_PRIORITY + 2);clicker lo = new clicker(Thread.NORM_PRIORITY - 2);

    lo.start();hi.start();try {

    Thread.sleep(10000);} catch (InterruptedException e) {System.out.println("Main thread interrupted.");

    }

    lo.stop();hi.stop();

    // Wait for child threads to terminate.try {hi.t.join();lo.t.join();

    } catch (InterruptedException e) {

    System.out.println("InterruptedException caught");}

    System.out.println("Low-priority thread: " + lo.click);System.out.println("High-priority thread: " + hi.click);

    }}

    PROGRAM 4(a) : Create an Applet to Scroll a Text Message.

    **********************************************************************************************************

    Code to create an applet to scroll a text message.

    /*

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    6/24

    JAVA/J2EE LAB Department of MCA,

    */

    import java.awt.*;import java.applet.*;

    public class AppletBanner extends Applet implements Runnable{

    String str;int x,y;

    public void init(){

    str="WELCOME TO RNSIT";x=300;new Thread(this).start();

    }

    public void run(){

    try{

    while(true){

    x=x-10;if(x < 0 ){

    x=300;}repaint();

    System.out.println(x);Thread.sleep(1000);}

    } catch(Exception e){}}

    public void paint(Graphics g){

    for(int i=0;ijavac AppletBanner.java

    E:\j2sdk1.4.0\bin>appletviewer AppletBanner.java290280270260250240

    230220210200

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    7/24

    JAVA/J2EE LAB Department of MCA,

    190180170160150140130120110100908070605040

    E:\j2sdk1.4.0\bin>

    Two instances of the applet : one at the value x = 210 and second at x = 50

    (b) Write a java program to pass parameters to applets and display the same.

    *********************************************************************************************// Use Parametersimport java.awt.*;import java.applet.*;/*

    */

    public class ParamDemo extends Applet{String fontName;int fontSize;float leading;boolean active;

    // Initialize the string to be displayed.public void start() {String param;

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    8/24

    JAVA/J2EE LAB Department of MCA,

    fontName = getParameter("fontName");if(fontName == null)fontName = "Not Found";

    param = getParameter("fontSize");try {

    if(param != null) // if not foundfontSize = Integer.parseInt(param);

    elsefontSize = 0;

    } catch(NumberFormatException e) {fontSize = -1;

    }

    param = getParameter("leading");try {if(param != null) // if not foundleading = Float.valueOf(param).floatValue();

    elseleading = 0;

    } catch(NumberFormatException e) {leading = -1;

    }

    param = getParameter("accountEnabled");if(param != null)active = Boolean.valueOf(param).booleanValue();

    }

    // Display parameters.public void paint(Graphics g) {

    g.drawString("Font name: " + fontName, 0, 10);g.drawString("Font size: " + fontSize, 0, 26);g.drawString("Leading: " + leading, 0, 42);g.drawString("Account Active: " + active,0,58);

    }}

    PROGRAM 6: Writea Java Program to implement Client Server( Client requests afile, Server responds to client with contents of that file which is then display onthe screen by Client Socket Programming).

    *********************************************************************

    Code for Client Program.

    import java.net.*;import java.util.*;import java.io.*;

    public class Client{

    public static void main(String args[]){

    Socket client=null;BufferedReader br=null;try{

    System.out.println(args[0] + " " + args[1]);client=new Socket(args[0],Integer.parseInt(args[1]));

    } catch(Exception e){}

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    9/24

    JAVA/J2EE LAB Department of MCA,

    DataInputStream input=null;PrintStream output=null;

    try{

    input=new DataInputStream(client.getInputStream());

    output=new PrintStream(client.getOutputStream());br=new BufferedReader(new

    InputStreamReader(System.in));

    String str=input.readLine();//get the prompt from the serverSystem.out.println(str); // display the prompt on the client

    machine

    String filename=br.readLine();if(filename!=null)

    output.println(filename);

    String data;while((data=input.readLine())!=null)

    System.out.println(data);

    client.close();}catch(Exception e){

    System.out.println(e);}

    }}

    Code for Server Program.

    import java.net.*;import java.io.*;import java.util.*;

    public class Server{

    public static void main(String args[]){

    ServerSocket server=null;

    try{

    server=new ServerSocket(Integer.parseInt(args[0]));}catch(Exception e){}

    while(true){

    Socket client=null;PrintStream output=null;DataInputStream input=null;try{

    client=server.accept();} catch(Exception e){ System.out.println(e);}try

    {output=new PrintStream(client.getOutputStream());input=new

    DataInputStream(client.getInputStream());

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    10/24

    JAVA/J2EE LAB Department of MCA,

    } catch(Exception e){ System.out.println(e);}

    // send the command prompt to the clientoutput.println("ENTER THE FILE NAME >");

    try{

    // get the file name from the clientString filename=input.readLine();System.out.println("Client requested file: " + filename);

    try{

    File f=new File(filename);BufferedReader br=new BufferedReader(new

    FileReader(f));String data;

    while((data=br.readLine()) != null){

    output.println(data);}}

    catch(FileNotFoundException e){ output.println("FILE NOT FOUND"); }

    client.close();}catch(Exception e){System.out.println(e);}

    }

    }}

    OUTPUT :

    Run Server Program first and then Client Program

    Output of Server :E:\j2sdk1.4.0\bin>javac Server.javaNote: Server.java uses or overrides a deprecated API.Note: Recompile with -deprecation for details.

    E:\j2sdk1.4.0\bin>javac -d Server.java

    E:\j2sdk1.4.0\bin>java Server 4000Client requested file: gra.javaClient requested file: kk.txt^CE:\j2sdk1.4.0\bin>

    Output of Client :

    E:\j2sdk1.4.0\bin>javac Client.javaNote: Client.java uses or overrides a deprecated API.Note: Recompile with -deprecation for details.

    E:\j2sdk1.4.0\bin>javac -d Client.java

    E:\j2sdk1.4.0\bin>java Client localhost 4000localhost 4000ENTER THE FILE NAME >gra.javaimport java.awt.*;

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    11/24

    JAVA/J2EE LAB Department of MCA,

    import java.applet.*;

    public class gra extends Applet{

    public void paint(Graphics g){

    g.drawRect(10,10,700,500);}

    }

    E:\j2sdk1.4.0\bin>java Client localhost 4000localhost 4000ENTER THE FILE NAME >kk.txtFILE NOT FOUND

    E:\j2sdk1.4.0\bin>

    PROGRAM 7 : Write a Java Program to implement the Simple Client / ServerApplication using RMI .

    **********************************************************************************************************

    Code for Remote Interface.

    import java.rmi.*;

    public interface HelloInterface extends Remote{

    public String getMessage() throws RemoteException;

    public void display() throws RemoteException;

    }

    Code for Server.

    import java.rmi.*;import java.rmi.server.*;

    public class HelloServerImpl extends unicastRemoteobject implementsHelloInterface{

    public HelloServerImpl() throws RemoteException

    {}

    public String getMessage() throws RemoteException{

    return "Hello Krishna Kumar";}

    public void display() throws RemoteException{

    System.out.println("Hai how are you ");}

    public static void main (String args[]){

    try{HelloServerImpl Server = new HelloServerImpl();

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    12/24

    JAVA/J2EE LAB Department of MCA,

    Naming.rebind("rmi://localhost:1099/Server",Server);

    }catch(Exception e){}}

    }

    Code for Client.

    import java.rmi.*;

    public class HelloClient{

    public static void main(String args[]){

    try{HelloInterface Server =

    (HelloInterface)Naming.lookup("rmi://localhost:1099/Server");

    String msg = Server.getMessage();

    System.out.println(msg);

    Server.display();

    }catch(Exception e){}}

    }

    OUTPUT :

    E:\j2sdk1.4.0\bin>javac HelloInterface.java

    E:\j2sdk1.4.0\bin>javac HelloServerImpl.java

    E:\j2sdk1.4.0\bin>javac HelloClient.java

    E:\j2sdk1.4.0\bin>rmic HelloServerImp

    E:\j2sdk1.4.0\bin>start rmiregistry // Opens a New Window

    E:\j2sdk1.4.0\bin>java HelloServerImpl // Run in the New Window

    E:\j2sdk1.4.0\bin>java HelloClient // Run in New WindowHello Krishna Kumar

    Server Window Output

    Hai how are you

    PROGRAM 8: Write a java program to implement a dynamic HTML using Servlet(user name and password should be accepted using HTML and displayed using aServlet).

    **********************************************************************************************************

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

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    13/24

    JAVA/J2EE LAB Department of MCA,

    public class prg 7 extends HttpServlet{

    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException

    {PrintWriter out=res.getWriter();

    out.println("");out.println("Program 15 ");out.println("");

    out.println("User Information");out.println("

    ");

    out.println("

  • 8/14/2019 Department of Master of Computer Applications

    14/24

    JAVA/J2EE LAB Department of MCA,

    ForwardedServletimport java.io.IOException;import java.util.Enumeration;

    import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;

    import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

    /* This servlet generates full response page. In this example, this servlet is calledby TestForwardedServlet. Servlets with this kind of logic, could also be calledrequested direcly by the client,but it may not serve its actual purpose.* /

    public class ForwardedServlet extends HttpServlet {

    /*** This methods generates response page for the caller's servlet/jsp.* It also tries to get the param value that was stored by caller.* Since the foward happens within one single request, values stored in

    caller can be retrieved* in the called resource.** @param req HttpServletRequest This object is created by

    servletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet containerand is used to return data/ reponse to the client.

    * @exception ServletException This is thrown if the request processing couldnot be handled.

    * @exception IOException IOException encountered while processing request.*/

    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {//getting parameter.System.out.println("*********** inside GET method of Forwarded

    Servlet");

    PrintWriter write = res.getWriter();write.println("");write.println("");write.println("");write.println("");write.println(" Printing Header Names and Values
    ");// Retrieving Header names and values.

    Enumeration headerNames = req.getHeaderNames();while (headerNames.hasMoreElements()) {

    String header = (String) headerNames.nextElement();String value = req.getHeader(header);write.println("HeaderName : "+header+" And Value :

    "+value +"
    ");}

    write.println(" Printing request attribute forwarded by otherServlet
    ");

    String attributeValue = (String)req.getAttribute("attribute");write.println(" attribute value from TestForwardedServlet :" +

    attributeValue);

    write.println("");write.println("");

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    15/24

    JAVA/J2EE LAB Department of MCA,

    }

    }import java.io.IOException;import javax.servlet.ServletException;

    import javax.servlet.RequestDispatcher;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

    /*** This servlet shows how a servlet/jsp could forward the request at run time using

    RequestDispatcher.* It also shows how RequestDispatcher instance could be obtained using

    HttpServletRequest and ServletContext.**/

    public class TestForwardServlet extends HttpServlet {

    /*** This methods forwards request to the ForwardedServlet. Before

    forwarding, it adds a value to request object,* which is retrieved in the ForwardedServlet.* It should be ensured that the caller (TestForwardServlet) should not

    have comitted the response before* forwarding the request, doing so you will get Exception. In case of

    include action for the example* TestIncludeServlet the response could have been comitted in the caller

    before calling include() method.

    * RequestDispatcher is used to forward the request to theForwardedServlet, This method shows both ways of getting* RequestDispatcher.** @param req HttpServletRequest This object is created by

    servletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet containerand is used to return data/ reponse to the client.

    * @exception ServletException This is thrown if the request processing couldnot be handled.

    * @exception IOException IOException encountered while processing request.*/

    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {

    //getting parameter.System.out.println("*********** inside GET method of

    TestForwardServlet");

    req.setAttribute("attribute", "value");

    dispatchFromRequest(req, res);

    System.out.println("This will not print");//req.setAttribute("attribute", "value");

    //dispatchFromServletContext(req, res);}

    /**

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    16/24

    JAVA/J2EE LAB Department of MCA,

    * It gets RequestDispatcher using HttpServletRequest and forwards therequest to the ForwardedServlet,

    * calling "forward()" method. HttpServletRequest's getRequestDispatchermethod can take param with resource path

    * either being relative or absolute. forward() method will not delegate therequest back to the caller.

    *

    * @param req HttpServletRequest This object is created byservletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet containerand is used to return data/ reponse to the client.

    * @exception ServletException This is thrown if the equest processing couldnot be handled.

    */public void dispatchFromRequest(HttpServletRequest req,

    HttpServletResponse res) throws ServletException {

    // This shows both relative and absolute method could be used toforward the request.

    //RequestDispatcher dispatch =req.getRequestDispatcher("/testweb/ForwardedServlet");

    RequestDispatcher dispatch =req.getRequestDispatcher("ForwardedServlet");

    try {dispatch.forward(req, res);

    } catch (Exception e) {throw new ServletException("Exception while forwarding the

    request ");}

    }

    /*** It gets RequestDispatcher using ServletContext and forwards therequest to the ForwardedServlet,

    * calling "forward()" method. ServletContext's getRequestDispatchermethod can take param with resource path

    * being only absolute.forward() method will not delegate the request backto the caller resource.

    ** @param req HttpServletRequest This object is created by

    servletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet containerand is used to return data/ reponse to the client.

    * @exception ServletException This is thrown if the equest processing couldnot be handled.

    */public void dispatchFromServletContext(HttpServletRequest req,

    HttpServletResponse res) throws ServletException{

    RequestDispatcher dispatch =getServletContext().getRequestDispatcher("/testweb/ForwardedServlet");

    try {dispatch.forward(req, res);

    } catch (Exception e) {throw new ServletException("Exception while forwarding the

    request ");

    }}

    }

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    17/24

    JAVA/J2EE LAB Department of MCA,

    IncludeServletimport java.io.IOException;

    import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

    /*** This servlet generates only part of the response page. In this example this

    servlet is called by TestIncludeServlet.* Servlets with this kind of logic, could also be called requested direcly by the

    client,* but it may not serve its actual purpose.**/

    public class IncludedServlet extends HttpServlet {

    /*** This methods generates part of o/p response for the caller's servlet/jsp.* It also tries to get the param value that was stored by caller.* Since the delagate happens within one single request, values stored in

    caller can be* retrieved in the called resource.** @param req HttpServletRequest This object is created by

    servletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet container

    and is used to return data/ reponse to the client.* @exception ServletException This is thrown if the request processing could

    not be handled.* @exception IOException IOException encountered while processing request.

    */public void doGet(HttpServletRequest req, HttpServletResponse res)

    throws ServletException, IOException {System.out.println("*********** inside GET method of Included

    Servlet");// retrive value that was stored in caller servlet.String attributeValue = (String)req.getAttribute("attribute");PrintWriter write = res.getWriter();write.println(" attribute value from TestIncludeServlet :" +

    attributeValue);

    }

    }

    import java.io.IOException;import java.io.PrintWriter;

    import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

    /**

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    18/24

    JAVA/J2EE LAB Department of MCA,

    * This servlet shows how a servlet/jsp could be included at the run time usingRequestDispatcher.* It also shows how RequestDispatcher instance could be obtained using

    HttpServletRequest and ServletContext.**/

    public class TestIncludeServlet extends HttpServlet {

    /*** This methods generates the o/p response partially for the request and

    delegate the request to IncludedServlet.* It also adds a value to request object, which is retrieved in the

    IncludedServlet, and IncludedServlet adds* that value in the response it generates.The response generated by

    IncludedServlet will be appened* to response which TestIncludeServlet already generated, finally the

    request will be delegated back to* TestIncludeServlet which completes the request process.* RequestDispatcher is used to delgate the request to the IncludedServlet,

    This method shows both ways of getting* RequestDispatcher.** @param req HttpServletRequest This object is created by

    servletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet containerand is used to return data/ reponse to the client.

    * @exception ServletException This is thrown if the request processing couldnot be handled.

    * @exception IOException IOException encountered while processing request.*/

    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {System.out.println("*********** inside GET method of

    TestIncludeServlet");

    PrintWriter write = res.getWriter();// generating the response page with data provided by the request

    object.write.println("");write.println("");write.println("");write.println("");String searchString = req.getParameter("searchstring");

    String[] stateList = req.getParameterValues("state");write.println(" Your search String :" + searchString +"
    ");write.println(" Your Selected states
    ");

    for (int i=0; i

  • 8/14/2019 Department of Master of Computer Applications

    19/24

    JAVA/J2EE LAB Department of MCA,

    // this method uses ServletContext object to get theRequestDispatcher.

    // comment this line if you calling dispatchFromRequest.//dispatchFromServletContext(req, res);

    write.println("");

    write.println("");

    }

    /*** It gets RequestDispatcher using HttpServletRequest and delegate the

    request to the IncludedServlet,* calling "include()" method. HttpServletRequest's getRequestDispatcher

    method can take param with resource path* either being relative or absolute. include() method will delegate the

    request back to the caller.** @param req HttpServletRequest This object is created by

    servletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet containerand is used to return data/ reponse to the client.

    * @exception ServletException This is thrown if the equest processing couldnot be handled.

    */public void dispatchFromRequest(HttpServletRequest req,

    HttpServletResponse res) throws ServletException {RequestDispatcher dispatch =

    req.getRequestDispatcher("IncludedServlet");

    try {

    dispatch.include(req, res);

    } catch (Exception e) {throw new ServletException("Exception while delegating the

    request ");

    }

    }

    /*** It gets RequestDispatcher using ServletContext and delegate the

    request to the IncludedServlet,* calling "include()" method. ServletContext's getRequestDispatcher

    method can take param with resource path* being only absolute.include() method will delegate the request back to

    the caller resource.** @param req HttpServletRequest This object is created by

    servletcontainer and holds the data and header information obtained from theclient.

    * @param res HttpServletResponse This object is created by servlet container

    and is used to return data/ reponse to the client.* @exception ServletException This is thrown if the equest processing could

    not be handled.*/

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    20/24

    JAVA/J2EE LAB Department of MCA,

    public void dispatchFromServletContext(HttpServletRequest req,HttpServletResponse res) throws ServletException {

    RequestDispatcher dispatch =getServletContext().getRequestDispatcher("/IncludedServlet");

    try {

    dispatch.include(req, res);} catch (Exception e) {

    throw new ServletException("Exception while delegating therequest ");

    }}

    }

    (b) Write a java program to implement and demonstrate get () and post ()methods (using HTTP servlet class).get () methods

    Color:RedGreenBlue

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

    public class ColorGetServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException {

    String color = request.getParameter("color");response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("The selected color is: ");pw.println(color);pw.close();

    }}

    Post () methods

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    21/24

    JAVA/J2EE LAB Department of MCA,

    Color:RedGreenBlue

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

    public class ColorPostServlet extends HttpServlet {

    public void doPost(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException {

    String color = request.getParameter("color");response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("The selected color is: ");pw.println(color);pw.close();

    }}

    PROGRAM 11: Write a java program to implement sendRedirect () method (using

    HTTP servlet class)./**

    RedirectNewLocationRedirectNewLocation

    RedirectNewLocation/RedirectNewLocation

    * */

    importjava.io.IOException;importjava.io.PrintWriter;

    importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

    public class RedirectNewLocation extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", "http://www.java2s.com");

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    22/24

    JAVA/J2EE LAB Department of MCA,

    response.setContentType("text/html"); return; }}

    importjava.io.IOException;importjava.io.PrintWriter;

    importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

    public class RedirectWithLinkServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    response.setContentType("text/html"); out.println(""); out.println("Java Source and Support
    "); out.println("Click here"); out.println("");

    return; }}

    Servlet: URL rewrite:

    importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

    public class UrlRewrite extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

    response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); String contextPath = request.getContextPath();

    String encodedUrl = response.encodeURL(contextPath + "/default.jsp");

    out.println(""); out.println(""); out.println("URL Rewriter"); out.println(""); out.println(""); out.println("This page will use URL rewriting if necessary"); out.println("Go to the default.jsp page here."); out.println(""); out.println("");

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    23/24

    JAVA/J2EE LAB Department of MCA,

    doGet(request, response);

    }}

    PROGRAM 12: Write a java program to implement sessions (using HTTP session

    interface).

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

    public class Sessions extends HttpServlet{

    public void doGet(HttpServletRequest req, HttpServletResponse res)

    throws ServletException,IOException{PrintWriter out=res.getWriter();out.println("");

    out.println("Sessions ");out.println("");

    out.println("Session Creation and Display");out.println("

    ");

    HttpSession session=req.getSession(true);out.println("Session ID: &nbsp"+session.getId());

    out.println("

    Session Created on:");out.println(new Date(session.getCreationTime()));

    out.println("

    Session Last accessed: ");out.println(new Date(session.getLastAccessedTime()));

    out.println("

    Creation of New Sessionattribute");

    out.println("");out.println("
    Name of the session Attribute:");out.println(" ");out.println("
    Value of the session Attribute:");

    out.println(" ");out.println("
    ");out.println("");

    out.println("");out.println("The Session Values:");

    String attName = req.getParameter("attname");String attValue = req.getParameter("attvalue");if (attName != null && attValue != null) {

    req.setAttribute(attName, attValue);

    }

    Enumeration names = req.getAttributeNames();while (names.hasMoreElements()) {

    String name = (String) names.nextElement();

    Page No : 1

  • 8/14/2019 Department of Master of Computer Applications

    24/24

    JAVA/J2EE LAB Department of MCA,

    String value = req.getAttribute(name).toString();out.println(name + " = " + value + "
    ");

    }

    out.println("");out.println("");

    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException{

    doGet(req, res);

    }}