You are on page 1of 31

Program-5

Objective: Write a JAVA program to show:


A) Multi-Level Inheritance
Theory:
When a class extends a class, which extends anther class then this is called multilevel
inheritance. For example class C extends class B and class B extends class A then this type of
inheritance is known as multilevel inheritance.
Source code:
class Person{
Person() {
System.out.println("Person constructor");
}
void nationality(){
System.out.println("Indian"
);
}
void place(){
System.out.println("Mumbai"
);
}
}
class Emp extends Person{
Emp(){
System.out.println("Emp constructor");
}
void organization(){
System.out.println("IBM"
);
}
void place(){
System.out.println("New
York");
}
}
class Manager extends Emp{
Manager(){
System.out.println("Manager constructor");
}
void subordinates(){
System.out.println(12
);
}
void place(){
System.out.println("London"
);
}}
class Check{
public static void main(String
arg[]){ Manager m=new Manager();
m.nationality();
m.organization()
;
m.subordinates()
; m.place();
}}
Output:
B) Multi-Threading
Theory:
MULTITHREADING in Java is a process of executing two or more threads simultaneously to
maximum utilization of CPU. Multithreaded applications execute two or more threads run
concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each
other. Mulitple threads don't allocate separate memory area, hence they save memory. Also,
context switching between threads takes less time.
Source code:
class Th1 extends Thread{
public void run(){
try{
for(int i=1;i< =10;i++){
System.out.println("value of i="+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie){
System.err.println("Problem in thread execution");
}
}
}
class Threaddemo2{
public static void main(String
args[]){ Th1 t1=new Th1();
System.out.println("Execution status of t1 before
start="+t1.isAlive()); t1.start();
System.out.println("Execution status of t1 before
start="+t1.isAlive()); try{
Thread.sleep(5000);
}
catch(InterruptedException ie){
System.out.println("Problem in thread execution");
}
System.out.println("Execution status of t1 during
execution="+t1.isAlive()); try{
Thread.sleep(5001);
}
catch(InterruptedException ie){
System.out.println("problem in thread execution");
}
System.out.println("Execution status of t1
after completation="+t1.isAlive());
}
}
Output:
Execution status of t1 before start=false Execution status of t1 after start=true
1
2
3
4
5
6
Execution status of t1 during execution=true 7
8
9
10
Execution status of t1 after complexation=false
Program-6

Objective: Write a JAVA applet to display the Application Program Screen i.e. calculator and
other.
Theory: Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Source code:
Program
(AppletCalculator.java)
import java.applet.*;
import java.awt.*;
import
java.awt.event.*;
public class AppletCalculator extends Applet implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2;
Button b1,b2,b3,b4;
public void init()
{
setLayout(new FlowLayout());
l1=new Label("First
Number:"); t1=new
TextField(20);
l2=new Label("Second
Number:"); t2=new
TextField(20);
b1=new Button("Add");
b2=new Button("Sub");
b3=new Button("Mul");
b4=new Button("Div");
l3=new
Label("Result");
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(b2);
add(b3);
add(b4);
add(l3);
b1.addActionListener(this)
;
b2.addActionListener(this)
;
b3.addActionListener(this)
;
b4.addActionListener(this); }
public void actionPerformed(ActionEvent
ae){
Double
num1=Double.parseDouble(t1.getText());
Double
num2=Double.parseDouble(t2.getText());
if(ae.getSource()==b1){
Double
value=num1+num2;
l3.setText(""+value);
}
if(ae.getSource()==b2){
Double value=num1-
num2;
l3.setText(""+value);
}
if(ae.getSource()==b3){
Double
value=num1*num2;
l3.setText(""+value);
}
if(ae.getSource()==b4) {
Double
value=num1/num2;
l3.setText(""+value);
}}}
Program (AppletCalculator.html)
<html>
<head><title>Applet Calculator</title></head>
<body>
<applet code = "AppletCalculator.class" width = "200" height = "400">
If your browser is Java enabled, then only you can see Applet in your browser
. If it is not Java enabled,then you need to add Java plug-
ins in your browser or use appletviewer to view applet.
</applet></body> </html>
Output :
Program-7

Objective: Writing program in XML for creation of DTD, which specifies set of rules. Create a
style sheet in CSS/XSL & display the document in internet explorer.
Theory: DTD stands for Document Type Definition. A DTD defines the structure and the legal
elements and attributes of an XML document.
Basic Syntax:
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>
Source Code: assign.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Person[
<!ELEMENT Person (Name+,Age,Address,Hobbies,DOB+)>
<!ELEMENT Name (First_Name,Last_Name)>
<!ELEMENT First_Name (#PCDATA)>
<!ELEMENT Last_Name (#PCDATA)>
<!ELEMENT Age (#PCDATA)>
<!ELEMENT Address (#PCDATA)>
<!ELEMENT Hobbies EMPTY>
<!ELEMENT DOB (Day,Month,Year)>
<!ELEMENT Day (#PCDATA)>
<!ELEMENT Month (#PCDATA)>
<!ELEMENT Year (#PCDATA)>
<!ATTLIST Person gender CDATA "female">
<!ENTITY add "Delhi Road,Majholi,Moradabad">
]>
<Person gender="male">
<Name>
<First_Name>YASH</First_Name>
<Last_Name>AGARWAL</Last_Name>
</Name>
<Age>21</Age>
<Address>&add;</Address>
<Hobbies/>
<DOB>
<Day>18</Day>
<Month>07</Month>
<Year>2002</Year>
</DOB>
</Person>
Output:
Program-11

Objective: Write a JSP which insert the details of the 3 or 4 users who register with the
web site by using registration form. Authenticate the user when he submits the login form
using the user name and password from the database.

Theory:
JSP scripting elements let you insert Java code into the servlet that will be generated from
the current JSP page. There are three forms:
1. Expressions of the form <%= expression %> that are evaluated and inserted into the
output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method,
and
3. Declarations of the form <%! code %> that are inserted into the body of the servlet
class, outside of any existing methods.
Each of these is described in more detail below.
JSP Expressions:-

A JSP expression is used to insert Java values directly into the output. It has the
following form:
<%= Java Expression %>
JSP Scriptlets:-
If you want to do something more complex than insert a simple expression,
JSP scriptlets let you insert arbitrary code into the servlet method that will be built to
generate the page. Scriptlets have the following form:
<% Java Code %>
Note that code inside a scriptlet gets inserted exactly as written, and any static
HTML (template text) before or after a scriptlet gets converted to print statements. This
means that scriptlets need not contain complete Java statements, and blocks left open can
affect the static HTML outside of the scriptlets.
JSP Declarations:-
A JSP declaration lets you define methods or fields that get inserted into the main
body of the servlet class (outside of the service method processing the request). It has the
following form:

<%! Java Code %>


Since declarations do not generate any output, they are normally used in
conjunction with JSP expressions or scriptlets. For example, here is a JSP fragment that
prints out the number of times the current page has been requested since the server
booted (or the servlet class was changed and reloaded):

<%! private int accessCount = 0; %>


Source Code:
<html> <body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table><tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
</tr <td colspan="2" align="center"><b>&nbsp;</td>
>
<tr> <td>User Name</td>
<td><input type="text" name="user"/></td>
</tr
> <td>Password</td>
<tr> <td><input type="password" name="pwd"/></td>

</tr <td>&nbsp;</td>
> <td>&nbsp;</td>
<tr>

</tr
>
<tr>
<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>
</tr>
</table></form>
</td></tr></table></body></html>
Auth.jsp:
<%@page import="java.sql.*;"%>
<html><head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!String uname,pwd;%>
<%
uname=request.getParameter("user")
;
pwd=request.getParameter("pwd");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.158:1521:CCLAB
","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select name,password from personal where
name='"+uname+"' and
password='"+pwd+"'");
if(rs.next()){
out.println("Authorized
person");
}
else{
out.println("UnAuthorized person");
}
con.close();
}
catch(Exception e){out.println(""+e);}
%>
</body></html>
OUTPUT:-

AUTHORISED USER
Program-12
Objective: Install a database (Mysql or Oracle). Create a table which should contain at least the
following fields: name, password, email-id, phone number Write a java program/servlet/JSP to
connect to that database and extract data from the tables and display them. Insert the details
of the users who register with the web site, whenever a new user clicks the submit button in
the registration page.
Theory:
Mysql

MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −

 MySQL is released under an open-source license. So you have nothing to pay to use it.
 MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
 MySQL uses a standard form of the well-known SQL data language.
Configuration Step:
Step1: open MySQL WorkBench and then go to Database>Connect to Database.

Step2: A pop-up window will be opened just click on ok.


Step3: Once you click on “ok” it will ask you for a password. It is the same password which you have

used during the installation process. So enter the correct password and then click on the “ok” button.

.
Source Code:
select ce.entity_id,
concat(cevf.value, ' ', cevl.value) name,
ce.email,
caev.value phone_numb from customer_entity ce
inner join customer_entity_varchar cevf
on ce.entity_id =
cevf.entity_id inner join
eav_attribute eaf
on eaf.attribute_id =
cevf.attribute_id inner join
customer_entity_varchar cevl
on ce.entity_id =
cevl.entity_id inner join
eav_attribute eal
on eal.attribute_id =
cevl.attribute_id inner join
eav_entity_type eet
on eet.entity_type_id = eal.entity_type_id =
eaf.entity_type_id inner join customer_address_entity cae
on cae.parent_id = ce.entity_id
inner join customer_address_entity_varchar
caev on cae.entity_id = caev.entity_id
inner join eav_attribute eat
on caev.attribute_id =
eat.attribute_id where
eet.entity_type_code ='name'
and eaf.attribute_code = 'password'
and eal.attribute_code = 'email-id',
and
eat.attribute_code='phone_numb'
order by ce.entity_id desc limit 1

Servlet.java
import javax.swing.*;
import
javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import java.sql.*;
public class FetchData implements ActionListener {
JFrame frame1;//creating object of first JFrame
JLabel nameLabel;//creating object of JLabel
JTextField nameTextField;//creating object of
JTextfield JButton fetchButton;//creating object of
JButton
JButton resetButton;//creating object of
JButton JFrame frame2;//creating object of
second JFrame
DefaultTableModel defaultTableModel;//creating object of
DefaultTableModel
JTable table;//Creating object of JTable
Connection connection;//Creating object of Connection
class Statement statement;//Creating object of Statement
class int flag=0;
FetchData() {
frame1 = new JFrame();
frame1.setTitle("Search Database");//setting the title of first
JFrame
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//setting
default close operation
GridBagLayout bagLayout = new GridBagLayout();//creating object of
GridBagLayout
GridBagConstraints bagConstraints = new
GridBagConstraints();//creating object of GridBagConstratints
frame1.setSize(500, 300);//setting the size of first JFrame
frame1.setLayout(bagLayout);//setting the layout to GridBagLayout of
first JFrame
bagConstraints.insets = new Insets(15, 40, 0, 0);//Setting the
padding between the components and neighboring components
//Setting the property of JLabel and adding it to the first
JFrame nameLabel = new JLabel("Enter Username");
bagConstraints.gridx = 0;
bagConstraints.gridy = 0;
frame1.add(nameLabel, bagConstraints);
//Setting the property of JTextfield and adding it to the first JFrame
nameTextField = new JTextField(15);
bagConstraints.gridx = 1;
bagConstraints.gridy = 0;
frame1.add(nameTextField, bagConstraints);

//Setting the property of JButton(Fetch Data) and adding it to


the first JFrame
fetchButton = new JButton("Fetch
Data"); bagConstraints.gridx = 0;
bagConstraints.gridy = 1;
bagConstraints.ipadx = 60;
frame1.add(fetchButton,
bagConstraints);
//Setting the property of JButton(Reset Data) and adding it to
the second JFrame
resetButton = new JButton("Reset
Data"); bagConstraints.gridx = 1;
bagConstraints.gridy = 1;
frame1.add(resetButton,
bagConstraints);
//adding ActionListener to both buttons
fetchButton.addActionListener(this);
resetButton.addActionListener(this);
frame1.setVisible(true);//Setting the visibility of First
JFrame
frame1.validate();//Performing relayout of the First JFram
}
public static void main(String[] args)
{ new FetchData();
}
@Override
public void actionPerformed(ActionEvent e)
{ if (e.getSource() == fetchButton) {
String userName = nameTextField.getText().toString();//getting
text of username text field and storing it in a String variable
frameSecond(userName);//passing the text value to frameSecond
metho
d }
if (e.getSource() == resetButton) {
nameTextField.setText("");//resetting the value of username text

field
}

}
public void frameSecond(String userName) {
//setting the properties of second JFrame
frame2 = new JFrame("Database Results");
frame2.setLayout(new FlowLayout());
frame2.setSize(400, 400);
//Setting the properties of JTable and DefaultTableModel
defaultTableModel = new DefaultTableModel();
table = new JTable(defaultTableModel);
table.setPreferredScrollableViewportSize(new Dimension(300, 100));
table.setFillsViewportHeight(true);
frame2.add(new JScrollPane(table));
defaultTableModel.addColumn('name');
defaultTableModel.addColumn("Password")
; try {
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase", "root",
"root");//Crating connection with database
statement = connection.createStatement();//crating statement
object
String query = "select * from STUDENT where USERNAME = '" + name
+ "'";//Storing MySQL query in A string variable
ResultSet resultSet =
statement.executeQuery(query);//executing query and storing result in
ResultSet
while (resultSet.next()) {
//Retrieving details from the database and storing it in the String
variables
String name = resultSet.getString('name');
String roll =
resultSet.getString('phone_numb'); String dept
= resultSet.getString('email-id'); if
(userName.equalsIgnoreCase(name)) {
flag = 1;
defaultTableModel.addRow(new Object[]{name, roll,
dept});//Adding row in Table
frame2.setVisible(true);//Setting the visibility of
second Frame
frame2.validate()
; break;
} }
if (flag == 0) {
JOptionPane.showMessageDialog(null, "No Such Username
Found");//When invalid username is entered
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}}
Output:
Program-13
Objective: Assume four users user1, user2, user3 and user4 having the passwords pwd1,
pwd2, pwd3 and pwd4 respectively. Write a servlet for doing the following
a) Create a Cookie and add these four user id’s and passwords to this Cookie.
b) Read the user id and passwords entered in the Login form and authenticate with
the values available in the cookies.
Theory:
Servlet Life cycle:
· Servlet class loading
· Servlet Instantiation
· call the init method
· call the service method
· call destroy method
Class loading and instantiation:-
If you consider a servlet to be just like any other Java program, except that it runs
within a servlet container, there has to be a process of loading the class and making it ready
for requests. Servlets do not have the exact equivalent of a main method that causes them
to start execution.
The init method:-
The HttpServlet class inherits the init method from GenericServlet. The init method
performs a role slightly similar to a constructor in an “ordinary” Java program in that it
allows initialization of an instance at start up. It is called automatically by the servlet
container and as it causes the application context (WEB.XML) to be parsed and any
initialization will be performed. It comes in two versions, one with a zero parameter
constructor and one that takes a ServletConfig parameter.
Calling the service method:-
The service() method gets information about the request from the request object,
processes the request, and uses methods of the response object to create the client
response. The service method can invoke other methods to process the request, such as
doGet(), doPost(), or methods you write. The service method is called for each request
processed and is not normally overridden by the programmer.
The code that makes a servlet “go” is the. Servlet
void service(ServletRequest req,ServletResponse res)
The destroy Method:-
Two typical reasons for the destroy method being called are if the container is
shutting down or if the container is low on resources. This can happen when the container
keeps a pool of instances of servlets to ensure adequate performance. If no requests have
come in for a particular servlet for a while it may destroy it to ensure resources are available
for the servlets that are being requested. The destroy method is called only once, before a
servlet is unloaded and thus you cannot be certain when and if it is called.
void destroy()
ServletConfig Class:-
ServletConfig object is used by the Servlet Container to pass information to the
Servlet during it's initialization. Servlet can obtain information regarding initialization
parameters and their values using different methods of ServletConfig class initialization
parameters are name/value pairs used to provide basic information to the Servlet during it's
initialization like JDBC driver name, path to database, username, password etc.
Source Code:
cologin.html:
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
cologin1.htm
l
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin1">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
Addcook.java:
import javax.servlet.* ;
import
javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Cookie c1=new
Cookie("usr1","suni"); Cookie
p1=new Cookie("pwd1","ani"); Cookie
c2=new Cookie("usr2","abc"); Cookie
p2=new Cookie("pwd2","123"); Cookie
c3=new Cookie("usr3","def"); Cookie
p3=new Cookie("pwd3","456"); Cookie
c4=new Cookie("usr4","mno"); Cookie
p4=new Cookie("pwd4","789");
res.addCookie(c1);
res.addCookie(p1);
res.addCookie(c2);
res.addCookie(p2);
res.addCookie(c3);
res.addCookie(p3);
res.addCookie(c4);
res.addCookie(p4);
out.println("COOKIE ADDED");
}
}
Clogin.java:
import javax.servlet.* ;
import
javax.servlet.http.*;
import java.io.*;
public class Clogin extends HttpServlet{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException{
res.setContentType("text/html
"); PrintWriter
out=res.getWriter();
user=req.getParameter("usr");
pas=req.getParameter("pwd");
Cookie[] c=req.getCookies();
for(int i=0;i<c.length;i++)
{
if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))||
c[i].getName().equals("usr2") &&c[i+1].getName().equals("pwd2"))||
(c[i].getName().equals("usr3")&&
c[i+1].getName().equals("pwd3"))||(c[i].getName().equals("usr4")&&
c[i+1].getName().equals("pwd4") ))
{
if((user.equals(c[i].getValue()) && pas.equals(c[i+1].getValue())) )
//RequestDispatcher rd=req.getRequestDispatcher("/cart.html");
rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>him</servlet-name>
<servlet-class>Clogin</servlet-class>
</servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>
Output:

You might also like