SlideShare uma empresa Scribd logo
1 de 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);
}
}

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
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
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Último (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
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...
 
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...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

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); } }