KEMBAR78
Java - A broad introduction | PPTX
JAVA
A BROAD INTRODUCTION
• Programming Languages in the
web development
• What is Java and where is it used
• OOP PRINCIPLES
• JAVA SE, JRE, JDK
• IDE’s
• Where Java used in the “Real
World”
What is Java and where is it used
Programming Languages in the web
development
Programming
Language
Description Pro Con
C# auf ASP.net direct rival not only restricted to web development Interoperability - Runs only really
good on Microsoft Server
Ruby good and new concepts and conventions (not as wide spread)
PHP very popular,
good for small projects (if one server for mulptiple
customer, few requests),
good security features,
limitation of RAM usage
Not ideal for big projects
all lot of features where added later
on (OOP, Security features)
Python science area good for small projects python-interpreter gets called for
every request (CPU time) ->
troublesome with a lot of requests
Perl difficult syntax
outdated („‚Write once, never read
again‘)
Java “Run anywhere” (Interoperability)
* General language
* Web development, mobile applications, embedded
systems (eg chip cards)
* Clean
* Boards come together for language changes
* Concurrency
* Multithreading
*Distributed
*Secure
* Relatively complex because of
many features
* good in big projects
* GUI (AWT and Swing)
* +/- fast, but still slower than C or
C++
WHAT:
TYPICIAL OOP LANGUAGE
CREATE ALL KIND OF APPS,
JAVA (SERVER SIDE) AND JAVASCRIPT (CLIENT SIDE) HAS
NOTHING TO DO WITH EACH OTHER
WHERE:
ANDROID,
FINANCIAL (MUREX),
IDE’S (NETBEANS, ECLIPSE),
EMBEDDED SYSTEMS,
GAMING (MINECRAFT)
What is Java and where
is it used
OOP PRINCIPLES
1. Encapsulation
2. Inheritance
3. Abstraction
4. Polymorphism
- We do not see how a phone works or remote control works, we just press the
button and you're done
- same thing with code
- only what I need, should be visible, the rest „private“
- Use Getters and Setters (control what to see and write)
- do logical code blocks in own methods (analogous to the interface of a telephone /
machine (do not want to know more about the procedure than necessary)
- break the code modular pieces (granularity)
- Tip: Put methods in their own helper classes that can be used throughout the system
- my own little library
- Ideally do models in their own package "model" where objects are stuck (eg Olive,
Hero, Customer, Book, ...)
OOP PRINCIPLES -
ENCAPSULATION
GETTING STARTED
● Developers need JDK (compiler, debuggers, tools to create
programs)
Optional
◦ Java Application Server (z. B. Tomcat)
◦ IDE (z. B. Eclipse, Netbeans, Intellij)
Source: https://stackoverflow.com/questions/1906445/what-is-the-difference-between-jdk-and-
jre
JAVA SE, JRE, JDK
JRE:
Basic Java Runtime
Environment.
Her is the Java Virtual
Machine
JDK:
Add tools for
Developers to compile
Code
POPULAR IDE
• Eclipse (free)
• Netbeans
• IntelliJ IDEA
• BlueJ
• Sidenote: Jshell (since Java 9)
IDE DEBUGGING EXAMPLE -
DEBUGGING DURING RUNTIME
Eclipse
IntelliJ
IDEA
DEMO (IDE - ECLIPSE)
DEBUGGING - DISPLAY VIEW
Maven
(Build Projekt)
Java Code Display Code
(Debugging Helper)
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.testmaven</groupId>
<artifactId>birolmaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>birolmaven</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-
8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package com.testlynda.birolexamples;
import java.util.Scanner;
public class testConversion {
public static void main(String[] args) {
/* Challenge: Paint a house */
House myHouse = new House();
// Ask the user for the house
length, the width and the height.
Scanner scan = new
Scanner(system.in);
System.out.println("house
length:");
myHouse.length =
Double.parseDouble(scan.nextLine());
System.out.println("house width:");
myHouse.width =
Double.parseDouble(scan.nextLine());
System.out.println("house
height:");
myHouse.height =
Double.parseDouble(scan.nextLine());
// Ask for the number and size of
the windows.
System.out.println("Number of the
windows:");
myHouse.numberWindows =
Integer.parseInt(scan.nextLine());
System.out.println("Width of the
(myHouse.width * myHouse.height * 2 + myHouse.length *
myHouse.width * 2)
-
(myHouse.numberWindows * myHouse.sizeWindowsWidth
*myHouse.sizeWindowsHeight)
-
(myHouse.numberDoors * myHouse.sizeDoorsWidth *
myHouse.sizeDoorsHeight)
Usage for projects
● basically anywhere in the industry (
e. g. material flows)
● E-commerce
● Reservation pages
● Administration pages (Address,
Students etc.)
● Real World Examples
games (minecraft)
● Ebay.com
● BMW
● Toys R Us
● Freitag
● Garmin International
● Condor
● NH Hotels
Where Java used in the “Real World”
OOP - ENCASULATION
SIMPLE EXAMPLE
package OOP;
public class ErsteKlasse {
public static void main(String[]
args) {
Konto meinKonto = new
Konto();
meinKonto.einzahlen(33.11);
System.out.println(meinKonto.getKo
ntostand());
}
}
class Konto {
String besitzer;
private double kontostand;
void einzahlen(double betrag) {
this.kontostand += betrag;
}
void abheben( double betrag ) {
this.kontostand -= betrag;
}
double getKontostand() {
return this.kontostand;
}
}
OOP PRINCIPLES -
INHERITANCE
- Ideal to pass standard values and methods
- Deepening towards "Abstract", "Interfaces" and
"Polymorphism"
- Ideally in the superclass:
- Encapsulate methods and variables as needed
(encapsulation)
- then use getters and setters for variables
OOP - ENCASULATION
SIMPLE EXAMPLE
package OOP;
public class ErsteKlasse {
public static void main(String[] args) {
Konto meinKonto = new Konto();
meinKonto.einzahlen(33.11);
System.out.println(meinKonto.getKontostand());
}
}
class Konto {
String besitzer;
double kontostand;
void einzahlen(double betrag) {
this.kontostand += betrag;
}
void abheben( double betrag ) {
this.kontostand -= betrag;
}
double getKontostand() {
return this.kontostand;
}
}
Abstract methods may only be in abstract classes (see
„zeichneMich()“-Method)
* Attention: no code block "{}", which is the method of the child
class
* for example circle, triangle, pentagon must definitely be
overwritten
The inherited father class (here „GeoForm“) forces the child class
"circle"
to use the „draw()“-method to use it or override.
* Useful, because every geometric class is drawn differently !!
OOP PRINCIPLES - ABSTRACTION
OOP - ABSTRACT VS INTERFACE
(SOURCE: STACKOVERFLOW)
Interface (implements):
In general, interfaces should be used to define
contracts (what is to be achieved, not how to achieve
it).
1. A class can implement multiple interfaces
2. An interface cannot provide any code at all
3. An interface can only define public static
final constants
4. An interface cannot define instance
variables
5. Adding a new method has ripple effects
on implementing classes (design maintenance)
6. An interface cannot extends or implement
an abstract class
7. All interface methods are public
Abstract Class (extends):
Abstract classes should be used for (partial)
implementation. They can be a mean to restrain the
way API contracts should be implemented.
1. A class can extend at most one abstract
class
2. An abstract class can contain code
3. An abstract class can define both static and
instance constants (final)
4. An abstract class can define instance
variables
5. Modification of existing abstract class code
has ripple effects on extending classes
(implementation maintenance)
6. Adding a new method to an abstract class
has no ripple effect on extending classes (Using both,
abstract and interface)
7. An abstract class can implement an
interface
OOP PRINCIPLES - ABSTRACTION (LAT. TAKE SO. OFF,
DIVIDE) - SIMPLE EXAMPLE
package vererbung.ABSTRAKT;
abstract class GeoForm {
private String name;
private int xpos, ypos;
GeoForm() {
this.xpos = 0;
this.ypos = 0;
}
GeoForm(String name) {
this(); //Ruft Standardkonstrukt Nr.
1 auf (s.o.)
this.name = name;
}
abstract void zeichneMich();
}
package vererbung.ABSTRAKT;
public class Kreis extends GeoForm {
Kreis()
{
super();
}
Kreis( String name )
{
super( name );
}
void zeichneMich()
{
// Draw a circle implementation
}
}
OOP PRINCIPLES - POLYMORPHISM
Etymologie: Poly = many: polygon, Morph = Chance
• Examples:
• Animals
• Dog, Cat, Lion, … more to come
• doShout()
• Person
• Butcher, Actor, Hairdresser -
• cut()
Advantage: Reuse code, Maintenance, Overwriting and
Overloading
OOP - POLYMORPHISM - SIMPLE EXAMPLE
package polymorphism.beispiel4;
import java.util.Vector;
abstract class Figur
{
abstract double getFlaeche();
}
class Rechteck extends Figur
{
private double a, b;
public Rechteck( double a, double b )
{
this.a = a;
this.b = b;
}
public double getFlaeche()
{
return a * b;
}
}
class Kreis extends Figur
{
private double r;
public Kreis( double r )
{
this.r = r;
}
public double getFlaeche()
{
return Math.PI * r * r;
}
}
package polymorphism.beispiel4;
import java.util.Vector;
public class Polymorphie
{
public static void main( String[] args )
{
double flaeche = 0;
// Instanziiere Figur-Objekte
Rechteck re1 = new Rechteck( 3, 4 );
Figur re2 = new Rechteck( 5, 6 );
Kreis kr1 = new Kreis( 7 );
Figur kr2 = new Kreis( 8 );
Vector vec = new Vector();
// Fuege beliebig viele beliebige Figuren hinzu
vec.add( re1 );
vec.add( re2 );
vec.add( kr1 );
vec.add( kr2 );
// Berechne die Summe der Flaechen aller Figuren:
for( int i=0; i< vec.size(); i++ )
{
Figur f = (Figur)(vec.get( i ));
flaeche += f.getFlaeche();
}
System.out.println( "Gesamtflaeche ist: " + flaeche );
}
}
Integration
Layer
Business
Layer
Presentation
Layer
JEE OVERVIEW
What are JSP’s and Servlets
● MVC Frameworks
○ Spring, Spring Boot, JSF,
Struts
○ nutzen im Hintergrund die
JSP’s und Servlets im auf
Low Level Ebene
● JSP
○ View of our Webapp
○ HTML with some Java
○ Info: Don’t put business
logic in the view
● Servlet
○ counterpiece that runs on
the server
○ handles the request and
reponse
JSP
JSP Description
● Syntax
○ <%= %>
○ Codesample
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Testseite</title>
</head>
<body>
<p>"java.util.Date" is inside by default</p>
Time: <%= new java.util.Date() %>
</body>
</html>
● Compare JSP with rendered HTML:
● Include dynamic content from Java code
● processed on the server
● Result is rendered HTML (to browser)
Filestructure:
Servlet
Servlet web.xml (configure servlet maaping)
package com.servlet.explore;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out =
response.getWriter();
out.print("<h1>Hallo,
hier eine Ausgabe vom Servlet.</h1> Bin Ihnen
zu Dienst, <b>Herr Client!</b>");
}
protected void doPost(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated
method stub
}
}
<?xml version="1.0" encoding="UTF-8"?>
…….
<!-- Example HelloWorldServlet -->
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>com.servlet.explore.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
JDBC (simple DB Connection)
Java Code
……..
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
myConn = dataSource.getConnection();
String sql = "select * from student";
myStmt = myConn.createStatement();
myRs = myStmt.executeQuery(sql);
while (myRs.next()) {
String email = myRs.getString("email");
out.println(email);
}
}
catch (Exception exc) {
exc.printStackTrace();
}
…..
MVC Pattern - JSP + Serverlet + JDBC
View - Controller
View Controller
<div id="container">
<h3>Add Student</h3>
<form
action="StudentControllerServlet"
method="GET">
<input type="hidden"
name="command" value="ADD" />
<table>
<tbody>
<tr>
<td><label>First
name:</label></td>
<td><input type="text"
name="firstName" /></td>
</tr>
<tr>
<td><label>Last
name:</label></td>
<td><input type="text"
name="lastName" /></td>
</tr>
<tr>
<td><label>Email:</label></td>
<td><input type="text"
name="email" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit"
…..
@Override
public void init() throws ServletException {
super.init();
// create our student db util ... and pass in the conn
pool / datasource
try {
studentDbUtil = new StudentDbUtil(dataSource);
}
catch (Exception exc) {
throw new ServletException(exc);
}
}
….
….
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
try {
// read the "command" parameter
String theCommand =
request.getParameter("command");
// if the command is missing, then default to listing
students
if (theCommand == null) {
theCommand = "LIST";
}
// route to the appropriate method
switch (theCommand) {
case "LIST":
listStudents(request, response);
break;
case "ADD":
addStudent(request, response);
break;
…….
private void listStudents(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
View - Controller (2)
addStudent (Controller) DBUtil.java
private void
addStudent(HttpServletRequest request,
HttpServletResponse response) throws
Exception {
// read student info from form data
String firstName =
request.getParameter("firstName");
String lastName =
request.getParameter("lastName");
String email =
request.getParameter("email");
// create a new student object
Student theStudent = new
Student(firstName, lastName, email);
// add the student to the database
studentDbUtil.addStudent(theStudent);
// send back to main page (the student
list)
listStudents(request, response);
}
public void addStudent(Student theStudent) throws
Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
// get db connection
myConn = dataSource.getConnection();
// create sql for insert
String sql = "insert into student "
+ "(first_name, last_name, email) "
+ "values (?, ?, ?)";
myStmt = myConn.prepareStatement(sql);
// set the param values for the student
myStmt.setString(1, theStudent.getFirstName());
myStmt.setString(2, theStudent.getLastName());
myStmt.setString(3, theStudent.getEmail());
// execute sql insert
myStmt.execute();
}
finally {
// clean up JDBC objects
close(myConn, myStmt, null);
}
}

Java - A broad introduction

  • 1.
  • 2.
    • Programming Languagesin the web development • What is Java and where is it used • OOP PRINCIPLES • JAVA SE, JRE, JDK • IDE’s • Where Java used in the “Real World” What is Java and where is it used
  • 3.
    Programming Languages inthe web development Programming Language Description Pro Con C# auf ASP.net direct rival not only restricted to web development Interoperability - Runs only really good on Microsoft Server Ruby good and new concepts and conventions (not as wide spread) PHP very popular, good for small projects (if one server for mulptiple customer, few requests), good security features, limitation of RAM usage Not ideal for big projects all lot of features where added later on (OOP, Security features) Python science area good for small projects python-interpreter gets called for every request (CPU time) -> troublesome with a lot of requests Perl difficult syntax outdated („‚Write once, never read again‘) Java “Run anywhere” (Interoperability) * General language * Web development, mobile applications, embedded systems (eg chip cards) * Clean * Boards come together for language changes * Concurrency * Multithreading *Distributed *Secure * Relatively complex because of many features * good in big projects * GUI (AWT and Swing) * +/- fast, but still slower than C or C++
  • 4.
    WHAT: TYPICIAL OOP LANGUAGE CREATEALL KIND OF APPS, JAVA (SERVER SIDE) AND JAVASCRIPT (CLIENT SIDE) HAS NOTHING TO DO WITH EACH OTHER WHERE: ANDROID, FINANCIAL (MUREX), IDE’S (NETBEANS, ECLIPSE), EMBEDDED SYSTEMS, GAMING (MINECRAFT) What is Java and where is it used
  • 5.
    OOP PRINCIPLES 1. Encapsulation 2.Inheritance 3. Abstraction 4. Polymorphism
  • 6.
    - We donot see how a phone works or remote control works, we just press the button and you're done - same thing with code - only what I need, should be visible, the rest „private“ - Use Getters and Setters (control what to see and write) - do logical code blocks in own methods (analogous to the interface of a telephone / machine (do not want to know more about the procedure than necessary) - break the code modular pieces (granularity) - Tip: Put methods in their own helper classes that can be used throughout the system - my own little library - Ideally do models in their own package "model" where objects are stuck (eg Olive, Hero, Customer, Book, ...) OOP PRINCIPLES - ENCAPSULATION
  • 7.
    GETTING STARTED ● Developersneed JDK (compiler, debuggers, tools to create programs) Optional ◦ Java Application Server (z. B. Tomcat) ◦ IDE (z. B. Eclipse, Netbeans, Intellij)
  • 8.
    Source: https://stackoverflow.com/questions/1906445/what-is-the-difference-between-jdk-and- jre JAVA SE,JRE, JDK JRE: Basic Java Runtime Environment. Her is the Java Virtual Machine JDK: Add tools for Developers to compile Code
  • 9.
    POPULAR IDE • Eclipse(free) • Netbeans • IntelliJ IDEA • BlueJ • Sidenote: Jshell (since Java 9)
  • 10.
    IDE DEBUGGING EXAMPLE- DEBUGGING DURING RUNTIME Eclipse IntelliJ IDEA
  • 11.
    DEMO (IDE -ECLIPSE) DEBUGGING - DISPLAY VIEW Maven (Build Projekt) Java Code Display Code (Debugging Helper) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.testmaven</groupId> <artifactId>birolmaven</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>birolmaven</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF- 8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> package com.testlynda.birolexamples; import java.util.Scanner; public class testConversion { public static void main(String[] args) { /* Challenge: Paint a house */ House myHouse = new House(); // Ask the user for the house length, the width and the height. Scanner scan = new Scanner(system.in); System.out.println("house length:"); myHouse.length = Double.parseDouble(scan.nextLine()); System.out.println("house width:"); myHouse.width = Double.parseDouble(scan.nextLine()); System.out.println("house height:"); myHouse.height = Double.parseDouble(scan.nextLine()); // Ask for the number and size of the windows. System.out.println("Number of the windows:"); myHouse.numberWindows = Integer.parseInt(scan.nextLine()); System.out.println("Width of the (myHouse.width * myHouse.height * 2 + myHouse.length * myHouse.width * 2) - (myHouse.numberWindows * myHouse.sizeWindowsWidth *myHouse.sizeWindowsHeight) - (myHouse.numberDoors * myHouse.sizeDoorsWidth * myHouse.sizeDoorsHeight)
  • 12.
    Usage for projects ●basically anywhere in the industry ( e. g. material flows) ● E-commerce ● Reservation pages ● Administration pages (Address, Students etc.) ● Real World Examples games (minecraft) ● Ebay.com ● BMW ● Toys R Us ● Freitag ● Garmin International ● Condor ● NH Hotels Where Java used in the “Real World”
  • 13.
    OOP - ENCASULATION SIMPLEEXAMPLE package OOP; public class ErsteKlasse { public static void main(String[] args) { Konto meinKonto = new Konto(); meinKonto.einzahlen(33.11); System.out.println(meinKonto.getKo ntostand()); } } class Konto { String besitzer; private double kontostand; void einzahlen(double betrag) { this.kontostand += betrag; } void abheben( double betrag ) { this.kontostand -= betrag; } double getKontostand() { return this.kontostand; } }
  • 14.
    OOP PRINCIPLES - INHERITANCE -Ideal to pass standard values and methods - Deepening towards "Abstract", "Interfaces" and "Polymorphism" - Ideally in the superclass: - Encapsulate methods and variables as needed (encapsulation) - then use getters and setters for variables
  • 15.
    OOP - ENCASULATION SIMPLEEXAMPLE package OOP; public class ErsteKlasse { public static void main(String[] args) { Konto meinKonto = new Konto(); meinKonto.einzahlen(33.11); System.out.println(meinKonto.getKontostand()); } } class Konto { String besitzer; double kontostand; void einzahlen(double betrag) { this.kontostand += betrag; } void abheben( double betrag ) { this.kontostand -= betrag; } double getKontostand() { return this.kontostand; } }
  • 16.
    Abstract methods mayonly be in abstract classes (see „zeichneMich()“-Method) * Attention: no code block "{}", which is the method of the child class * for example circle, triangle, pentagon must definitely be overwritten The inherited father class (here „GeoForm“) forces the child class "circle" to use the „draw()“-method to use it or override. * Useful, because every geometric class is drawn differently !! OOP PRINCIPLES - ABSTRACTION
  • 17.
    OOP - ABSTRACTVS INTERFACE (SOURCE: STACKOVERFLOW) Interface (implements): In general, interfaces should be used to define contracts (what is to be achieved, not how to achieve it). 1. A class can implement multiple interfaces 2. An interface cannot provide any code at all 3. An interface can only define public static final constants 4. An interface cannot define instance variables 5. Adding a new method has ripple effects on implementing classes (design maintenance) 6. An interface cannot extends or implement an abstract class 7. All interface methods are public Abstract Class (extends): Abstract classes should be used for (partial) implementation. They can be a mean to restrain the way API contracts should be implemented. 1. A class can extend at most one abstract class 2. An abstract class can contain code 3. An abstract class can define both static and instance constants (final) 4. An abstract class can define instance variables 5. Modification of existing abstract class code has ripple effects on extending classes (implementation maintenance) 6. Adding a new method to an abstract class has no ripple effect on extending classes (Using both, abstract and interface) 7. An abstract class can implement an interface
  • 18.
    OOP PRINCIPLES -ABSTRACTION (LAT. TAKE SO. OFF, DIVIDE) - SIMPLE EXAMPLE package vererbung.ABSTRAKT; abstract class GeoForm { private String name; private int xpos, ypos; GeoForm() { this.xpos = 0; this.ypos = 0; } GeoForm(String name) { this(); //Ruft Standardkonstrukt Nr. 1 auf (s.o.) this.name = name; } abstract void zeichneMich(); } package vererbung.ABSTRAKT; public class Kreis extends GeoForm { Kreis() { super(); } Kreis( String name ) { super( name ); } void zeichneMich() { // Draw a circle implementation } }
  • 19.
    OOP PRINCIPLES -POLYMORPHISM Etymologie: Poly = many: polygon, Morph = Chance • Examples: • Animals • Dog, Cat, Lion, … more to come • doShout() • Person • Butcher, Actor, Hairdresser - • cut() Advantage: Reuse code, Maintenance, Overwriting and Overloading
  • 20.
    OOP - POLYMORPHISM- SIMPLE EXAMPLE package polymorphism.beispiel4; import java.util.Vector; abstract class Figur { abstract double getFlaeche(); } class Rechteck extends Figur { private double a, b; public Rechteck( double a, double b ) { this.a = a; this.b = b; } public double getFlaeche() { return a * b; } } class Kreis extends Figur { private double r; public Kreis( double r ) { this.r = r; } public double getFlaeche() { return Math.PI * r * r; } } package polymorphism.beispiel4; import java.util.Vector; public class Polymorphie { public static void main( String[] args ) { double flaeche = 0; // Instanziiere Figur-Objekte Rechteck re1 = new Rechteck( 3, 4 ); Figur re2 = new Rechteck( 5, 6 ); Kreis kr1 = new Kreis( 7 ); Figur kr2 = new Kreis( 8 ); Vector vec = new Vector(); // Fuege beliebig viele beliebige Figuren hinzu vec.add( re1 ); vec.add( re2 ); vec.add( kr1 ); vec.add( kr2 ); // Berechne die Summe der Flaechen aller Figuren: for( int i=0; i< vec.size(); i++ ) { Figur f = (Figur)(vec.get( i )); flaeche += f.getFlaeche(); } System.out.println( "Gesamtflaeche ist: " + flaeche ); } }
  • 21.
  • 22.
    What are JSP’sand Servlets ● MVC Frameworks ○ Spring, Spring Boot, JSF, Struts ○ nutzen im Hintergrund die JSP’s und Servlets im auf Low Level Ebene ● JSP ○ View of our Webapp ○ HTML with some Java ○ Info: Don’t put business logic in the view ● Servlet ○ counterpiece that runs on the server ○ handles the request and reponse
  • 23.
    JSP JSP Description ● Syntax ○<%= %> ○ Codesample <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Testseite</title> </head> <body> <p>"java.util.Date" is inside by default</p> Time: <%= new java.util.Date() %> </body> </html> ● Compare JSP with rendered HTML: ● Include dynamic content from Java code ● processed on the server ● Result is rendered HTML (to browser) Filestructure:
  • 24.
    Servlet Servlet web.xml (configureservlet maaping) package com.servlet.explore; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public HelloWorldServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.print("<h1>Hallo, hier eine Ausgabe vom Servlet.</h1> Bin Ihnen zu Dienst, <b>Herr Client!</b>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } <?xml version="1.0" encoding="UTF-8"?> ……. <!-- Example HelloWorldServlet --> <servlet> <servlet-name>HelloWorldServlet</servlet-name> <servlet-class>com.servlet.explore.HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldServlet</servlet-name> <url-pattern>/HelloWorldServlet</url-pattern> </servlet-mapping> </web-app>
  • 25.
    JDBC (simple DBConnection) Java Code …….. PrintWriter out = response.getWriter(); response.setContentType("text/plain"); Connection myConn = null; Statement myStmt = null; ResultSet myRs = null; try { myConn = dataSource.getConnection(); String sql = "select * from student"; myStmt = myConn.createStatement(); myRs = myStmt.executeQuery(sql); while (myRs.next()) { String email = myRs.getString("email"); out.println(email); } } catch (Exception exc) { exc.printStackTrace(); } …..
  • 26.
    MVC Pattern -JSP + Serverlet + JDBC
  • 27.
    View - Controller ViewController <div id="container"> <h3>Add Student</h3> <form action="StudentControllerServlet" method="GET"> <input type="hidden" name="command" value="ADD" /> <table> <tbody> <tr> <td><label>First name:</label></td> <td><input type="text" name="firstName" /></td> </tr> <tr> <td><label>Last name:</label></td> <td><input type="text" name="lastName" /></td> </tr> <tr> <td><label>Email:</label></td> <td><input type="text" name="email" /></td> </tr> <tr> <td><label></label></td> <td><input type="submit" ….. @Override public void init() throws ServletException { super.init(); // create our student db util ... and pass in the conn pool / datasource try { studentDbUtil = new StudentDbUtil(dataSource); } catch (Exception exc) { throw new ServletException(exc); } } …. …. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // read the "command" parameter String theCommand = request.getParameter("command"); // if the command is missing, then default to listing students if (theCommand == null) { theCommand = "LIST"; } // route to the appropriate method switch (theCommand) { case "LIST": listStudents(request, response); break; case "ADD": addStudent(request, response); break; ……. private void listStudents(HttpServletRequest request, HttpServletResponse response) throws Exception {
  • 28.
    View - Controller(2) addStudent (Controller) DBUtil.java private void addStudent(HttpServletRequest request, HttpServletResponse response) throws Exception { // read student info from form data String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); // create a new student object Student theStudent = new Student(firstName, lastName, email); // add the student to the database studentDbUtil.addStudent(theStudent); // send back to main page (the student list) listStudents(request, response); } public void addStudent(Student theStudent) throws Exception { Connection myConn = null; PreparedStatement myStmt = null; try { // get db connection myConn = dataSource.getConnection(); // create sql for insert String sql = "insert into student " + "(first_name, last_name, email) " + "values (?, ?, ?)"; myStmt = myConn.prepareStatement(sql); // set the param values for the student myStmt.setString(1, theStudent.getFirstName()); myStmt.setString(2, theStudent.getLastName()); myStmt.setString(3, theStudent.getEmail()); // execute sql insert myStmt.execute(); } finally { // clean up JDBC objects close(myConn, myStmt, null); } }