Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
197 views

Department of Computer Science & Engineering: 08Csl77-Java and J2Ee Laboratory

The document contains a lab manual for a Java/J2EE laboratory course. It includes 5 programming assignments: 1. Demonstrate constructor and method overloading in a class. 2. Implement inheritance by creating a subclass that extends a superclass. 3. Create an interface and implement it in a class. Also create a thread class and change thread properties. 4. Create an applet to scroll text and pass parameters to an applet. 5. Use JDBC to insert into and retrieve from a student database using a Swing front-end.

Uploaded by

frd12345
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views

Department of Computer Science & Engineering: 08Csl77-Java and J2Ee Laboratory

The document contains a lab manual for a Java/J2EE laboratory course. It includes 5 programming assignments: 1. Demonstrate constructor and method overloading in a class. 2. Implement inheritance by creating a subclass that extends a superclass. 3. Create an interface and implement it in a class. Also create a thread class and change thread properties. 4. Create an applet to scroll text and pass parameters to an applet. 5. Use JDBC to insert into and retrieve from a student database using a Swing front-end.

Uploaded by

frd12345
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 50

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VII SEMESTER

08CSL77-JAVA and J2EE LABORATORY

LAB MANUAL
JAVA/J2EE LAB Department of CSE, NMIT

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();
  }
}
JAVA/J2EE LAB Department of CSE, NMIT

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

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).
JAVA/J2EE LAB Department of CSE, NMIT

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

public static void main(String args[]) {


try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}

PROGRAM 3:
JAVA/J2EE LAB Department of CSE, NMIT

(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 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);
}
JAVA/J2EE LAB Department of CSE, NMIT

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.
JAVA/J2EE LAB Department of CSE, NMIT

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

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 )
{
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);
}
}
JAVA/J2EE LAB Department of CSE, NMIT

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>

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.
JAVA/J2EE LAB Department of CSE, NMIT

*********************************************************************************************
// 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) {
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) {
JAVA/J2EE LAB Department of CSE, NMIT

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

5).Write a JAVA program to insert into Student database and retrieve info base
on particular queries (Using JDBC Design Front end using Swings).

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
class StudentDb extends JFrame implements ActionListener
{
JTextField studname,studreg,studcourse;
JLabel name,reg,course;
JFrame frame;
JButton save,exit;
Container contentPane;
StudentDb()
{
contentPane=getContentPane();
contentPane.setLayout(new FlowLayout());
frame=new JFrame("Student form");
name=new JLabel("Name");
reg=new JLabel("Register");
course=new JLabel("Course");
save=new JButton("Save");
exit=new JButton("Exit");
studname=new JTextField(15);
studreg=new JTextField(15);
studcourse=new JTextField(15);
frame.setSize(280,230);
Panel p1=new Panel();
Panel p2=new Panel();
Panel p3=new Panel();
Panel p4=new Panel();
Panel p5=new Panel();
p1.add(name);
p1.add(studname);
contentPane.add(p1);
p2.add(reg);
p2.add(studreg);
contentPane.add(p2);
p3.add(course);
p3.add(studcourse);
contentPane.add(p3);
JAVA/J2EE LAB Department of CSE, NMIT

contentPane.add(p5);
p4.add(save);
p4.add(exit);
contentPane.add(p4);
frame.getContentPane().add(contentPane,"Center");
save.addActionListener(this);
exit.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String str=ae.getActionCommand();
if(str.equals("save"));
{
String name=studname.getText();
String course=studcourse.getText();
String reg=studreg.getText();
System.out.println("save");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:van","scott","tiger");
Statement st=con.createStatement();
st.executeUpdate("insert into student12
values('"+name+"','"+course+"','"+reg+"')");
System.out.println("row inserted successfully");

}
catch(SQLException e)
{
}
catch(Exception e)
{
}
}
if(str.equals("Exit"));
System.exit(0);
}

public static void main(String args[])


{
StudentDb stu=new StudentDb();
stu.frame.setVisible(true);
stu.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Sql statement create table student12

Create table student12(name varchar2(10),course varchar2(10),


regno varchar2(10));
OUTPUT:
JAVA/J2EE LAB Department of CSE, NMIT

Save
row inserted successfully

Name Course RegNo


-------------------------------
Nidhi MBA 1117
Anusha MS 1120
Reena MCA 1000
Rohan MBA 1111
Vani MTech 1112
-------------------------------
JAVA/J2EE LAB Department of CSE, NMIT

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;

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
JAVA/J2EE LAB Department of CSE, NMIT

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());
} 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
JAVA/J2EE LAB Department of CSE, NMIT

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
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.*;
JAVA/J2EE LAB Department of CSE, NMIT

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
{
}

public String getMessage() throws RemoteException


{
return "Hello Krishna Kumar";
}

public void display() throws RemoteException


