26
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS IV SEMESTER MCA07MCA46-JAVA and J2EE LABORATORY LAB MANUAL

J2EE Lab Manual

Embed Size (px)

Citation preview

Page 1: J2EE Lab Manual

DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

IV SEMESTER

MCA07MCA46-JAVA and J2EE LABORATORY

LAB MANUAL

Page 2: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 27

PROGRAM 1

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

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

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() {

Page 3: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 28

System.out.println("k: " + k);

}

void sum() {

System.out.println("i+j+k: " + (i+j+k));

}

}

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 of

its 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 catch and

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;

Page 4: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 29

} 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");

}

}

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

{

Page 5: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 30

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 methods thread class to

change name, priority, --- of the current thread and display the same.

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

class clicker implements Runnable {

int click = 0;

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.");

Page 6: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 31

}

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.

/*

<applet code=AppletBanner width=300 height=200>

</applet>

*/

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 )

Page 7: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 32

{

x=300;

}

repaint();

System.out.println(x);

Thread.sleep(1000);

}

} catch(Exception e){}

}

public void paint(Graphics g)

{

for(int i=0;i<10;i++)

g.drawString(str,x,100);

}

}

OUTPUT :

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

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

290

280

270

260

250

240

230

220

210

200

190

180

170

160

150

140

130

120

110

100

90

80

70

60

50

40

E:\j2sdk1.4.0\bin>

Page 8: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 33

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 Parameters

import java.awt.*;

import java.applet.*;

/*

<applet code="ParamDemo" width=300 height=80>

<param name=fontName value=Courier>

<param name=fontSize value=14>

<param name=leading value=2>

<param name=accountEnabled value=true>

</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;

fontName = getParameter("fontName");

if(fontName == null)

fontName = "Not Found";

param = getParameter("fontSize");

try {

if(param != null) // if not found

fontSize = Integer.parseInt(param);

else

fontSize = 0;

} catch(NumberFormatException e) {

Page 9: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 34

fontSize = -1;

}

param = getParameter("leading");

try {

if(param != null) // if not found

leading = Float.valueOf(param).floatValue();

else

leading = 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: Write a Java Program to implement Client Server( Client requests a file,

Server responds to client with contents of that file which is then display on the 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){}

DataInputStream input=null;

PrintStream output=null;

Page 10: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 35

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 server

System.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());

Page 11: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 36

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

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

// send the command prompt to the client

output.println("ENTER THE FILE NAME >");

try

{

// get the file name from the client

String 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.java

Note: 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 4000

Client requested file: gra.java

Client requested file: kk.txt

^C

E:\j2sdk1.4.0\bin>

Output of Client :

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

Page 12: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 37

Note: 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 4000

localhost 4000

ENTER THE FILE NAME >

gra.java

import java.awt.*;

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 4000

localhost 4000

ENTER THE FILE NAME >

kk.txt

FILE NOT FOUND

E:\j2sdk1.4.0\bin>

PROGRAM 7 : Write a Java Program to implement the Simple Client / Server Application

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 implements HelloInterface

{

public HelloServerImpl() throws RemoteException

{

}

Page 13: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 38

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();

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

Page 14: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 39

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 Window

Hello 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 a Servlet).

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

import java.lang.*;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class prg 7 extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException,IOException

{

PrintWriter out=res.getWriter();

out.println("<html>");

out.println("<head><title>Program 15 </title></head>");

out.println("<body>");

out.println("<h1>User Information</h1>");

out.println("<br><hr><br>");

out.println("<form method=post action=/servlets-examples/prg15");

out.println("Dear User.<br>");

out.println("Please Enter the following Information.<br><br>");

out.println("UserName: <input type=text name=username

value=\"\"><br><br>");

out.println("Address: <input type=text name=address value=\"\"><br><br>");

out.println("<input type=submit value=Submit><input type=reset

value=Clear>");

out.println("</form>");

out.println("</body></html>");

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException,IOException

{

PrintWriter out=res.getWriter();

Page 15: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 40

String username=req.getParameter("username");

String address=req.getParameter("address");

out.println("<html>");

out.println("<head><title>Program 7 </title></head>");

out.println("<body>");

out.println("<h1>User Information</h1>");

out.println("<br><hr><br>");

out.println("Dear User.<br>");

out.println("Your Information.<br><br>");

out.println("UserName: "+username+"<br>");

out.println("Address :"+address+"<br>");

out.println("<br><center><a href=/servlets-examples/prg15>Back</a></center>");

out.println("</body>");

out.println("</html>");

}

}

PROGRAM 10:

(a) Write a servlet program to implement RequestDispatcher object (use include () and

forward () methods ()

ForwardedServlet

import 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 called by

TestForwardedServlet. 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 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 the client.

* @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.

Page 16: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 41

* @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("<html>");

write.println("<head>");

write.println("</head>");

write.println("<body>");

write.println(" Printing Header Names and Values <br>");

// 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 +"

<br>");

}

write.println(" Printing request attribute forwarded by other Servlet<br>");

String attributeValue = (String)req.getAttribute("attribute");

write.println(" attribute value from TestForwardedServlet :" +

attributeValue);

write.println("</body>");

write.println("</html>");

}

}

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 {

/**

Page 17: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 42

* 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 the ForwardedServlet, 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 the client.

* @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 {

//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);

}

/**

* It gets RequestDispatcher using HttpServletRequest and forwards the request to

the ForwardedServlet,

* calling "forward()" method. HttpServletRequest's getRequestDispatcher method

can take param with resource path

* either being relative or absolute. forward() method will not 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 the client.

* @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.

*/

