[Go to site: main page, start]

0% found this document useful (0 votes)
4 views91 pages

Sharable Java Python

The document outlines a parallel course on Java and Python, covering various programming paradigms, compilation processes, and basic programming concepts such as variables, operators, branching, and looping. It includes code examples for both languages, demonstrating how to implement functionalities like arithmetic operations, string methods, and class creation. Additionally, it discusses object-oriented programming concepts like aggregation and method definitions.

Uploaded by

Deepikaa Balaji
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views91 pages

Sharable Java Python

The document outlines a parallel course on Java and Python, covering various programming paradigms, compilation processes, and basic programming concepts such as variables, operators, branching, and looping. It includes code examples for both languages, demonstrating how to implement functionalities like arithmetic operations, string methods, and class creation. Additionally, it discusses object-oriented programming concepts like aggregation and method definitions.

Uploaded by

Deepikaa Balaji
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

<Codemithra />

Java & Python | Parallel Course


Programming Paradigms

Functional/procedural programming:

Program is a list of instructions to the computer

Object-oriented programming

Program is composed of a collection objects that communicate with each other


Java Compilation
Python

Source
Compiler Byte Code Interpreter Processor
Code
First Program

print("Hello, World!")

class Main {
public static void main(String args[]){
[Link]("Hello, World!");
}
}
Variables
a = 10
b = 10.4
c = "String"
d = 'single quoted string'
e = True
print("a, b, c, d, e", a, b, c, d, e)

class Main {
public static void main(String[] args) {
int a = 10;
float b = 10.4f;
String c = "String";
// Not possible
// String d = 'String';
boolean e = true;
[Link]("a, b, c, e " + a + " " + b + " " + c + " " + e);
}
}
Numbers in Python

a = 10
print(a, type(a))
a = float(a)
print(a, type(a))
a = complex(a)
print(a, type(a))
a = complex(a, a)
print(a, type(a))
Numbers in Java

class Main {
public static void main(String[] args) {
Integer a = 10;
Float b = 10.4f;
Double c = 10.4d;
[Link]("a, b, c " + a + " " + b + " " + c);
}
}
Number methods

print("[Link] " , [Link](81.5));


print("[Link] " , [Link](81.5));
print("[Link] " , [Link](81.5));
print("[Link] " , [Link](3));

class Main {
public static void main(String[] args) {
[Link]("[Link] " + [Link](81.5));
[Link]("[Link] " + [Link](81.5));
[Link]("[Link] " + [Link](81.5));
[Link]("[Link] " + [Link](3));
}
}
Number methods

print("[Link] " , [Link](-6));


print("[Link] " , [Link](81));
print("[Link] " , max(5, 6));
print("[Link]" , min(5, 6));

class Main {
public static void main(String[] args) {
[Link]("[Link] " + [Link](-6));
[Link]("[Link] " + [Link](81));
[Link]("[Link] " + [Link](5, 6));
[Link]("[Link]" + [Link](5, 6));
}
}
String methods

str = "ethnus"
print([Link]("nus"))
print([Link]("eth"))
print([Link]())
print([Link]())

class Main {
public static void main(String[] args) {
String str = "ethnus tech";
Character c = '3';
[Link]([Link]("nus"));
[Link]([Link]("eth"));
[Link]([Link](c));
[Link]([Link](c));
}
}
String methods

str = "ethnus"
print([Link]())
print([Link]())

class Main {
public static void main(String[] args) {
String str = "ethnus tech";
[Link]([Link]());
[Link]([Link]());
}
}
Arithmetic Operators

print(a + b) [Link](a + b) 110

print(a - b) [Link](a - b) 90

print(a / b) [Link]((float) a / b) 10.0

print(a * b) [Link](a * b) 1000

print(a ** b) [Link]([Link](a, b)) 100000000000000000000