{
System.out.println("Hai how are you ");
}
JAVA/J2EE LAB Department of CSE, NMIT

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

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
JAVA/J2EE LAB Department of CSE, NMIT

8. Write a JAVA Servlet Program to implement a dynamic HTML using Servlet


(user name and password should be accepted using HTML and displayed
using a Servlet).

Servlet-1:-
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Myservlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body bgcolor='skyblue'>");
out.println("<form action='./apple' method='get'>");
out.println("Username:<input type='text' name='username'/>
<br /><br />");
out.println("Password:<input type='password' name='password'/>
<br /><br />");
out.println("<input type='submit' name='Login'/>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}

Servlet-2:-

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Myservlet1 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String name=req.getParameter("username");
String password=req.getParameter("password");
out.println("<html>");
out.println("<body bgcolor='skyblue'>");
out.println("The user name is:\t"+name);
out.println("<br />The password is is:\t"+password);
out.println("</body>");
out.println("</html>");
}
}
JAVA/J2EE LAB Department of CSE, NMIT

WEB -XML Part:-

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/orange</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Myservlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/apple</url-pattern>
</servlet-mapping>
<servlet>
</web-app>

OUTPUT:- http://localhost:7001/newapp-15/orange

out.println("<br />The password is is:\t"+password);


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

WEB -XML Part:-


JAVA/J2EE LAB Department of CSE, NMIT

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/orange</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Myservlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/apple</url-pattern>
</servlet-mapping>
<servlet>
</web-app>

OUTPUT:- http://localhost:7001/newapp-15/orange

out.println("<br />The password is is:\t"+password);


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

WEB -XML Part:-

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
JAVA/J2EE LAB Department of CSE, NMIT

<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/orange</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Myservlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/apple</url-pattern>
</servlet-mapping>
<servlet>
</web-app>

OUTPUT:- http://localhost:7001/newapp-15/orange

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;
JAVA/J2EE LAB Department of CSE, NMIT

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

}
JAVA/J2EE LAB Department of CSE, NMIT

}
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 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");
JAVA/J2EE LAB Department of CSE, NMIT

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

// 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{
JAVA/J2EE LAB Department of CSE, NMIT

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;

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

}
JAVA/J2EE LAB Department of CSE, NMIT

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 {

/**
* 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>");
JAVA/J2EE LAB Department of CSE, NMIT

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.
//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) {
JAVA/J2EE LAB Department of CSE, NMIT

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.
*/
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>
JAVA/J2EE LAB Department of CSE, NMIT

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

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


JAVA/J2EE LAB Department of CSE, NMIT

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

b) Write a JAVA Servlet Program to implement and demonstrate get() and Post
methods(Using HTTP Servlet Class).

Servlet Part:-

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Myservlet2 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
OException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body bgcolor='skyblue'>");
out.println("<form action='./mango' method='post'>");
out.println("username:<input type='text' name='username'/>
<br /><br />");
out.println("<input type='submit' name='submit'/>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}

public void doPost(HttpServletRequest req,HttpServletResponse res) throws


IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String name=req.getParameter("username");
out.println("<html>");
out.println("<body bgcolor='pink'>");
out.println("The user name is: " +name);
out.println("</body>");
out.println("</html>");
}

}
JAVA/J2EE LAB Department of CSE, NMIT

WEB- XML Part:-

</web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<servlet-class>Myservlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/mango</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:- http://localhost:7001/newapp-15/mango
JAVA/J2EE LAB Department of CSE, NMIT

WEB- XML Part:-

</web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<servlet-class>Myservlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/mango</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:- http://localhost:7001/newapp-15/mango

WEB- XML Part:-


JAVA/J2EE LAB Department of CSE, NMIT

</web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<servlet-class>Myservlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/mango</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:- http://localhost:7001/newapp-15/mango

PROGRAM 11: Write a java program to implement sendRedirect () method (using HTTP
servlet class).
WEB-XML Part:-

<web-app>
<servlet>
<servlet-name>god</servlet-name>
<servlet-class>Lab11</servlet-class>
JAVA/J2EE LAB Department of CSE, NMIT

</servlet>
<servlet-mapping>
<servlet-name>god</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

HTML Part:-

<html>
<body bgcolor='skyblue'>
<form action='../god1.do'>
<input type='text' name='username'></input>
<input type='submit' value='login'></input>
</form>
<form action='../god2.do'>
<input type='text' name='name'></input>
<input type='submit' value='go'></input>
</form>
</body>
</html>

JSP Part 1:-

<html>
<body bgcolor='skyblue'>
<%
String strname=request.getParameter("username");
%>
<%=strname%> you are in skyblue..
</body>
</html

JSP Part 2:-

<html>
<body bgcolor='skyblue'>
<%
String strname =request.getParameter("name");
response.sendRedirect("../JSP/11c.jsp");
%>
</body>
</html>