public void dispatchFromRequest(HttpServletRequest req, HttpServletResponse res)

throws ServletException {

Page 18: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 43

// This shows both relative and absolute method could be used to forward 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 the request to the

ForwardedServlet,

* calling "forward()" method. ServletContext's getRequestDispatcher method can

take param with resource path

* being only absolute.forward() method will not 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 the client.

* @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.

*/

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 ");

}

}

}

IncludeServlet

import 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;

Page 19: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 44

/**

* 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 the client.

* @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;

/**

* This servlet shows how a servlet/jsp could be included at the run time using

RequestDispatcher.

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

and ServletContext.

*

*/

public class TestIncludeServlet extends HttpServlet {

Page 20: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 45

/**

* 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 the client.

* @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 TestIncludeServlet");

PrintWriter write = res.getWriter();

// generating the response page with data provided by the request object.

write.println("<html>");

write.println("<head>");

write.println("</head>");

write.println("<body>");

String searchString = req.getParameter("searchstring");

String[] stateList = req.getParameterValues("state");

write.println(" Your search String :" + searchString +" <br>");

write.println(" Your Selected states <br>");

for (int i=0; i<stateList.length; i++) {

write.println( stateList[i] + "<br>");

}

// sets a request attribute to show how it could be retrieved in

IncludedServlet.

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

// this method uses HttpServletRequest object to get the RequestDispatcher.

// comment this line if you calling dispatchFromServletContext.

dispatchFromRequest(req, res);

// this method uses ServletContext object to get the RequestDispatcher.

// comment this line if you calling dispatchFromRequest.

Page 21: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 46

//dispatchFromServletContext(req, res);

write.println("</body>");

write.println("</html>");

}

/**

* 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 the client.

* @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.

*/

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 the client.

* @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 22: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 47

*/

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 the request

");

}

}

}

(b) Write a java program to implement and demonstrate get () and post () methods (using

HTTP servlet class).

get () methods

<html>

<body>

<center>

<form name="Form1"

action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet">

<B>Color:</B>

<select name="color" size="1">

<option value="Red">Red</option>

<option value="Green">Green</option>

<option value="Blue">Blue</option>

</select>

<br><br>

<input type=submit value="Submit">

</form>

</body>

</html>

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("<B>The selected color is: ");

pw.println(color);

pw.close();

}

Page 23: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 48

}

Post () methods

<html>

<body>

<center>

<form name="Form1"

method="post"

action="http://localhost:8080/servlets-examples/servlet/ColorPostServlet">

<B>Color:</B>

<select name="color" size="1">

<option value="Red">Red</option>

<option value="Green">Green</option>

<option value="Blue">Blue</option>

</select>

<br><br>

<input type=submit value="Submit">

</form>

</body>

</html>

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("<B>The selected color is: ");

pw.println(color);

pw.close();

}

}

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

servlet class).

/*

* <servlet>

<servlet-name>RedirectNewLocation</servlet-name>

<servlet-class>RedirectNewLocation</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>RedirectNewLocation</servlet-name>

<url-pattern>/RedirectNewLocation</url-pattern>

</servlet-mapping>

Page 24: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 49

* */

import 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;

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");

response.setContentType("text/html");

return;

}

}

import 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;

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("<html><body>");

out.println("<H1>Java Source and Support</H1><BR>");

out.println("<a href=\"http://www.java2s.com\">Click here</a>");

out.println("</body></html>");

return;

}

}

Servlet: URL rewrite:

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

Page 25: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 50

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("<html>");

out.println("<head>");

out.println("<title>URL Rewriter</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>This page will use URL rewriting if necessary</h2>");

out.println("Go to the default.jsp page <a href=\"" + encodedUrl

+ "\">here</a>.");

out.println("</body>");

out.println("</html>");

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, java.io.IOException {

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("<html>");

out.println("<head><title>Sessions </title></head>");

out.println("<body>");

out.println("<h2>Session Creation and Display</h2>");

Page 26: J2EE Lab Manual

JAVA/J2EE LAB Department of MCA, TOCE

Page No : 51

out.println("<br><hr><br>");

HttpSession session=req.getSession(true);

out.println("Session ID: &nbsp"+session.getId());

out.println("<br><br>Session Created on:");

out.println(new Date(session.getCreationTime()));

out.println("<br><br>Session Last accessed: ");

out.println(new Date(session.getLastAccessedTime()));

out.println("<br><hr><br><h3> Creation of New Session attribute</h3>");

out.println("<form method=post action=/servlets-examples/prg13>");

out.println("<br>Name of the session Attribute:");

out.println(" <input type=text name=attname value=\"\">");

out.println("<br>Value of the session Attribute:");

out.println(" <input type=text name=attvalue value=\"\">");

out.println("<br><input type=submit value=Submit><input type=reset

name=CLear>");

out.println("</form>");

out.println("<hr>");

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();

String value = req.getAttribute(name).toString();

out.println(name + " = " + value + "<br>");

}

out.println("</body>");

out.println("</html>");

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException,IOException

{

doGet(req, res);

}

}