11 – oop design

50
Mark Dixon 1 11 – OOP Design

Upload: oma

Post on 19-Jan-2016

33 views

Category:

Documents


1 download

DESCRIPTION

11 – OOP Design. Session Aims & Objectives. Aims To cover a range of web-application design techniques Objectives, by end of this week’s sessions, you should be able to: create a servlet Create and use a Java Bean use a class to gather code common to different pages SQL insertion attacks. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 11 – OOP Design

Mark Dixon 1

11 – OOP Design

Page 2: 11 – OOP Design

Mark Dixon 2

Session Aims & Objectives• Aims

– To cover a range of web-application design techniques

• Objectives,by end of this week’s sessions, you should be able to:

– create a servlet– Create and use a Java Bean– use a class to gather code common to different

pages– SQL insertion attacks

Page 3: 11 – OOP Design

Mark Dixon 3

• most application programs – 3 major layers– Top (Presentation) layer:

• human/machine interaction (the user interface)– input from the keyboard / mouse– output in the form of screen displays / sound

– Middle (Application or business logic) layer:• core functionality – gives application program its character• contains business rules -> drive an organisation• e.g. order entry system vs. inventory control system

– Bottom layer• general services needed by other layers• e.g. file, print, communications, and database services

3

Application Layers

Page 4: 11 – OOP Design

Mark Dixon 4

2-Tier Architecture• Presentation and Application layer

located on client machine– could be implemented using Applet interacting server

• Known as a ‘fat client’

Tier 1

Server

Presentation layerApplication layer

Client

Database server

Tier 2

Server

Page 5: 11 – OOP Design

Mark Dixon 5

3-Tier Architecture• 3-tier architecture,

– only presentation layer on client– application layer on server – Database on server or third machine

• Known as a ‘thin-client’– very little (application) code / processing on client

• e.g. use of Java Servlets (JSP pages)

T ier 1

Presentation layer

Client

T ier 3

Database server

Application layer

T ier 2

Server

Page 6: 11 – OOP Design

Mark Dixon 6

Example: AddNum (JSP)<%@page contentType="text/html" pageEncoding="UTF-8"%><%double N1;double N2;String Res = ""; if (request.getParameter("btnAdd") != null){ N1 = Double.parseDouble(request.getParameter("txtN1")); N2 = Double.parseDouble(request.getParameter("txtN2")); Res = Double.toString(N1 + N2); }%><!DOCTYPE html><html> <head><title>Add Numbers</title></head> <body> <form method="post"> <input name="txtN1" type="text" /><br /> <input name="txtN2" type="text" /><br /> <input name="btnAdd" type="submit" value="Add" /> <p><%=Res%></p> </form> </body></html>

AddNum.jsp

Java - functionality

HTML – user interface

Page 7: 11 – OOP Design

Mark Dixon 7

JSP pages & Servlets• all JSP pages converted to servlet

• Servlet– Java program running in web server– Special type of Java class (.java file)

• Can get servlet error – caused by error in JSP page (usually missing } ), but difficult to see the connection

Page 8: 11 – OOP Design

Mark Dixon 8

AddNum: Servlet (.html file)• Split

– User interface (html)– Functionality (Java)

<!DOCTYPE html><html> <head><title>Add Numbers</title></head> <body> <form method="post" action="AddNum"> <input name="txtN1" type="text" /><br /> <input name="txtN2" type="text" /><br /> <input name="btnAdd" type="submit" value="Add" /> </form> </body></html>

Points to Servlet (.java)

Page 9: 11 – OOP Design

Mark Dixon 9

AddNum: Servlet (.java file)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 class AddNum extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { double N1; double N2; String Res = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { N1 = Double.parseDouble(request.getParameter("txtN1")); N2 = Double.parseDouble(request.getParameter("txtN2")); Res = Double.toString(N1 + N2); out.println("<html>"); out.println("<head>"); out.println("<title>Add Numbers</title>"); out.println("</head>"); out.println("<body>"); out.println(Res); out.println("</body>"); out.println("</html>"); } finally { out.close(); } }

@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

