O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

Sharable_Java_Python.pdf

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Carregando em…3
×

Confira estes a seguir

1 de 91 Anúncio
Anúncio

Mais Conteúdo rRelacionado

Mais recentes (20)

Anúncio

Sharable_Java_Python.pdf

  1. 1. <Codemithra /> Java & Python | Parallel Course
  2. 2. 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
  3. 3. Java Compilation
  4. 4. Python Source Code Compiler Byte Code Interpreter Processor
  5. 5. First Program print("Hello, World!") class Main { public static void main(String args[]){ System.out.println("Hello, World!"); } }
  6. 6. 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; System.out.println("a, b, c, e " + a + " " + b + " " + c + " " + e); } } Variables
  7. 7. 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))
  8. 8. Numbers in Java class Main { public static void main(String[] args) { Integer a = 10; Float b = 10.4f; Double c = 10.4d; System.out.println("a, b, c " + a + " " + b + " " + c); } }
  9. 9. Number methods print("math.floor " , math.floor(81.5)); print("math.ceil " , math.ceil(81.5)); print("math.round " , math.round(81.5)); print("math.exp " , math.exp(3)); class Main { public static void main(String[] args) { System.out.println("Math.floor " + Math.floor(81.5)); System.out.println("Math.ceil " + Math.ceil(81.5)); System.out.println("Math.round " + Math.round(81.5)); System.out.println("Math.exp " + Math.exp(3)); } }
  10. 10. Number methods print("math.abs " , math.abs(-6)); print("math.sqrt " , math.sqrt(81)); print("Integer.max " , max(5, 6)); print("Integer.min" , min(5, 6)); class Main { public static void main(String[] args) { System.out.println("Math.abs " + Math.abs(-6)); System.out.println("Math.sqrt " + Math.sqrt(81)); System.out.println("Integer.max " + Integer.max(5, 6)); System.out.println("Integer.min" + Integer.min(5, 6)); } }
  11. 11. String methods str = "ethnus" print(str.endswith("nus")) print(str.startswith("eth")) print(str.isdigit()) print(str.isspace()) class Main { public static void main(String[] args) { String str = "ethnus tech"; Character c = '3'; System.out.println(str.endsWith("nus")); System.out.println(str.startsWith("eth")); System.out.println(Character.isDigit(c)); System.out.println(Character.isSpace(c)); } }
  12. 12. String methods str = "ethnus" print(str.upper()) print(str.lower()) class Main { public static void main(String[] args) { String str = "ethnus tech"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); } }
  13. 13. Arithmetic Operators print(a + b) System.out.println(a + b) 110 print(a - b) System.out.println(a - b) 90 print(a / b) System.out.println((float) a / b) 10.0 print(a * b) System.out.println(a * b) 1000 print(a ** b) System.out.println(Math.pow(a, b)) 100000000000000000000 print(a // b) System.out.println(a / b) 10 print(a % b) System.out.println(a % b) 0 a = 100, b = 10
  14. 14. Comparison Operators print(a == b) System.out.print(a == b) False print(a > b) System.out.print(a > b) True print(a >= b) System.out.print(a >= b) True print(a < b) System.out.print(a < b) False print(a <= b) System.out.print(a <= b) False print(a != b) System.out.print(a != b) True print(a == b) System.out.print(a == b) False a = 100, b = 10
  15. 15. Bitwise Operators print(a & b) System.out.print(a & b) 0 print(a | b) System.out.print(a | b) 6 print(a << 1) System.out.print(a << 1) 4 print(a >> 1) System.out.print(a >> 1) 1 print(a ^ b) System.out.print(a ^ b) 6 a = 2, b = 4
  16. 16. Logical Operators print(a and b) System.out.print(a && b) False print(a or b) System.out.print(a || b) True print(not a) System.out.print(!a) False a = True, b = False
  17. 17. 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; System.out.println(min); } }
  18. 18. Branching a = '' if a: print("Value of a = ", a) else: print("False value in a") a = 0 if a: print("Value of a = ", a) else: print("False value in a") a = -1 if a: print("Value of a = ", a) else: print("False value in a") a = False if a: print("Value of a = ", a) else: print("False value in a")
  19. 19. Branching class Main { public static void main(String[] args) { boolean a = true; if(a) System.out.println("A is true"); else System.out.println("A is false"); } } class Main { public static void main(String[] args) { int a = 5; if(a) System.out.println("A is true"); else System.out.println("A is false"); } }
  20. 20. 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) { System.out.println("a is greater than 3"); } else { System.out.println("a is greater than 3"); } } } }
  21. 21. Branching public class Main { public static void main(String[] args) { char grade = 'B'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } }
  22. 22. 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) { System.out.println(count); count = count + 1; } } }
  23. 23. 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; } System.out.println(count); count = count + 1; } } }
  24. 24. Looping count = 0 for count in range(0,9): if count == 4: continue print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) continue; System.out.println(count); } } } count = 0 for count in range(0,9): if count == 4: break print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) break; System.out.println(count); } } }
  25. 25. Looping count = 0 for count in range(0,9): if count == 4: continue else: print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) continue; else System.out.println(count); } } } count = 0 for count in range(0,9): if count == 4: pass print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) { } System.out.println(count); } } }
  26. 26. Looping x = 10 while True: print(x) x = x + 1 if x > 19: break public class Main { public static void main(String[] args) { int x = 10; do { System.out.print(x + "t"); x = x + 1; } while( x < 20 ); } }
  27. 27. Looping x = 10 while True: print(x) x = x + 1 if x > 19: break public class Main { public static void main(String[] args) { int i, j; for(i = 1; i < 5; i++) { System.out.println(); for(j = i; j > 0; j--) { System.out.print(j + " "); } } } }
  28. 28. Input age = input("Enter your age") print("Entered age is ", age) import java.util.Scanner; class Main { public static void main(String[] args) { int age; Scanner scanner = new Scanner(System.in); System.out.println("Enter your age"); age = scanner.nextInt(); System.out.println("Entered age is " + age); } }
  29. 29. Classes class Player: def __init__(self, name, role, rating): self.name = name self.role = role self.rating = rating class Player { String name; String role; int rating; Player(String name, String role, int rating) { this.name = name; this.role = role; this.rating = rating; } }
  30. 30. Creating Objects class Player: def __init__(self, name, role): self.name = name self.role = role def getRole(self): return self.role dhoni = Player("Dhoni", 'wicket keeper') yadav = Player("Yadav", 'bowler') print(dhoni.getRole()) print(yadav.getRole())
  31. 31. Creating Objects class Player { String name; String role; Player(String name, String role) { this.name = name; this.role = role; } String getRole() { return this.role; } } class Main { public static void main(String[] args) { Player dhoni = new Player("Dhoni", "wicket keeper"); Player yadav = new Player("Yadav", "bowler"); System.out.println(dhoni.getRole()); System.out.println(yadav.getRole()); } }
  32. 32. Creating Objects class Player: def __init__(self, name = "", role = ""): self.name = name self.role = role def getRole(self): return self.role dhoni = Player() yadav = Player("Yadav", 'bowler') print(dhoni.getRole()) print(yadav.getRole())
  33. 33. class Player { String name; String role; Player() { } Player(String name, String role) { this.name = name; this.role = role; } String getRole() { return this.role; } } class Main { public static void main(String[] args) { Player dhoni = new Player(); Player yadav = new Player("Yadav", "bowler"); System.out.println(dhoni.getRole()); System.out.println(yadav.getRole()); } } Creating Objects
  34. 34. Aggregation in Python class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = shoe shoe_eight = Shoe(8) shoe_seven = Shoe(7) dhoni = Player("Dhoni", shoe_eight) jaddu = Player("Jadeja", shoe_seven) print(dhoni.shoe.size) print(jaddu.shoe.size)
  35. 35. Aggregation in Java class Shoe { int size; Shoe(int size) { this.size = size; } } class Player { String name; Shoe shoe; Player(String name, Shoe shoe) { this.name = name; this.shoe = 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); System.out.println(dhoni.shoe.size); System.out.println(jaddu.shoe.size); } }
  36. 36. Googly class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = shoe def displayShoe(self): print(self.size) class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = shoe def displayShoe(self): print(self.shoe.size) shoe_eight = Shoe(8) shoe_seven = Shoe(7) dhoni = Player("Dhoni", shoe_eight) jaddu = Player("Jadeja", shoe_seven) dhoni.displayShoe() jaddu.displayShoe()
  37. 37. Swapped? class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = 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) dhoni.swap(jaddu) print(dhoni.shoe.size) print(jaddu.shoe.size)
  38. 38. class Shoe { int size; Shoe(int size) { this.size = size; } } class Player { String name; Shoe shoe; Player(String name, Shoe shoe) { this.name = name; this.shoe = shoe; } void swapShoe(Player other) { other.shoe = this.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); dhoni.swapShoe(jaddu); System.out.println(dhoni.shoe.size); System.out.println(jaddu.shoe.size); } } Swapped?
  39. 39. Association in Python class Bat: def __init__(self, company): self.company = company class Player: def __init__(self, name): self.name = name def batting(self, bat): print("I use " + bat.company) mrf = Bat("MRF Bat"); ss = Bat("SS Bat"); sachin = Player("Dhoni") dhoni = Player("Jadeja") dhoni.batting(mrf) sachin.batting(ss)
  40. 40. class Bat { String company; Bat(String company) { this.company = company; } } class Player { String name; Player(String name) { this.name = name; } void batting(Bat bat) { System.out.print("I use "); System.out.println(bat.company); } } 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); sachin.batting(mrf); dhoni.batting(ss); } } Association in Java
  41. 41. Difference between association & aggregation Instance Variable Local Variable
  42. 42. Inheritance class Employee: def __init__(self, id): self.id = id class FullTime(Employee): def __init__(self, id, name): super().__init__(id) self.name = name def printDetails(self): print(self.id, self.name) aravind = FullTime(1001, "Aravind") raghavan = FullTime(1002, "Raghavan") aravind.printDetails() raghavan.printDetails()
  43. 43. Inheritance class Employee { int id; Employee(int id) { this.id = id; } } class FullTime extends Employee { String name; FullTime(int id, String name) { super(id); this.name = name; } void printDetails() { System.out.print(this.id); System.out.println(this.name); } } class Main { public static void main(String a[]) { FullTime aravind = new FullTime(1001, "Aravind"); FullTime raghavan = new FullTime(1002, "Raghavan"); aravind.printDetails(); raghavan.printDetails(); } }
  44. 44. Inheritance class Employee: def __init__(self, id, private): self.id = id self.__private = private class FullTime(Employee): def __init__(self, id, name): super().__init__(id, "Something") self.name = name def printDetails(self): print(self.id, self.name) aravind = FullTime(1001, "Aravind") print(aravind.id) print(aravind.__private) #print(aravind._Employee__private) print(aravind.name)
  45. 45. Inheritance class Employee { private int id; Employee(int id) { this.id = id; } } class FullTime extends Employee { String name; FullTime(int id, String name) { super(id); this.name = name; } } class Main { public static void main(String a[]) { FullTime aravind = new FullTime(1001, "Aravind"); System.out.println(aravind.name); System.out.println(aravind.id); } }
  46. 46. Access Specifiers in Java Same Package Different Package Inside Class Outside Class Inherited Classes Other Classes public ✔ ✔ ✔ ✔ protected ✔ ✔ ✔ ✘ default ✔ ✔ ✘ ✘ private ✔ ✘ ✘ ✘
  47. 47. Calling inherited method class Employee: def __init__(self): pass def method(self): print("I am here") class FullTime(Employee): def __init__(self): self.method() aravind = FullTime()
  48. 48. Calling inherited method class Employee { void method() { System.out.println("I am here"); } } class FullTime extends Employee { public FullTime() { this.method(); } } class Demo01 { public static void main(String a[]) { FullTime aravind = new FullTime(); } }
  49. 49. Dynamic Polymorphism class Employee { void method() { System.out.println("I am here"); } } class FullTime extends Employee { void method() { System.out.println("FullTime"); } void myMethod() { System.out.println("myMethod"); } } class Demo01 { public static void main(String a[]) { Employee aravind = new FullTime(); aravind.method(); } }
  50. 50. Dynamic Polymorphism class Employee { void method() { System.out.println("I am here"); } } class FullTime extends Employee { void method() { System.out.println("FullTime"); } void myMethod() { System.out.println("myMethod"); } } class Demo01 { public static void main(String a[]) { Employee aravind = new FullTime(); aravind.myMethod(); } }
  51. 51. Abstract class from abc import ABC, abstractmethod class Employee(ABC): @abstractmethod def work(self): pass class FullTime(Employee): def work(self): print("50Hrs") class PartTime(Employee): def work(self): print("20Hrs") aravind = FullTime() aravind.work()
  52. 52. Abstract class abstract class Employee { abstract void work(); } class FullTime extends Employee { void work() { System.out.println("50Hrs"); } } class PartTime extends Employee { void work() { System.out.println("20Hrs"); } } class Main { public static void main(String a[]) { FullTime aravind = new FullTime(); aravind.work(); } }
  53. 53. 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?
  54. 54. 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; System.out.println("No exception"); } catch(Exception e) { System.out.println("Exception"); } } }
  55. 55. Exceptions! a = 5 b = 0 try: c = a / b print("No exception") except: print("Exception") finally: print("Anyways") class Main { public static void main(String args[]) { int a = 5, b = 0; try { int c = a / b; System.out.println("No exception"); } catch(Exception e) { System.out.println("Exception"); } finally { System.out.println("Anyways"); } } }
  56. 56. Our own exceptions class MyException(Exception): pass a = 5 b = 0 try: raise MyException() except: print("Exception") class MyException extends Exception { } class Main { public static void main(String args[]) { try { throw new MyException(); } catch(MyException e) { System.out.println("Exception"); } } }
  57. 57. 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 { Main.method(); } catch(Exception e) { System.out.println("Exception"); } } }
  58. 58. About a static class Animal: def walk(): print("Static method") dog = Animal() Animal.walk() dog.walk() class Animal { public static void method() { System.out.println("Static method"); } } class Main { public static void main(String[] args) { Animal dog = new Animal(); dog.method(); Animal.method(); } }
  59. 59. About a final class Animal { final int age = 5; } class Main { public static void main(String[] args) { Animal dog = new Animal(); dog.age = 10; } }
  60. 60. About a final class Animal { int age = 5; final void method() { System.out.println("A Method"); } } class Dog extends Animal { void method() { System.out.println("D Method"); } } class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.method(); } }
  61. 61. About a final final class Animal { int age = 5; void method() { System.out.println("A Method"); } } class Dog extends Animal { void method() { System.out.println("D Method"); } } class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.method(); } }
  62. 62. Creating connection import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) print(mydb) import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; class Demo01 { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); String conn = "jdbc:mysql://localhost:3306/test"; String user = "root"; String pwd = ""; Connection con = DriverManager.getConnection(conn, user, pwd); Statement stmt = con.createStatement(); } }
  63. 63. Selecting data import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) mycursor = mydb.cursor() mycursor.execute("select * from demo") myresult = mycursor.fetchall() for x in myresult: print(x) Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from demo"); while(rs.next()) { System.out.println(rs.getInt(1)); }
  64. 64. Inserting data import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) mycursor = mydb.cursor() sql = "insert into demo (id) values (%s)" val = (4,) mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.") PreparedStatement stmt=con.prepareStatement("insert into demo (id) values (?)"); stmt.setInt(1,5); int i=stmt.executeUpdate(); System.out.println(i+" records inserted.");
  65. 65. Updating data import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) mycursor = mydb.cursor() sql = "udpate demo set id = 1 where id = 2" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record updated.") PreparedStatement stmt=con.prepareStatement("update demo set id = (?) where id = 4"); stmt.setInt(1,5); int i=stmt.executeUpdate(); System.out.println(i+" records inserted.");
  66. 66. Hashing the passwords import hashlib result = hashlib.md5(b'MyPassword') print("Hashed Password ", end ="") print(result.hexdigest()) String myPassword = "MyPassword"; MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(myPassword.getBytes()); BigInteger no = new BigInteger(1, messageDigest); String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } System.out.println("Hashed Password: " + hashtext);
  67. 67. Encrypting a string String key = "someKey"; String initVector = "someIntVec"; String myPassword = "MyPassword"; IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(myPassword.getBytes()); String encryptedString = Base64.getEncoder().encodeToString(encrypted); System.out.println(encryptedString); cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedString)); System.out.println(new String(original));
  68. 68. Encrypting a string from cryptography.fernet import Fernet message = "my deep dark secret".encode() key = Fernet.generate_key() f = Fernet(key) encrypted = f.encrypt(message) print(encrypted) decrypted = f.decrypt(encrypted) print(decrypted.decode())
  69. 69. File Writing fo = open("E:/output.txt", "a") fo.write( "Text from pythonn") fo.close() String str = "My text is heren"; FileWriter fw=new FileWriter("E:/output.txt", true); for (int i = 0; i < str.length(); i++) fw.write(str.charAt(i)); System.out.println("Writing successful"); fw.close();
  70. 70. File Reading fo = open("E:/output.txt", "r") for x in fo: print(x) fo.close() File file = new File("E:/output.txt"); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } fileReader.close();
  71. 71. Threads in Python import threading import time fo = open("E:/output.txt", "a") def jobA(): for x in range(1, 999): fo.write("An") if x % 100 == 0: time.sleep(1) print("Some random job A") def jobB(): for x in range(1, 999): fo.write("Booooooon") if x % 100 == 0: time.sleep(1) print("Some random job B")
  72. 72. Threads in Python t1 = threading.Thread(target=jobA) t2 = threading.Thread(target=jobB) t1.start() t2.start() t1.join() t2.join() fo.close()
  73. 73. Threads in Java class Multi extends Thread{ public void run(){ for(int i = 0; i < 999; i++) { System.out.println(Thread.currentThread().getName()); if(i % 100 == 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
  74. 74. Threads in Java class Main { public static void main(String[] args) throws Exception { Multi t1=new Multi(); t1.setName("A"); Multi t2 = new Multi(); t2.setName("Booooo"); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Done!"); } }
  75. 75. Introduction WEB SERVER WEB CLIENT HTTP REQUEST HTTP RESPONSE
  76. 76. Process 1 R e c e i v e t h e r e q u e s t 2 S e a r c h f o r t h e f i l e 3 P r o v i d e t h e r e s p o n s e
  77. 77. Web Server
  78. 78. Getting python CGI right Check in browser Add shebang line & Execute your python Start Apache Download XAMPP Install Run & start apache Config apache Open xampp/apache/conf/http d.conf Add AddHandler cgi-script .py ScriptInterpreterSource Registry-Strict at the end of the file
  79. 79. First CGI Page #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Content-type:text/htmlrnrn") 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>')
  80. 80. How about this form? #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Content-type:text/htmlrnrn") 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> ''')
  81. 81. How about this form? #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Content-type:text/htmlrnrn") 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> ''')
  82. 82. Get in server #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe import cgi, cgitb form = cgi.FieldStorage() first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print("Content-type:text/htmlrnrn") 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>")
  83. 83. Lets have some cookies #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe 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/htmlrnrn") print('''I have set some cookie''')
  84. 84. Lets have some cookies #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe 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/htmlrnrn") print('''I have set some cookie''')
  85. 85. Reading the cookies #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe from os import environ import cgi, cgitb print("Content-type:text/htmlrnrn") if environ['HTTP_COOKIE']: allCookies = environ['HTTP_COOKIE'].split(';') for cookie in allCookies: print(cookie.split("=")) else: print("no cookie")
  86. 86. Process Run on Server Create HTML / JSP Run the file on server Install Tomcat Download Tomcat Unzip the downloaded file Create Dynamic Web Create dynamic web project Select run time as Tomcat with proper version
  87. 87. 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="process.jsp" 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>
  88. 88. 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=request.getParameter("first_name"); out.print("welcome "+name); %> </body> </html>
  89. 89. 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"); response.addCookie(cookie); %> <form action="process.jsp" 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>
  90. 90. 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 = request.getCookies(); if( cookies != null ) { for (int i = 0; i < cookies.length; i++) { out.print("Name : " + cookies[i].getName( ) + ", "); out.print("Value: " + cookies[i].getValue( )+" <br/>"); } } %> </body> </html>
  91. 91. Thank You https://codemithra.com <Codemithra />

×