JSP Part 3:-


<html>
<body bgcolor='skyblue'>
<%
JAVA/J2EE LAB Department of CSE, NMIT

String strname=request.getParameter("name");
%>
<%=strname%> ur in nitte college..
</body>
</html>

Servlet Part:-

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Lab11 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletRespons res)
throws ServletException,IOException
{
System.out.println("!!!!!!!!!!!!!");
res.setContentType("text/html");
PrintWriter out= res.getWriter();
String s=req.getServletPath();
System.out.println("s is"+s);
if(s.equals("/god1.do"))
{
String strname=req.getParameter("username");
RequestDispatcher rd=req.
getRequestDispatcher("./JSP/11a.jsp");
rd.forward(req,res);
}

else if(s.equals("/god2.do"))
{
String strname1=req.getParameter("name");
RequestDispatcher rd=req.
getRequestDispatcher("./JSP/11b.jsp");
rd.forward(req,res);
}
}
}

OUTPUT:- http://localhost:7001/newapp/html/11.html
JAVA/J2EE LAB Department of CSE, NMIT

else if(s.equals("/god2.do"))
{
String strname1=req.getParameter("name");
RequestDispatcher rd=req.
getRequestDispatcher("./JSP/11b.jsp");
rd.forward(req,res);
}
}
}

OUTPUT:- http://localhost:7001/newapp/html/11.html
JAVA/J2EE LAB Department of CSE, NMIT

else if(s.equals("/god2.do"))
{
String strname1=req.getParameter("name");
RequestDispatcher rd=req.
getRequestDispatcher("./JSP/11b.jsp");
rd.forward(req,res);
}
}
}

OUTPUT:- http://localhost:7001/newapp/html/11.html
JAVA/J2EE LAB Department of CSE, NMIT

12. Write a JAVA Servlet Program to implement sessions (Using HTTP


session Interface).

WEB-XML Part:-

<web-app>

<servlet>
<servlet-name>rb</servlet-name>
<servlet-class> lab12 </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rb</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>

HTML Part:-

<html>
<head>
<title>lab12 program</title>
</head>
<body bgcolor='skyblue'><form action='../login.do'>
Enter Username:<input type='text' name='username'/><br /><br />
Enter Password:<input type='password' name='password'/><br /><br
/>
<input type='submit' value='Submit'/>
</form>
</body>
</html>

