SlideShare ist ein Scribd-Unternehmen logo
1 von 28
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);
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Altece
 
XUL - Mozilla Application Framework
XUL - Mozilla Application FrameworkXUL - Mozilla Application Framework
XUL - Mozilla Application FrameworkUldis Bojars
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Gentle Intro to Drupal Code
Gentle Intro to Drupal CodeGentle Intro to Drupal Code
Gentle Intro to Drupal CodeAddison Berry
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming IntroLou Loizides
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLou Loizides
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Aaron Gustafson
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans Fabrizio Giudici
 
Visualizing MVC, and an introduction to Giotto
Visualizing MVC, and an introduction to GiottoVisualizing MVC, and an introduction to Giotto
Visualizing MVC, and an introduction to Giottopriestc
 
Type script, for dummies
Type script, for dummiesType script, for dummies
Type script, for dummiessantiagoaguiar
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 
Binaries Are Not Only Output
Binaries Are Not Only OutputBinaries Are Not Only Output
Binaries Are Not Only OutputHajime Morrita
 
Machine learning on source code
Machine learning on source codeMachine learning on source code
Machine learning on source codesource{d}
 
On the Edge Systems Administration with Golang
On the Edge Systems Administration with GolangOn the Edge Systems Administration with Golang
On the Edge Systems Administration with GolangChris McEniry
 

Was ist angesagt? (20)

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
XUL - Mozilla Application Framework
XUL - Mozilla Application FrameworkXUL - Mozilla Application Framework
XUL - Mozilla Application Framework
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
Gentle Intro to Drupal Code
Gentle Intro to Drupal CodeGentle Intro to Drupal Code
Gentle Intro to Drupal Code
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
AFPS_2011
AFPS_2011AFPS_2011
AFPS_2011
 
Visualizing MVC, and an introduction to Giotto
Visualizing MVC, and an introduction to GiottoVisualizing MVC, and an introduction to Giotto
Visualizing MVC, and an introduction to Giotto
 
Type script, for dummies
Type script, for dummiesType script, for dummies
Type script, for dummies
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
All of javascript
All of javascriptAll of javascript
All of javascript
 
Binaries Are Not Only Output
Binaries Are Not Only OutputBinaries Are Not Only Output
Binaries Are Not Only Output
 
Machine learning on source code
Machine learning on source codeMachine learning on source code
Machine learning on source code
 
On the Edge Systems Administration with Golang
On the Edge Systems Administration with GolangOn the Edge Systems Administration with Golang
On the Edge Systems Administration with Golang
 

Ähnlich wie Java: A Broad Introduction to Programming Languages, OOP Principles, and Real-World Usage

"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James NelsonGWTcon
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGuillaume Laforge
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!Alessandro Giorgetti
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Titanium appcelerator best practices
Titanium appcelerator best practicesTitanium appcelerator best practices
Titanium appcelerator best practicesAlessio Ricco
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoveragemlilley
 
Node.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsNode.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsManuel Eusebio de Paz Carmona
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebMikel Torres Ugarte
 

Ähnlich wie Java: A Broad Introduction to Programming Languages, OOP Principles, and Real-World Usage (20)

"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific Languages
 
Why Ruby?
Why Ruby? Why Ruby?
Why Ruby?
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Basics of C
Basics of CBasics of C
Basics of C
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
React native
React nativeReact native
React native
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Titanium appcelerator best practices
Titanium appcelerator best practicesTitanium appcelerator best practices
Titanium appcelerator best practices
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
Node.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsNode.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first steps
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
API Design
API DesignAPI Design
API Design
 
Java1 in mumbai
Java1 in mumbaiJava1 in mumbai
Java1 in mumbai
 
Node azure
Node azureNode azure
Node azure
 

Kürzlich hochgeladen

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Kürzlich hochgeladen (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Java: A Broad Introduction to Programming Languages, OOP Principles, and Real-World Usage

  • 2. • 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
  • 3. 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++
  • 4. 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
  • 5. OOP PRINCIPLES 1. Encapsulation 2. Inheritance 3. Abstraction 4. Polymorphism
  • 6. - 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
  • 7. GETTING STARTED ● Developers need 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 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; } }
  • 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 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; } }
  • 16. 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
  • 17. 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
  • 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 ); } }
  • 22. 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
  • 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 (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>
  • 25. 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(); } …..
  • 26. MVC Pattern - JSP + Serverlet + JDBC
  • 27. 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 {
  • 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); } }