print(a // b) [Link](a / b) 10

print(a % b) [Link](a % b) 0

a = 100, b = 10
Comparison Operators

print(a == b) [Link](a == b) False

print(a > b) [Link](a > b) True

print(a >= b) [Link](a >= b) True

print(a < b) [Link](a < b) False

print(a <= b) [Link](a <= b) False

print(a != b) [Link](a != b) True

print(a == b) [Link](a == b) False

a = 100, b = 10
Bitwise Operators

print(a & b) [Link](a & b) 0

print(a | b) [Link](a | b) 6

print(a << 1) [Link](a << 1) 4

print(a >> 1) [Link](a >> 1) 1

print(a ^ b) [Link](a ^ b) 6

a = 2, b = 4
Logical Operators

print(a and b) [Link](a && b) False

print(a or b) [Link](a || b) True

print(not a) [Link](!a) False

a = True, b = False
Ternary Operator

a = 100
b = 10
min = a < b and a or b
print(min)

class Main {
public static void main(String[] args) {
int a = 100;
int b = 10;
int min = a < b ? a : b;
[Link](min);
}
}
Branching

a = '' a = 0
if a: if a:
print("Value of a = ", a) print("Value of a = ", a)
else: else:
print("False value in a") print("False value in a")

a = -1 a = False
if a: if a:
print("Value of a = ", a) print("Value of a = ", a)
else: else:
print("False value in a") print("False value in a")
Branching
class Main {
public static void main(String[] args) {
boolean a = true;
if(a)
[Link]("A is true");
else
[Link]("A is false");
}
}

class Main {
public static void main(String[] args) {
int a = 5;
if(a)
[Link]("A is true");
else
[Link]("A is false");
}
}
Branching
a = 5
if a:
print("a is not False")
if a > 3:
print("a is greater than 3")
else:
print("a is lesser than or equal to 3")

class Main {
public static void main(String[] args) {
int a = 5;
if(a > 0) {
if(a > 3) {
[Link]("a is greater than 3");
} else {
[Link]("a is greater than 3");
}
}
}
}
Branching
public class Main {
public static void main(String[] args) {
char grade = 'B';
switch(grade) {
case 'A' :
[Link]("Excellent!");
break;
case 'B' :
case 'C' :
[Link]("Well done");
break;
case 'D' :
[Link]("You passed");
break;
default :
[Link]("Invalid grade");
}
[Link]("Your grade is " + grade);
}
}
Looping

count = 0
while (count < 9):
print(count)
count = count + 1

class Main {
public static void main(String[] args) {
int count = 0;
while (count < 9) {
[Link](count);
count = count + 1;
}
}
}
Looping
count = 0
while (count < 9):
if count == 4:
count = count + 1
continue
print(count)
count = count + 1

class Main {
public static void main(String[] args) {
int count = 0;
while (count < 9) {
if(count == 4) {
count = count + 1;
continue;
}
[Link](count);
count = count + 1;
}
}
}
Looping
count = 0 class Main {
for count in range(0,9): public static void main(String[] args) {
if count == 4: int count;
continue for(count = 0; count < 9; count++) {
print(count) if (count == 4)
continue;
[Link](count);
}
}
}

count = 0 class Main {


for count in range(0,9): public static void main(String[] args) {
if count == 4: int count;
break for(count = 0; count < 9; count++) {
print(count) if (count == 4)
break;
[Link](count);
}
}
}
Looping
count = 0 class Main {
for count in range(0,9): public static void main(String[] args) {
if count == 4: int count;
continue for(count = 0; count < 9; count++) {
else: if (count == 4)
print(count) continue;
else
[Link](count);
}
}
}

count = 0 class Main {


for count in range(0,9): public static void main(String[] args) {
if count == 4: int count;
pass for(count = 0; count < 9; count++) {
print(count) if (count == 4) {
}
[Link](count);
}
}
}
Looping

x = 10 public class Main {


while True: public static void main(String[] args) {
print(x) int x = 10;
x = x + 1 do {
if x > 19: [Link](x + "\t");
break x = x + 1;
} while( x < 20 );
}
}
Looping

x = 10 public class Main {


while True: public static void main(String[] args) {
print(x) int i, j;
x = x + 1 for(i = 1; i < 5; i++) {
if x > 19: [Link]();
break for(j = i; j > 0; j--) {
[Link](j + " ");
}
}
}
}
Input

age = input("Enter your age")


print("Entered age is ", age)

import [Link];
class Main {
public static void main(String[] args) {
int age;
Scanner scanner = new Scanner([Link]);
[Link]("Enter your age");
age = [Link]();
[Link]("Entered age is " + age);
}
}
Classes
class Player:
def __init__(self, name, role, rating):
[Link] = name
[Link] = role
[Link] = rating

class Player {
String name;
String role;
int rating;
Player(String name, String role, int rating) {
[Link] = name;
[Link] = role;
[Link] = rating;
}
}
Creating Objects

class Player:
def __init__(self, name, role):
[Link] = name
[Link] = role

def getRole(self):
return [Link]

dhoni = Player("Dhoni", 'wicket keeper')


yadav = Player("Yadav", 'bowler')

print([Link]())
print([Link]())
Creating Objects
class Player {
String name;
String role;
Player(String name, String role) {
[Link] = name;
[Link] = role;
}
String getRole() {
return [Link];
}
}
class Main {
public static void main(String[] args) {
Player dhoni = new Player("Dhoni", "wicket keeper");
Player yadav = new Player("Yadav", "bowler");
[Link]([Link]());
[Link]([Link]());
}
}
Creating Objects

class Player:
def __init__(self, name = "", role = ""):
[Link] = name
[Link] = role
def getRole(self):
return [Link]

dhoni = Player()
yadav = Player("Yadav", 'bowler')

print([Link]())
print([Link]())
Creating Objects
class Player {
String name;
String role;
Player() {
}
Player(String name, String role) {
[Link] = name;
[Link] = role;
}
String getRole() {
return [Link];
}
}
class Main {
public static void main(String[] args) {
Player dhoni = new Player();
Player yadav = new Player("Yadav", "bowler");
[Link]([Link]());
[Link]([Link]());
}
}
Aggregation in Python

class Shoe:
def __init__(self, size):
[Link] = size

class Player:
def __init__(self, name, shoe):
[Link] = name
[Link] = shoe

shoe_eight = Shoe(8)
shoe_seven = Shoe(7)
dhoni = Player("Dhoni", shoe_eight)
jaddu = Player("Jadeja", shoe_seven)
print([Link])
print([Link])
Aggregation in Java
class Shoe { class Player {
int size; String name;
Shoe(int size) { Shoe shoe;
[Link] = size; Player(String name, Shoe shoe) {
} [Link] = name;
} [Link] = shoe;
}
}

class Main {
public static void main(String a[]) {
Shoe shoe_eight = new Shoe(8);
Shoe shoe_seven = new Shoe(7);
Player dhoni = new Player("Dhoni", shoe_eight);
Player jaddu = new Player("Jadeja", shoe_seven);
[Link]([Link]);
[Link]([Link]);
}
}
Googly
class Shoe: class Shoe:
def __init__(self, size): def __init__(self, size):
[Link] = size [Link] = size

class Player: class Player:


def __init__(self, name, shoe): def __init__(self, name, shoe):
[Link] = name [Link] = name
[Link] = shoe [Link] = shoe
def displayShoe(self): def displayShoe(self):
print([Link]) print([Link])

shoe_eight = Shoe(8)
shoe_seven = Shoe(7)
dhoni = Player("Dhoni", shoe_eight)
jaddu = Player("Jadeja", shoe_seven)
[Link]()
[Link]()
Swapped?
class Shoe:
def __init__(self, size):
[Link] = size

class Player:
def __init__(self, name, shoe):
[Link] = name
[Link] = shoe
def swap(self, other):
other = self

shoe_eight = Shoe(8)
shoe_seven = Shoe(7)
dhoni = Player("Dhoni", shoe_eight)
jaddu = Player("Jadeja", shoe_seven)
[Link](jaddu)

print([Link])
print([Link])
Swapped?
class Shoe { class Player {
int size; String name;
Shoe(int size) { Shoe shoe;
[Link] = size; Player(String name, Shoe shoe) {
} [Link] = name;
} [Link] = shoe;
}
void swapShoe(Player other) {
[Link] = [Link];
}
}

class Main {
public static void main(String a[]) {
Shoe shoe_eight = new Shoe(8);
Shoe shoe_seven = new Shoe(7);
Player dhoni = new Player("Dhoni", shoe_eight);
Player jaddu = new Player("Jadeja", shoe_seven);
[Link](jaddu);
[Link]([Link]);
[Link]([Link]);
}
}
Association in Python

class Bat:
def __init__(self, company):
[Link] = company

class Player:
def __init__(self, name):
[Link] = name
def batting(self, bat):
print("I use " + [Link])

mrf = Bat("MRF Bat");


ss = Bat("SS Bat");
sachin = Player("Dhoni")
dhoni = Player("Jadeja")
[Link](mrf)
[Link](ss)
Association in Java
class Bat { class Player {
String company; String name;
Bat(String company) { Player(String name) {
[Link] = company; [Link] = name;
} }
} void batting(Bat bat) {
[Link]("I use ");
[Link]([Link]);
}
}

class Main {
public static void main(String a[]) {
Bat mrf = new Bat("MRF Bat");
Bat ss = new Bat("SS Bat");
Player dhoni = new Player("Dhoni", ss);
Player sachin = new Player("Sachin", mrf);
[Link](mrf);
[Link](ss);
}
}
Difference between association & aggregation

Instance Variable

Local Variable
Inheritance

class Employee:
def __init__(self, id):
[Link] = id

class FullTime(Employee):
def __init__(self, id, name):
super().__init__(id)
[Link] = name
def printDetails(self):
print([Link], [Link])

aravind = FullTime(1001, "Aravind")


raghavan = FullTime(1002, "Raghavan")
[Link]()
[Link]()
Inheritance
class Employee { class FullTime extends Employee {
int id; String name;
Employee(int id) { FullTime(int id, String name) {
[Link] = id; super(id);
} [Link] = name;
} }
void printDetails() {
[Link]([Link]);
[Link]([Link]);
}
}

class Main {
public static void main(String a[]) {
FullTime aravind = new FullTime(1001, "Aravind");
FullTime raghavan = new FullTime(1002, "Raghavan");
[Link]();
[Link]();
}
}
Inheritance

class Employee:
def __init__(self, id, private):
[Link] = id
self.__private = private

class FullTime(Employee):
def __init__(self, id, name):
super().__init__(id, "Something")
[Link] = name
def printDetails(self):
print([Link], [Link])

aravind = FullTime(1001, "Aravind")


print([Link])
print(aravind.__private) #print(aravind._Employee__private)
print([Link])
Inheritance

class Employee { class FullTime extends Employee {


private int id; String name;
Employee(int id) { FullTime(int id, String name) {
[Link] = id; super(id);
} [Link] = name;
} }
}

class Main {
public static void main(String a[]) {
FullTime aravind = new FullTime(1001, "Aravind");
[Link]([Link]);
[Link]([Link]);
}
}
Access Specifiers in Java

Same Package Different Package

Inside Class Outside Class Inherited Classes Other Classes

public ✔ ✔ ✔ ✔

protected ✔ ✔ ✔ ✘

default ✔ ✔ ✘ ✘

private ✔ ✘ ✘ ✘
Calling inherited method

class Employee:
def __init__(self):
pass
def method(self):
print("I am here")

class FullTime(Employee):
def __init__(self):
[Link]()

aravind = FullTime()
Calling inherited method

class Employee {
void method() {
[Link]("I am here");
}
}
class FullTime extends Employee {
public FullTime() {
[Link]();
}
}

class Demo01 {
public static void main(String a[]) {
FullTime aravind = new FullTime();
}
}
Dynamic Polymorphism
class Employee {
void method() {
[Link]("I am here");
}
}
class FullTime extends Employee {
void method() {
[Link]("FullTime");
}
void myMethod() {
[Link]("myMethod");
}
}
class Demo01 {
public static void main(String a[]) {
Employee aravind = new FullTime();
[Link]();
}
}
Dynamic Polymorphism
class Employee {
void method() {
[Link]("I am here");
}
}
class FullTime extends Employee {
void method() {
[Link]("FullTime");
}
void myMethod() {
[Link]("myMethod");
}
}
class Demo01 {
public static void main(String a[]) {
Employee aravind = new FullTime();
[Link]();
}
}
Abstract class

from abc import ABC, abstractmethod


class Employee(ABC):
@abstractmethod
def work(self):
pass

class FullTime(Employee): class PartTime(Employee):


def work(self): def work(self):
print("50Hrs") print("20Hrs")

aravind = FullTime()
[Link]()
Abstract class
abstract class Employee {
abstract void work();
}

class FullTime extends Employee { class PartTime extends Employee {


void work() { void work() {
[Link]("50Hrs"); [Link]("20Hrs");
} }
} }

class Main {
public static void main(String a[]) {
FullTime aravind = new FullTime();
[Link]();
}
}
Let’s ask

What happens if we didn’t


override the abstract method in
child?

What happens if we try to create


object for abstract class?

How can we call concrete


method from an abstract class?
Exceptions!
a = 5
b = 0
try:
c = a / b
print("No exception")
except:
print("Exception")

class Main {
public static void main(String args[]) {
int a = 5, b = 0;
try {
int c = a / b;
[Link]("No exception");
} catch(Exception e) {
[Link]("Exception");
}
}
}
Exceptions!

a = 5 class Main {
b = 0 public static void main(String args[]) {
try: int a = 5, b = 0;
c = a / b try {
print("No exception") int c = a / b;
except: [Link]("No exception");
print("Exception") } catch(Exception e) {
finally: [Link]("Exception");
print("Anyways") } finally {
[Link]("Anyways");
}
}
}
Our own exceptions

class class MyException extends Exception {


MyException(Exception): }
pass class Main {
public static void main(String args[]) {
a = 5 try {
b = 0 throw new MyException();
try: } catch(MyException e) {
raise MyException() [Link]("Exception");
except: }
print("Exception") }
}
Our own exceptions
def someFun():
raise Exception()

try:
someFun()
except:
print("Exception")

class Main {
public static void method() throws Exception {
throw new Exception();
}
public static void main(String args[]) {
try {
[Link]();
} catch(Exception e) {
[Link]("Exception");
}
}
}
About a static
class Animal:
def walk():
print("Static method")

dog = Animal()
[Link]()
[Link]()

class Animal {
public static void method() {
[Link]("Static method");
}
}
class Main {
public static void main(String[] args) {
Animal dog = new Animal();
[Link]();
[Link]();
}
}
About a final

class Animal {
final int age = 5;
}
class Main {
public static void main(String[] args) {
Animal dog = new Animal();
[Link] = 10;
}
}
About a final

class Animal {
int age = 5;
final void method() {
[Link]("A Method");
}
}
class Dog extends Animal {
void method() {
[Link]("D Method");
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
}
}
About a final

final class Animal {


int age = 5;
void method() {
[Link]("A Method");
}
}
class Dog extends Animal {
void method() {
[Link]("D Method");
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
}
}
Creating connection
import [Link]
mydb = [Link](
host="localhost", user="root", passwd="", database="test"
)
print(mydb)

import [Link];
import [Link];
import [Link];
import [Link];
class Demo01 {
public static void main(String[] args) throws Exception {
[Link]("[Link]");
String conn = "jdbc:mysql://localhost:3306/test";
String user = "root";
String pwd = "";
Connection con = [Link](conn, user, pwd);
Statement stmt = [Link]();
}
}
Selecting data
import [Link]
mydb = [Link](
host="localhost", user="root", passwd="", database="test"
)
mycursor = [Link]()
[Link]("select * from demo")
myresult = [Link]()
for x in myresult:
print(x)

Statement stmt = [Link]();


ResultSet rs = [Link]("select * from demo");
while([Link]()) {
[Link]([Link](1));
}
Inserting data
import [Link]
mydb = [Link](
host="localhost", user="root", passwd="", database="test"
)
mycursor = [Link]()
sql = "insert into demo (id) values (%s)"
val = (4,)
[Link](sql, val)
[Link]()
print([Link], "record inserted.")

PreparedStatement stmt=[Link]("insert into demo (id) values


(?)");
[Link](1,5);
int i=[Link]();
[Link](i+" records inserted.");
Updating data
import [Link]
mydb = [Link](
host="localhost", user="root", passwd="", database="test"
)
mycursor = [Link]()
sql = "udpate demo set id = 1 where id = 2"
[Link](sql)
[Link]()
print([Link], "record updated.")

PreparedStatement stmt=[Link]("update demo set id = (?)


where id = 4");
[Link](1,5);
int i=[Link]();
[Link](i+" records inserted.");
Hashing the passwords
import hashlib
result = hashlib.md5(b'MyPassword')
print("Hashed Password ", end ="")
print([Link]())

String myPassword = "MyPassword";


MessageDigest md = [Link]("MD5");
byte[] messageDigest = [Link]([Link]());

BigInteger no = new BigInteger(1, messageDigest);


String hashtext = [Link](16);
while ([Link]() < 32) {
hashtext = "0" + hashtext;
}

[Link]("Hashed Password: " + hashtext);


Encrypting a string
String key = "someKey";
String initVector = "someIntVec";
String myPassword = "MyPassword";
IvParameterSpec iv = new IvParameterSpec([Link]("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec([Link]("UTF-8"), "AES");
Cipher cipher = [Link]("AES/CBC/PKCS5PADDING");
[Link](Cipher.ENCRYPT_MODE, skeySpec, iv);

byte[] encrypted = [Link]([Link]());


String encryptedString = [Link]().encodeToString(encrypted);
[Link](encryptedString);

cipher = [Link]("AES/CBC/PKCS5PADDING");
[Link](Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original =
[Link]([Link]().decode(encryptedString));

[Link](new String(original));
Encrypting a string

from [Link] import Fernet


message = "my deep dark secret".encode()

key = Fernet.generate_key()
f = Fernet(key)
encrypted = [Link](message)
print(encrypted)

decrypted = [Link](encrypted)
print([Link]())
File Writing

fo = open("E:/[Link]", "a")
[Link]( "Text from python\n")
[Link]()

String str = "My text is here\n";


FileWriter fw=new FileWriter("E:/[Link]", true);
for (int i = 0; i < [Link](); i++)
[Link]([Link](i));

[Link]("Writing successful");
[Link]();
File Reading

fo = open("E:/[Link]", "r")
for x in fo:
print(x)
[Link]()

File file = new File("E:/[Link]");


FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
Threads in Python

import threading
import time

fo = open("E:/[Link]", "a")
def jobA():
for x in range(1, 999):
[Link]("A\n")
if x % 100 == 0:
[Link](1)
print("Some random job A")

def jobB():
for x in range(1, 999):
[Link]("Booooooo\n")
if x % 100 == 0:
[Link](1)
print("Some random job B")
Threads in Python

t1 = [Link](target=jobA)
t2 = [Link](target=jobB)

[Link]()
[Link]()

[Link]()
[Link]()

[Link]()
Threads in Java

class Multi extends Thread{


public void run(){
for(int i = 0; i < 999; i++) {
[Link]([Link]().getName());
if(i % 100 == 0) {
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}
Threads in Java

class Main {
public static void main(String[] args) throws Exception {
Multi t1=new Multi();
[Link]("A");
Multi t2 = new Multi();
[Link]("Booooo");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Done!");
}
}
Introduction

HTTP REQUEST

WEB SERVER

WEB CLIENT

HTTP RESPONSE
1
Process
Re
ce
iv
e
th
e
re
qu
es
t

2
Se
ar
c h
fo
rt
he
fil
e
3

Pr
o vi
de
th
e
re
sp
on
se
Web Server
Getting python CGI right

Start Apache Config apache Check in browser

Download XAMPP Open Add shebang line


xampp/apache/conf/http
Install [Link] &

Run & start apache Add AddHandler Execute your python


cgi-script .py
ScriptInterpreterSource
Registry-Strict

at the end of the file


First CGI Page

#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/[Link]

print("Content-type:text/html\r\n\r\n")
print('<html>')
print('<head>')
print('<title>Hello Word - First CGI Program</title>')
print('</head>')
print('<body>')
print('<h2>Hello Word! This is my first CGI program</h2>')
print('</body>')
print('</html>')
How about this form?

#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/[Link]

print("Content-type:text/html\r\n\r\n")
print('''<form action="/hello_get.cgi" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
''')
How about this form?

#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/[Link]

print("Content-type:text/html\r\n\r\n")
print('''<form action="/hello_get.cgi" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
''')
Get in server

#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/[Link]

import cgi, cgitb


form = [Link]()
first_name = [Link]('first_name')
last_name = [Link]('last_name')
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Hello - Second CGI Program</title>")
print("</head>")
print("<body>")
print("<h2>Hello %s %s</h2>" % (first_name, last_name))
print("</body>")
print("</html>")
Lets have some cookies

#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/[Link]

print("Set-Cookie:UserID=XYZ;")
print("Set-Cookie:Password=XYZ123;")
print("Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT;")
print("Set-Cookie:Domain=localhost;")
print("Set-Cookie:Path=/perl;")
print("Content-type:text/html\r\n\r\n")
print('''I have set some cookie''')
Lets have some cookies

#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/[Link]

print("Set-Cookie:UserID=XYZ;")
print("Set-Cookie:Password=XYZ123;")
print("Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT;")
print("Set-Cookie:Domain=localhost;")
print("Set-Cookie:Path=/perl;")
print("Content-type:text/html\r\n\r\n")
print('''I have set some cookie''')
Reading the cookies

#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/[Link]

from os import environ


import cgi, cgitb
print("Content-type:text/html\r\n\r\n")
if environ['HTTP_COOKIE']:
allCookies = environ['HTTP_COOKIE'].split(';')
for cookie in allCookies:
print([Link]("="))
else:
print("no cookie")
Process

Install Tomcat Create Dynamic Web Run on Server

Download Tomcat Create dynamic web Create HTML / JSP


project
Unzip the downloaded file Run the file on server
Select run time as
Tomcat with proper
version
First JSP page
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Java JSP Page</title>
</head>
<body>
<form action="[Link]" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Reading the data
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name=[Link]("first_name");
[Link]("welcome "+name);
%>
</body>
</html>
Setting the cookie
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<%
Cookie cookie = new Cookie("UserID","1001");
[Link](cookie);
%>
<form action="[Link]" method="post">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Reading the cookie
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<%
Cookie[] cookies = null;
cookies = [Link]();
if( cookies != null ) {
for (int i = 0; i < [Link]; i++) {
[Link]("Name : " + cookies[i].getName( ) + ", ");
[Link]("Value: " + cookies[i].getValue( )+" <br/>");
}
}
%>
</body>
</html>
<Codemithra />

Thank You
[Link]

You might also like