Servlet Part:-
JAVA/J2EE LAB Department of CSE, NMIT

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.*;
public class Lab12 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
HttpSession Session=req.getSession(true);
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String s=req.getServletPath();
System.out.println("S is "+s);
if(s.equals("/login.do"))
{
String username=req.getParameter("username");
String password=req.getParameter("password");
out.println("<html><head><title>12program</title></head>");
out.println("<body
bgcolor='skyblue'><formaction='./apple.do'>");
out.println("<table>");
out.println("<tr><td>Enter name:</td><td><input type='text'
name='name'></td></tr><br />");
out.println("<tr><td>Enter Addr:</td><td><input type='text'
name='addr'></td></tr><br />");
out.println("<tr><td>Enter phone no:</td><td><input
type='text'
name='phno'></td></tr><br />");
out.println("<tr><td>Enter mailid:</td><td><input type='text'
name='email'></td></tr><br />");
out.println("<input type='submit' value='register'>");
out.println("</form></table></body></html>");
}
else if(s.equals("/apple.do"))
{
String name=req.getParameter("name");
String addr=req.getParameter("addr");
String phno=req.getParameter("phno");
String email=req.getParameter("email");
Session.setAttribute("name",name);
Session.setAttribute("addr",addr);
Session.setAttribute("phno",phno);
Session.setAttribute("email",email);
out.println("<html><head></head>");
out.println("<body bgcolor='skyblue'>
<form ation='./orange.do'>");
out.println("<table>");
out.println("<tr><td>Enter empid:</td><td><input type='text'
name='empid'></td></tr><br />");
out.println("<tr><td>Enter salary :</td><td><input type='text'
name='salary'></td></tr><br />");
JAVA/J2EE LAB Department of CSE, NMIT

out.println("<tr><td>Enter designation:</td><td><input
type='text' name='design'></td></tr><br />");
out.println("<tr><td><input type='submit' value='submit'>");
out.println("</form></table></body></html>");
}

else if(s.equals("/orange.do"))
{

String empid=req.getParameter("empid");
String salary=req.getParameter("salary");
String design=req.getParameter("design");
Session.setAttribute("empid",empid);
Session.setAttribute("salary",salary);
Session.setAttribute("design",design);
String txt1=(String) Session.getAttribute("name");
String txt2=(String) Session.getAttribute("addr");
String txt3=(String) Session.getAttribute("phno");
String txt4=(String) Session.getAttribute("email");
String txt5=(String) Session.getAttribute("empid");
String txt6=(String) Session.getAttribute("salary");
String txt7=(String) Session.getAttribute("design");
out.println("<body bgcolor='skyblue'>");
out.println("<b>"+txt1+"<br/>"+txt2+"<br/>"+txt3+"<br/>
"+txt4+"<br/>"+txt5+"<br/>"+txt6+"<br/>"
+txt7+"</b>");
out.println("</body></html>");
}
}
}

OUTPUT:-

http://localhost:7001/newapp-14/html/lab12.html
JAVA/J2EE LAB Department of CSE, NMIT

13 a) Write a JAVA JSP Program to print 10 even and 10 odd number.

<html>
<head>
<title>odd &even no</title>
</head>
<body>
<%! int i=0; %>
<p><u>Even&Odd no</u></p>
<table border="5" bgcolor='skyblue'>
<tr>
<th> <u>EVEN</u></th>
<th><u>Odd</u></th>
</tr>
JAVA/J2EE LAB Department of CSE, NMIT

<% for(i=1;i<=20;i++){ %>


<tr>
<td>
<% if(i%2==0){%>
</td>
</tr>
<tr>
<td>
<%=i%>
</td>
<% }else{%>

<td>
<%=i%>
</td>
</tr>
<%} %>
<%}%>

</table>
</body>
</html>

OUTPUT:- http://localhost:7001/newapp-15/JSP/13a.jsp
JAVA/J2EE LAB Department of CSE, NMIT

13 b) Write a JAVA JSP Program to implement verification of a particular


user login and display a welcome page.

HTML Part:-

<html>
<head>
<title>13b program</title>
</head>
<body bgcolor='skyblue'>
JAVA/J2EE LAB Department of CSE, NMIT

<form action="../JSP/13b.jsp">
Username:<input type='text' name='username'/><br /><br />
Password:<input type='password' name='password'/><br /><br />
<input type='submit' name='Submit'/>
</form>
</body>
</html>

JSP Part:-

<html>
<body>
<% String strname=request.getParameter("username");
String strpassword=request.getParameter("password");

if(strname.equals("Mahesh")&&strpassword.equals("lalana")){%>
<%=strname%>
***Welcome Mahesh Welcome***
<%} else {%>
<%=strname%>
is nota member of RB'sfamily
<% }%>
</body>
</html>

OUTPUT:- http://localhost:7001/newapp-15/html/13b.html
JAVA/J2EE LAB Department of CSE, NMIT

14. Write a JAVA JSP Program to get student information through a HTML
and create a JAVA Bean Class, populate Bean and display the same
information through another JSP.

HTML Part:-

<html>
<body bgcolor="skyblue">
<form action='../JSP/14.jsp'>
<table>
<tr>
<th><b><font size='5'>Student Information</font></b></th>
</tr>
<tr>
<td>SID:</td><td><input type="text" name="sid"></td><br/><br/>
</tr>
<tr>
<td>NAME:</td><td><input type="text"
name="name"></td><br/><br/>
</tr>
<tr>
<td>MARKS:</td><td><input type="text"
name="marks"></td><br/><br/>
</tr>
<tr>
JAVA/J2EE LAB Department of CSE, NMIT

<td><input type="submit" value="send"></td>


</tr>
</table>
</form>
</body>
</html>

JSP Part:-

<%@page import="student.Student"%>
<jsp:usebean id="s1" class="student.Student" />
<jsp:setProperty name="s1" property="*" />
<html>
<body bgcolor="skyblue">
<h1>Student Information</h1>
<table border="5">
<tr>
<th>StudentId</th>
<th>StudentName</th>
<th>Marks</th>
</tr>
<tr>
<td><jsp:getProperty name="s1" property="sid"/></td>
<td><jsp:getProperty
name="s1"property="name"/></td>
<td><jsp:getProperty name="s1" property="marks"/></td>
</tr>
</table>
</body>
</html>

JAVA Part:-

package student;
public class Student implements java.io.Serializable
{
private int sid;
private String sname;
private int marks;
public void setSid(int sno)
{
this.sid=sno;
}
public int getSid()
{
return sid;
}
public void setName(String name)
{
this.sname=name;
}
public String getName()
JAVA/J2EE LAB Department of CSE, NMIT

{
return sname;
}
public void setMarks(int marks)
{
this.marks=marks;
}
public int getMarks()
{
return marks;
}
}

OUTPUT:- http://localhost:7001/newapp-18/html/14.html
JAVA/J2EE LAB Department of CSE, NMIT

OUTPUT:- http://localhost:7001/newapp-18/html/14.html
JAVA/J2EE LAB Department of CSE, NMIT

OUTPUT:- http://localhost:7001/newapp-18/html/14.html
JAVA/J2EE LAB Department of CSE, NMIT

You might also like