+ All Categories
Home > Documents > Java - UniTrento

Java - UniTrento

Date post: 17-Oct-2021
Category:
Upload: others
View: 7 times
Download: 0 times
Share this document with a friend
56
Java Serialization
Transcript
Page 1: Java - UniTrento

Java

Serialization

Page 2: Java - UniTrento

Il problema della persistenza

Serialization: trasform objects into data stream (and viceversa)

It’s a recursive problem!

Page 3: Java - UniTrento

JDK Support to persistence

ObjectOutputStream: converts oggetti into binary streams. ObjectInputStream: converts binary streams into objects. Serializable: no-method interface to mark classes as serializable Modifier transient: Transient variables are not serialized

Page 4: Java - UniTrento

Esempio –Reader 1/2

import java.io.Serializable; public class Person implements Serializable{ int age; String name; transient double id; Person(String name, int age) {

this.name=name; this.age=age; id=Math.random();

} public String toString(){return name+" "+age" "+id;} }

Page 5: Java - UniTrento

Serialization public class SerializationDemo { public static void main(String[] args) { Person p=new Person("Pippo",33); System.out.println(p); try { FileOutputStream ofs=

new FileOutputStream("serializedStream.txt"); ObjectOutputStream oos=new ObjectOutputStream(ofs); oos.writeObject(p); ofs.close(); } catch (Exception ex) {ex.printStackTrace(); } p=null; System.out.println(p);

Page 6: Java - UniTrento

Serialization - continued try { FileInputStream ifs=

new FileInputStream("serializedStream.txt"); ObjectInputStream ois=new ObjectInputStream(ifs); p=(Person)ois.readObject(); } catch (Exception ex) {ex.printStackTrace(); } System.out.println(p); } } Output: Pippo 33 0.06172593378557312 null Pippo 33 0.0

Page 7: Java - UniTrento

ObjectOutputstream – main methods

ObjectOutputStream(OutputStream) writeObject(Object) close() flush() reset() writeInt(int) writeFloat(float) writeDouble(double)

Page 8: Java - UniTrento

ObjectInputstream – main methods

ObjectInputStream(InputStream) Object readObject() available() How many bytes are left in the stream? int readInt() float writeFloat() double writeDouble()

Page 9: Java - UniTrento

Some basic Java vocabulary

Page 10: Java - UniTrento

POJO The term "POJO" is mainly used to denote a

Java object which does not follow any of the major Java object models, conventions, or frameworks.

"We wondered why people were so against

using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely.” Martin Fowler

Page 11: Java - UniTrento

A bean is a Java class that: p  Provides a public zero-arguments constructor p  Implements java.io.Serializable p  Follows JavaBeans design patterns

n  Has Set/get methods for properties p  Is thread safe/security conscious

public class SimpleBean implements Serializable {

private int counter; SimpleBean() {counter=0;} int getCounter() {return counter;} void setCounter(int c) {counter=c;}

} See http://docs.oracle.com/javase/tutorial/javabeans/

Java Bean

Page 12: Java - UniTrento

Basi

JSP

Last available official tutorial: http://docs.oracle.com/javaee/5/tutorial/doc/bnagx.html (2010)

Page 13: Java - UniTrento

Why JSP? It is today a deprecated technology, but it is the

basis for the current technology (JSF) So we better understand how it works…

Page 14: Java - UniTrento

A taste of servlet programming-2

import java.util.Calendar; public class SimpleServlet extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { PrintWriter out=response.getWriter(); response.setContentType("text/html"); out.println("<HTML><BODY>");

out.println(Calendar.get(Calendar.HOUR_OF_DAY)); out.println("</BODY></HTML>"); out.close(); }

}

Page 15: Java - UniTrento

<%@ page import=java.util.* %> <html> <body> <% out.println(Calendar.get(Calendar.HOUR_OF_DAY)); %> </body> </html>

Simple.jsp

Page 16: Java - UniTrento

JSP Lifecycle

Browser Generated Servlet

Compiled Servlet

JSP Page Server Web

Page 17: Java - UniTrento

Syntactic elements: <%@ directives %> <%! declarations %> <% scriptlets %> <%= expressions %> <jsp:actions/> <%-- Comment --%>