@Override public String getServletInfo() { return "Short description"; }}

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { double N1; double N2; String Res = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { N1 = Double.parseDouble(request.getParameter("txtN1")); N2 = Double.parseDouble(request.getParameter("txtN2")); Res = Double.toString(N1 + N2); out.println("<html>"); out.println("<head>"); out.println("<title>Add Numbers</title>"); out.println("</head>"); out.println("<body>"); out.println(Res); out.println("</body>"); out.println("</html>"); } finally { out.close(); } }

Calculationcode

Also, write html

Page 10: 11 – OOP Design

Mark Dixon 10

Example: PeopleList.jsp v2<%@page import="java.sql.*"%><%@page contentType="text/html"%><%Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection cn = DriverManager.getConnection("jdbc:odbc:PeopleDB", "", "");Statement st = cn.createStatement();ResultSet r = st.executeQuery("SELECT * FROM Person;");String html = "";String id; while(r.next()){ id = Integer.toString(r.getInt("PersonID")); html += "<a href='Person2.jsp?id=" + id + "'>"; html += r.getString("Surname") + "</a><br />"; } cn.close();%><!DOCTYPE html><html> <head><title></title></head> <body> <%=html%> </body></html>

Connect to db

Page 11: 11 – OOP Design

Mark Dixon 11

Example: Person.jsp v2<%@page import="java.sql.*"%><%@page contentType="text/html" pageEncoding="UTF-8"%><%String id = request.getParameter("id");Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection cn = DriverManager.getConnection("jdbc:odbc:PeopleDB", "", "");Statement st = cn.createStatement();ResultSet r = st.executeQuery("SELECT * FROM Person WHERE PersonID = " + id + ";");String surname = ""; if(r.next()){ surname = r.getString("Surname"); } cn.close();%><!DOCTYPE html><html> <head><title>Person</title></head> <body> Surname: <input name="txtSurname" type="text" value="<%=surname%>" /> </body></html>

Connect to DB

Page 12: 11 – OOP Design

Mark Dixon 12

Person & PeoplList v2

• both JSP page duplicate common code

<%@page import="java.sql.*"%><%@page contentType="text/html" pageEncoding="UTF-8"%><%String id = request.getParameter("id");Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection cn = DriverManager.getConnection("jdbc:odbc:PeopleDB", "", "");Statement st = cn.createStatement();ResultSet r = st.executeQuery("SELECT * FROM Person WHERE PersonID = " + id + ";");String surname = ""; if(r.next()){ surname = r.getString("Surname"); } cn.close();%><!DOCTYPE html><html> <head><title>Person</title></head> <body> Surname: <input name="txtSurname" type="text" value="<%=surname%>" /> </body></html>

<%@page import="java.sql.*"%><%@page contentType="text/html"%><%Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection cn = DriverManager.getConnection("jdbc:odbc:PeopleDB", "", "");Statement st = cn.createStatement();ResultSet r = st.executeQuery("SELECT * FROM Person;");String html = "";String id; while(r.next()){ id = Integer.toString(r.getInt("PersonID")); html += "<a href='Person2.jsp?id=" + id + "'>"; html += r.getString("Surname") + "</a><br />"; } cn.close();%><!DOCTYPE html><html> <head><title></title></head> <body> <%=html%> </body></html>

Page 13: 11 – OOP Design

Mark Dixon 13

Class People• Contains common code for both pages

Peoplecnstr

OpenSelectClose

Page 14: 11 – OOP Design

Mark Dixon 14

JavaBean: People.java 1• Common code

package Main;import java.sql.*;