JSP nuts and bolts

Implicit Objects: • request • response • pageContext • session • application • out • config • page

Page 18: Java - UniTrento

Syntactic elements: <%@ directives %> à Interaction with the CONTAINER <%! declarations %> à In the initialization of the JSP <% scriptlets %> à In the service method <%= expressions %> à (Syntactic sugar) same as scriptlets <jsp:actions/>

JSP nuts and bolts

Page 19: Java - UniTrento

A scriptlet is a block of Java code executed during the request-processing time.

In Tomcat all the scriptlets gets put into the service() method of

the servlet. They are therefore processed for every request that the servlet receives.

Scriptlets

Page 20: Java - UniTrento

Examples : <% z=z+1; %> <% // Get the Employee's Name from the request out.println("<b>Employee: </b>" + request.getParameter("employee")); // Get the Employee's Title from the request out.println("<br><b>Title: </b>" + request.getParameter("title")); %>

Scriptlet

Page 21: Java - UniTrento

A declaration is a block of Java code used to: define class-wide variables and methods in the generated

servlet. They are initialized when the JSP page is initialized. <%! DECLARATION %> Examples: <%! String nome=“pippo”; %> <%! public String getName() {return nome;} %>

Declarations

Page 22: Java - UniTrento

A directive is used as a message mechanism to: pass information from the JSP code to the container Main directives: page include (for including other STATIC resources at compilation

time) taglib (for including custom tag libraries)

Directives

Page 23: Java - UniTrento

<%@ DIRECTIVE{attributo=valore} %> main attributes: <%@ page language=java session=true %> <%@ page import=java.awt.*,java.util.* %> <%@ page isThreadSafe=false %> <%@ page errorPage=URL %> <%@ page isErrorPage=true %>

Directives

Page 24: Java - UniTrento

Standard action are tags that affect the runtime behavior of the JSP and the response sent back to the client.

<jsp:include page=“URL” /> For including STATIC or DYNAMIC resources at request time <jsp:forward page=“URL” />

Standard actions

Page 25: Java - UniTrento

<jsp:useBean id=“name” class=“fully_qualified_pathname” scope=“{page|request|session|application}” /> <jsp:setProperty name=“nome” property=“value” /> <jsp:getProperty name=“nome” property=“value” />

Standard actions involving beans

Page 26: Java - UniTrento

When should I use a JSP <%@include@%> directive, and when should I use a <jsp:include> action?

A JSP <%@include@%> directive (for example, <%@ include file="myfile.jsp" @%>) includes literal text "as is" in the JSP page and is not intended for use with content that changes at runtime. The include occurs only when the servlet implementing the JSP page is being built and compiled.

The <jsp:include> action allows you to include either static or dynamic content in the JSP page. Static pages are included just as if the <%@include@%> directive had been used. Dynamic included files, though, act on the given request and return results that are included in the JSP page. The include occurs each time the JSP page is served.

See also http://java.sun.com/blueprints/qanda/web_tier/index.html#directive

<%@include@%> or <jsp:include> ?

Page 27: Java - UniTrento

out Writer request HttpServletRequest response HttpServletResponse session HttpSession page this nel Servlet application servlet.getServletContext

area condivisa tra i servlet config ServletConfig exception solo nella errorPage pageContext sorgente degli oggetti, raramente usato

Predefined Objects

Page 28: Java - UniTrento

<%@ page errorPage="errorpage.jsp" %> <html> <head> <title>UseRequest</title> </head> <body> <% // Get the User's Name from the request out.println("<b>Hello: " + request.getParameter("user") + "</b>"); %> </body> </html>

request

Page 29: Java - UniTrento

<%@ page errorPage="errorpage.jsp" %> <html> <head> <title>UseSession</title> </head> <body> <% // Try and get the current count from the session Integer count = (Integer)session.getAttribute("COUNT"); // If COUNT is not found, create it and add it to the session if ( count == null ) { count = new Integer(1); session.setAttribute("COUNT", count); } else { count = new Integer(count.intValue() + 1); session.setAttribute("COUNT", count); } // Get the User's Name from the request out.println("<b>Hello you have visited this site: " + count + " times. </b>"); %> </body> </html>

session

Page 30: Java - UniTrento

WebApps

(Tomcat configuration)

Page 31: Java - UniTrento

Static pages

A web.xml file MUST be provided: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN“ "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> </web-app>

myApp

hello.html WEB-INF

webapps

web.xml

Page 32: Java - UniTrento

JSP pages

To let Tomcat serve JSP pages, we follow the same procedure that we described for static pages. In the myApp folder we can depost the JSP files. On our Tomcat server, the URL for the hello.jsp file becomes: http://machine/port/myApp/hello.jsp The WEB-INF directory is still empty. To actually see the webapp, you might have to restart Tomcat (depending on the version you have) The same web.xml file as in the static case must be provided.

myApp

hello.jsp WEB-INF

webapps

web.xml

Page 33: Java - UniTrento

Tag Extension

JSP

http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html

Page 34: Java - UniTrento

Ideally, JSP pages should contain no code written in the Java programming language (that is, no expressions or scriptlets). Anything a JSP page needs to do with Java code can be done from a

custom tag p  Separation of form and function. p  Separation of developer skill sets and activities.

p  Code reusability. p  Clarified system design.

JSP custom tag

Page 35: Java - UniTrento

<%@ taglib uri="/hello" prefix="example" %> <HTML><HEAD><TITLE>First custom tag</TITLE></HEAD> <BODY> This is static output <p /> <i><example:hello>HELLO THERE</example:hello></i> This is static output </BODY> </HTML>

a JSP custom tag

hello.doStartTag()

hello.doEndTag()

Page 36: Java - UniTrento