public class People{private Connection cn;private Statement st;private ResultSet r;

public void Open(){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); cn = DriverManager.getConnection("jdbc:odbc:PeopleDB", "", ""); } catch (Exception e){ //e.printStackTrace(); } }

public void Select(String sql){ try{ st = cn.createStatement(); r = st.executeQuery(sql); } catch (Exception e){ //e.printStackTrace(); } }

public boolean Next(){ boolean found = false; try{ found = r.next(); } catch (Exception e){ //e.printStackTrace(); } return found; }

public String get(String id){ String s = ""; try{ s = r.getString(id); } catch (Exception e){ //e.printStackTrace(); } return s; }

public void Close(){ try{ cn.close(); } catch (Exception e){ //e.printStackTrace(); } }}

package Main;import java.sql.*;

public class People{private Connection cn;private Statement st;private ResultSet r;

public void Open(){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); cn = DriverManager.getConnection("jdbc:odbc:PeopleDB", "", ""); } catch (Exception e){ //e.printStackTrace(); } }

public void Select(String sql){ try{ st = cn.createStatement(); r = st.executeQuery(sql); } catch (Exception e){ //e.printStackTrace(); } }

Page 15: 11 – OOP Design

Mark Dixon 15

JavaBean: People.java 2• Common code

package Main;import java.sql.*;

public class People{private Connection cn;private Statement st;private ResultSet r;

public void Open(){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); cn = DriverManager.getConnection("jdbc:odbc:PeopleDB", "", ""); } catch (Exception e){ //e.printStackTrace(); } }

public void Select(String sql){ try{ st = cn.createStatement(); r = st.executeQuery(sql); } catch (Exception e){ //e.printStackTrace(); } }

public boolean Next(){ boolean found = false; try{ found = r.next(); } catch (Exception e){ //e.printStackTrace(); } return found; }

public String get(String id){ String s = ""; try{ s = r.getString(id); } catch (Exception e){ //e.printStackTrace(); } return s; }

public void Close(){ try{ cn.close(); } catch (Exception e){ //e.printStackTrace(); } }}

public boolean Next(){ boolean found = false; try{ found = r.next(); } catch (Exception e){ //e.printStackTrace(); } return found; }

public String get(String id){ String s = ""; try{ s = r.getString(id); } catch (Exception e){ //e.printStackTrace(); } return s; }

public void Close(){ try{ cn.close(); } catch (Exception e){ //e.printStackTrace(); } }}

Page 16: 11 – OOP Design

Mark Dixon 16

PersonList.jsp

• Class complex

• Pages simpler

<jsp:useBean id="p" scope="session" class="Main.People" /><%@page contentType="text/html" pageEncoding="UTF-8"%><%String html = ""; p.Open(); p.Select("SELECT * FROM Person;"); while(p.Next()){ html += p.get("Surname") + "<br />"; } p.Close();%>

<!DOCTYPE html><html> <head><title>People</title></head> <body> <%=html%> </body></html>

Create Bean

Use methods

Page 17: 11 – OOP Design

Mark Dixon 17

• Apache – http server (html pages)

• Tomcat – runs JSP + Servlets– servlet container (interpreter/compiler)– Can run:

• Standalone– Handles simple page requests– Handles servlet requests

• Apache plugin– Apache handles HTML pages, CGI, PHP etc– Tomcat handles servlets

Apache TOMCAT

Page 18: 11 – OOP Design

Mark Dixon 18

Tomcat: LocalHost

Page 19: 11 – OOP Design

Mark Dixon 19

Directory Description context root This is the root directory for the Web application.

All JSPs, HTML documents, and supporting files reside in this directory or subdirectories. Name of directory is specified by the Web creator. To provide structure in a Web application, subdirectories can be placed in the context root. i.e. /images

WEB-INF This directory contains the Web application deployment descriptor (web.xml)

WEB-INF/classes Contains the servlet class files and other supporting class files used in a Web application. If the classes are part of a package, the complete package directory structure would begin here.

WEB-INF/lib This directory contains Java archive (JAR) files. JAR files can contain servlet class files and other supporting class files used in a Web application.

TOMCAT DIRECTORY STRUCTURE

Page 20: 11 – OOP Design

Mark Dixon 20

Tomcat Folder StructureContext root

Starting html page

Web application deployment descriptor (web.xml) Package name of

the HelloServlet class

The HelloServlet class

NetbeansWill create this

Structure …

Page 21: 11 – OOP Design

Mark Dixon 21

• fgfg

Default location is in webapps

Can have any number of

webapplications in webapps

But each need WEB-INF and

web.xml

Tomcat Folder Structure

Page 22: 11 – OOP Design

Mark Dixon 22

Apache Tomcat - NetBeans• JRE_HOME = C:\Program Files\Java\jre6

– Control Panel– System– Advanced– Environment Variables

• C:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.14\bin– startup.bat (run from command line)

• http://localhost:8080/

Page 23: 11 – OOP Design

Mark Dixon 23

• JSP programming style strongly encourages the use of JavaBeans.

• There are special tags built-in to support JavaBean properties.

• JSP + Bean combination separates the html look of the page from the ‘logic’ – i.e. the presentation from the code

• A JavaBean, or sometimes just called a bean, is basically an instance of a Java class. 23

JSP AND JAVABEAN

Page 24: 11 – OOP Design

Mark Dixon 24

• A Java class meeting specific requirements:

• Must have a zero-argument constructor:– e.g.

• public MyBean() {…

• }

• Must have no public attributes– All attributes should be private

• All data should be accessed via access methods

24

WHAT IS A JAVABEAN

Page 25: 11 – OOP Design

Mark Dixon 25

BANKACCOUNT BEAN

25

No Parameter constructor Important

Exception is for boolean attributes isXxxx()

Beans MUST be in packages

Get and set methods

MUST conform to getXxxx() and setXxxx()

Can have other methods but method

names cannot look like property get / set

Page 26: 11 – OOP Design

Mark Dixon 26

• An attribute is a variable which belongs to an class/object – For objects also known as instance

variables– For classes also known as class variables

• Remember final static int COLOUR_ONE

• Math.PI is a class variable

• A property is an attribute which has getter and setter methods – And that’s it !

26

REFINING THE TERMINOLOGY

Page 27: 11 – OOP Design

Mark Dixon 27

• Read-only properties:

String getAccountID()

• returns the accountID property

• Read/write properties:

void setBalance(double bal)double getBalance()

• Boolean properties:

boolean isActive()void setActive(boolean act) 27

JAVABEAN PROPERTIES

Page 28: 11 – OOP Design

Mark Dixon 28

• It is important to distinguish between a JavaBean as used in a:

–GUI development tool• This is a visual component

–i.e. will subclass Panel, Button etc.

• Note there is a visual Bean design tool at:http://java.sun.com/products/javabeans/beanbuilder/index.jsp

–Server-Side application

• We are only dealing with the latter 28

MORE THAN ONE BEAN

Page 29: 11 – OOP Design

Mark Dixon 29

• <jsp: useBean ……… >

• <jsp: setProperty ……… >

• <jsp: getProperty ……… >

29

BEAN RELATED TAGS

Page 30: 11 – OOP Design

Mark Dixon 30

BEANS WITH JSP• A JSP file which makes use of the Class Bank

– Note: file called Bank.jsp

30

Page 31: 11 – OOP Design

Mark Dixon 31

CREATING AN OBJECT

• Creates a bean instance called ‘myAccount’ of type ‘BankAccount’

• The id attribute is the name of the variable

• Similar to the following JSP code:

<% BankAccount myAccount = new BankAccount(); %>

• Or Java:

BankAccount myAccount = new BankAccount();31

Note: use of package name

Important

This / is important

Page 32: 11 – OOP Design

Mark Dixon 32

SETTING BEAN PROPERTIES 1

• Sets the value of the myAccount property balance to 500

• Basically the same operation as:

<%= myAccount.setBalance(500) %>

• Or in Java as:BankAccount myAccount = new BankAccount();

mybalance = myAccount.setBalance(500);32

Page 33: 11 – OOP Design

Mark Dixon 33

SETTING BEAN PROPERTIES 2

• Also can have a dynamic property which uses an expression tag

• This example is just setting the balance to some random value between 0 and 100

33

Page 34: 11 – OOP Design

Mark Dixon 34

SETTING BEAN PROPERTIES 3

• Although this value is text

• It is converted automatically in the right type

– In this case a double

34

Page 35: 11 – OOP Design

Mark Dixon 35

READING BEAN PROPERTIES

• Inserts the value of myAccount property balance into the web page

• Basically the same as:<%= myAccount.getBalance() %>

• Or in Java as:BankAccount myAccount = new BankAccount();

double mybalance;mybalance = myAccount.getBalance();

35

Page 36: 11 – OOP Design

Mark Dixon 36

BEANS WITH JSP - REVIEW

36

This line creates an object called myAccount of class BankAccount

This line sets the balance property to 500

This line gets the balance

Note how the value is displayed on the html page

Page 37: 11 – OOP Design

Mark Dixon 37

SETTING BEAN PROPERTIES FROM TEXT

BOXES

• This the same as:

String bal = request.getParamter(“openingbalance”);double tempBal = Double.parseDouble(bal);myaccount.setBalance(tempBal); 37

Sets the property ‘balance’ to what ever was typed in the textbox.

.jsp Page

.htmlPage

Page 38: 11 – OOP Design

Mark Dixon 38

USING TEXTBOXES

38

If the textbox name is the same name as the property

Then we do not need a ‘param’

Page 39: 11 – OOP Design

Mark Dixon 39

SETTING BEAN PROPERTIES … ‘WILDCARDS’

• Using wildcards to set properties:

39

Sets the value of all ‘somebean’ properties to JSP parameters with the same name If the parameters do not exist, the value of the bean properties do

not change

Page 40: 11 – OOP Design

Mark Dixon 40

OpenAccount.html

‘WILDCARDS’ EXAMPLE

40

NewAccount.jsp

Page 41: 11 – OOP Design

Mark Dixon 41

‘WILDCARDS’ EXAMPLE

41

Page 42: 11 – OOP Design

Mark Dixon 42

scope = “page”

scope = “request”

• These beans will not last after the request is completed– The difference between these 2 scopes is very small– Beans such as this do not allow you to share data between

servlets and JSPs

scope = “application”

scope = “session”

• These beans will last between requests, thus allowing sharing of data between requests– Again, the differences between these two requests are mostly

cosmetic42

JAVABEAN SCOPE 1The default scope

Page 43: 11 – OOP Design

Mark Dixon 43

SESSION BEANS

43

As Bank.jsp and Rent.jsp are scoped at session level, the object myAccount is not created in Rent.jsp

File: Rent.jsp

Page 44: 11 – OOP Design

Mark Dixon 44

SESSION BEANS

44

File: Rent.jsp

File: Bank.jsp

The file Bank.jsp

Creates the object myAccount, which is then used by Rent.jsp

Essentially passing information between JSP pages

Page 45: 11 – OOP Design

Mark Dixon 45

CONDITIONAL BEANS

• So far we have used the <jsp: useBean id =“somebean…. > tag

– jsp:useBean results in new bean being created only if no bean with same id and scope can be found.

– If a bean with same id and scope is found, then that bean is used.

• This means that any property we initially set will be again be set each time we visit the page

• This is ok when we visit the a page for the 1st time as we want to set the properties of the bean which will be used across several pages.

• But what if we wanted to set initial bean properties for a bean which is shared by multiple pages.

• Since we don’t know which page will be accessed first, we don’t know which page should contain the initialization code.

45

Page 46: 11 – OOP Design

Mark Dixon 46

EXAMPLE:• Lets assume we have a ‘back’ link on the PayRent.jsp

46

??? Balance should be 350.00

Page 47: 11 – OOP Design

Mark Dixon 47

• Problem is that when we return to the Bank.jsp page the setProperty sets the balance to 500 again

47

Page 48: 11 – OOP Design

Mark Dixon 48

SOLUTION USE A CONDITIONAL BEAN

• The <jsp:useBean ... />• replaced by

<jsp:useBean ...> statements </jsp:useBean>

• The statements (i.e. jsp:setProperty elements) are executed only if a new bean is created, not if an existing bean is found.

48

This is subtle but the effects are profound

Modified file: Bank.jsp

Page 49: 11 – OOP Design

Mark Dixon 49

EXAMPLE:• Now we have

49

Balance is correct at 350.00

Page 50: 11 – OOP Design

Mark Dixon 50

• Hall, M. Servlets and Java Server Pages 2nd Edition– Chapter 14: Using Beans with JSP

• Best coverage

• Armstrong, E. (2003) The J2EE 1.4 Tutorial – chapter 12: Pages 515 - 525

• http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html

50

REFERENCES - READ AT LEAST ONE OF …