package jsptags; import java.io.IOException; import java.util.Date; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTag extends TagSupport { public int doStartTag() throws JspTagException { try { pageContext.getOut().write("Start tag found here<BR>"); } catch (IOException e) { throw new JspTagException("Fatal error: could not write to JSP out"); } return EVAL_BODY_INCLUDE; // return SKIP_BODY; }

a JSP custom tag

Page 37: Java - UniTrento

… public class HelloTag extends TagSupport { … public int doEndTag() throws JspTagException { try { pageContext.getOut().write("End tag found<BR>"); } catch (IOException e) { throw new JspTagException("Fatal error: could not write to JSP out"); } return EVAL_PAGE; // return SKIP_PAGE; } }

a JSP custom tag

Page 38: Java - UniTrento

Javax.servlet.jsp.tagext.Tag interface

Tag Pagina JSP setPageContext(pageContext)

setParent(enclosingTag)

setAttribute1(pageContext)

doStartTag()

doEndTag()

release()

Page 39: Java - UniTrento

Class Diagram

Tag

doStart(Tag)doEnd(Tag)getParent()release()setPageContent()setParent()

<<Interface>>

BodyTag

doAfterBody()doInitBody()setBodyContent()

<<Interface>>

TagSupport

<stat ic> findAncestorWithClass()

BodyTagSupport

getBodyContent()getPreviousOut()

YourOwnBodyTag

YourOwnBodyTag

API

A BodyTag can manipulate its body, using its BodyContent object, while a normal Tag cannot. BodyTags are useful when you want to use or transform the contents of the tag.

Page 40: Java - UniTrento

<%@ taglib uri="/hello" prefix="example" %> <HTML><HEAD><TITLE>First custom tag</TITLE></HEAD> <BODY> This is static output <p /> <i><example:hello>HELLO THERE</example:hello></i> This is static output </BODY> </HTML>

a JSP custom tag

hello.doInitBody()

hello.doEndTag()

hello.doStartTag()

hello.doAfterBody()

Page 41: Java - UniTrento

package jsptags; … public class HelloTag extends BodyTagSupport { public int doStartTag() throws JspTagException { … } public void doInitBody() throws JspTagException { try { pageContext.getOut().write("Init Body<BR>"); } catch (IOException e) { throw new JspTagException("Fatal error: could not write to JSP out"); } }

a JSP custom tag

Page 42: Java - UniTrento

public int doAfterBody() throws JspTagException { try { pageContext.getOut().write("After Body<BR>"); } catch (IOException e) { throw new JspTagException("Fatal error: could not write to JSP out"); } return EVAL_BODY_TAG; // return SKIP_BODY; } */ public int doEndTag() throws JspTagException { … } }

a JSP custom tag

Page 43: Java - UniTrento

Javax.servlet.jsp.tagext.BodyTag interface

Tag Pagina JSP setPageContext(pageContext) setParent(enclosingTag) setAttribute1() doStartTag()

setBodyContent(out)

release()

PageContext

pushBody()

doInitBody()

doEndTag()

doAfterBody() popBody()

Page 44: Java - UniTrento

import java.io.IOException; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ReverseTag extends BodyTagSupport {

public int doEndTag() throws JspTagException { BodyContent bodyContent = getBodyContent(); if (bodyContent != null) {// Do nothing if there was no body content StringBuffer output = new StringBuffer(bodyContent.getString()); output.reverse(); try {

bodyContent.getEnclosingWriter().write(output.toString()); } catch (IOException ex) { throw new JspTagException("Fatal IO error"); } } return EVAL_PAGE; }

}

reversing body content

Page 45: Java - UniTrento

structure of the war file

hello

hello.jsp META-INF WEB-INF

MANIFEST.MF web.xml tlds classes

hello.tld HelloTag.class

A war file is a jar file with special directories and a file named web.xml in the WEB-INF directory

Page 46: Java - UniTrento

<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>examples</shortname> <info>Simple example library.</info> <tag> <name>reverse</name> <tagclass>tagext.ReverseTag</tagclass> <bodycontent>JSP</bodycontent> <info>Simple example</info> </tag> </taglib>

TLD

Page 47: Java - UniTrento

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN' 'http://

java.sun.com/j2ee/dtds/web-app_2.2.dtd'> <web-app> <display-name>tagext</display-name> <description>Tag extensions examples</description> <session-config> <session-timeout>0</session-timeout> </session-config> <taglib> <taglib-uri>/hello</taglib-uri> <taglib-location>/WEB-INF/tlds/hello.tld</taglib-location> </taglib> </web-app>

web.xml

Page 48: Java - UniTrento

Java Standard Template Library

JSTL

http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html

Page 49: Java - UniTrento

JSTL

Core tags <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

See http://download.oracle.com/javaee/5/tutorial/doc/bnakh.html

<c:set var="foo" scope="session" value="..."/> ${foo}

Page 50: Java - UniTrento

JSTL - xml

XML tags <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

See http://download.oracle.com/javaee/5/tutorial/doc/bnakq.html

<c:if test="${applicationScope:booklist == null}" > <c:import url="${initParam.booksURL}" var="xml" /> <x:parse doc="${xml}" var="booklist" scope="application" /> </c:if> <x:set var="abook" select="$applicationScope.booklist/ books/book[@id=$param:bookId]" /> <h2><x:out select="$abook/title"/></h2>

Page 51: Java - UniTrento

JSTL - sql

XML tags <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

See http://download.oracle.com/javaee/5/tutorial/doc/bnald.html

<sql:setDataSource dataSource="jdbc/BookDB" /> <c:set var="bid" value="${param.Add}"/> <sql:query var="books" > select * from PUBLIC.books where id = ? <sql:param value="${bid}" /> </sql:query>

Page 52: Java - UniTrento

JSTL-fn

function tags <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

See http://download.oracle.com/javaee/5/tutorial/doc/bnalg.html

<c:if test="${fn:length(param.username) > 0}" > <%@include file="response.jsp" %> </c:if>

Page 53: Java - UniTrento

JSTL-fmt

i18n tags <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

See http://download.oracle.com/javaee/5/tutorial/doc/bnakw.html

<h3><fmt:message key="Choose"/></h3>

Page 54: Java - UniTrento

Pattern Singleton

How to make sure that you’ll have only one instance of a class?

Page 55: Java - UniTrento

Singleton - Esempio –1/2

class Referee { static Referee instance= null; private Referee () { String s = ""; } public static Referee getReferee () { if (instance ==null) instance=new Referee (); return instance; } public void whistle() { //... } }

Page 56: Java - UniTrento

Singleton - Esempio – 2/2

package myPackage; public class Simple { public static void main(String a[]) { new Simple(); } Simple() { //Referee a=new Referee (); // would give an error! Referee b=Referee .getReferee (); Referee c=Referee .getAReferee (); System.out.println(b==c); } }


Recommended