Вы находитесь на странице: 1из 17

Su Doku

logic-based placement puzzle

Java Server Programming

5 3 4 | 6 7 8 | 9 1 2 6 7 2 | 1 9 5 | 3 4 8 1 9 8 | 3 4 2 | 5 6 7 -------+-------+-----8 5 9 | 7 6 1 | 4 2 3 4 2 6 | 8 5 3 | 7 9 1 7 1 3 | 9 2 4 | 8 5 6 -------+-------+-----9 6 1 | 5 3 7 | 2 8 4 2 8 7 | 4 1 9 | 6 3 5 3 4 5 | 2 8 6 | 1 7 9

02.11.2005

Lecture 8 / Andres Teder

02.11.2005

Lecture 8 / Andres Teder

Podcasts
Became popular in late 2004 i-Pod, broadcast
3

The previous lecture


Java Collections Framework Java Community Process Web Applications and Containers Servlets Scope Thread issues Filters
Lecture 8 / Andres Teder 4

http://javaposse.com Podcast of Java news and interviews

02.11.2005

Lecture 8 / Andres Teder

02.11.2005

Today
Servlets in context Java Server Pages Custom socket programming

Servlets And Design


Dont forget to separate the view and model

HTTP request HTTP response MVC

02.11.2005

Lecture 8 / Andres Teder

02.11.2005

Lecture 8 / Andres Teder

Magic Servlet Antipattern


View and Model need to be implemented without assuming anything about implementation details of the other In good design servlet is an interface point between user interface and server-side logic Magic Servlet antipattern encapsulating model, view and controller in a single method
02.11.2005 Lecture 8 / Andres Teder 7

When to use Servlets?


Controllers When implementing information services in an application Non-visual components Binary data generators

02.11.2005

Lecture 8 / Andres Teder

Java Server Pages


What is a JSP? JSP technology provides the means for textual specification of the creation of a dynamic response to a request. Most J2EE implementations translate JSP pages into servlets

JSP
Java Server Pages 2.0 (JSR-152), 24 Nov 2003 Java Server Pages 2.1 (JSR-245), Proposed Final Draft 25 Aug, 2005
Servlet/JSP Spec Apache Tomcat version 2.4/2.0 5.5.12 2.3/1.2 4.1.31 2.2/1.1 3.3.2

02.11.2005

Lecture 8 / Andres Teder

02.11.2005

Lecture 8 / Andres Teder

10

JSP Lifecycle
Similar to Servlets after being compiled

JSP Lifecycle
1. Compilation
1. JSP engine checks if compilation is needed 2. First the page is parsed turned into a servlet 3. The servlet is then compiled 4. If you want to bypass compilation, you can also compile manually (precompile)

02.11.2005

Lecture 8 / Andres Teder

11

02.11.2005

Lecture 8 / Andres Teder

12

JSP Lifecycle
2. Loading
1. As JSP essentially becomes a servlet it is loaded as a servlet would be 2. If a newer version of the JSP source file is found, the class file may be reloaded 3. ! Although the class file gets loaded the other utility classes might not be it depends on the JSP engine

JSP Lifecycle
3. Initialization
1. Servlets init() should not be overriden, jspInit() might be instead 2. You can use
<servlet> <servlet-name>HelloWorldJSP</servlet-name> <jsp-file>/HelloWorld.jsp</jsp-file> ... </servlet>

02.11.2005

Lecture 8 / Andres Teder

13

02.11.2005

Lecture 8 / Andres Teder

14

JSP Lifecycle
4. Execution
1. JSP engine invokes the jspService() method each time a request is made by the browser

JSP contents
Directives control how the engine generates the servlet
<%@ include file="somefile.ext" %>

5. Cleanup
1. The cleanup happens through jspDestroy()

include page
import contentType errorPage isErrorPage isThreadSafe

taglib
02.11.2005 Lecture 8 / Andres Teder 15 02.11.2005 Lecture 8 / Andres Teder 16

JSP contents
Scripting elements allow java code to directly be entered into the servlet
<%= Hello world" %>

Simple JSP page


<HTML> <BODY> Hello! The time is now <%= new java.util.Date() %> </BODY> </HTML>

Actions, custom actions (tags)


JSP Actions
<jsp:useBean id="myBean" class=pckg.Bean" scope="request" /> <jsp:getProperty name="myBean" property=userName" />

02.11.2005

Lecture 8 / Andres Teder

17

02.11.2005

Lecture 8 / Andres Teder

18

JSP recent specificaitons


Servlet/JSP Spec Apache Tomcat version 2.4/2.0 5.5.12 2.3/1.2 4.1.31 2.2/1.1 3.3.2

JSP 2.0
Requires JDK 1.3 for standalone containers and JDK 1.4 for J2EE containers Uses Servlet 2.4 specification for web semantics Simple expression language added Simple invocation protocol added
19 02.11.2005 Lecture 8 / Andres Teder 20

02.11.2005

Lecture 8 / Andres Teder

JSP 2.1
Includes a unified expression language the result of integrating JSP 2.0 and Faces 1.1 specification expression languages Uses Servlet 2.5 specification Requires JDK 1.5

JSP 2.0 Expression Language


Before:
<%= customer.getAddress().getCountry() %>

After
${aCustomer.address.country}

02.11.2005

Lecture 8 / Andres Teder

21

02.11.2005

Lecture 8 / Andres Teder

22

Custom tags
JSP Tag Extension API
1. Write a Java class that implements one of the Tag interfaces (Tag, IterationTag, BodyTag)
1. Tag basic methods for all tag handlers 2. IterationTag extension to Tag, provides doAfterBody 3. BodyTag extension to IterationTag, provides tag body manipulation

Simple tags in JSP 2.0


Expression Language (EL) and JSP Standard Tag Library (JSTL) make feasible to develop JSP pages which do not need scriptlets or scriptlet expressions Called Simple Tag Extensions Once initialized by the container, it is executed and then discarded Usage
Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. Page authors who do not know Java: by using tag files
23 02.11.2005 Lecture 8 / Andres Teder 24

2. Need to provide a tag library XML description


02.11.2005 Lecture 8 / Andres Teder

Simple Tags in JSP 2.0


package jsp2.examples.simpletag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; /** * SimpleTag handler that prints "This is my first tag!" */ public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().write("This is my first tag!"); } }
02.11.2005 Lecture 8 / Andres Teder 25

Simple Tags in JSP 2.0


Descriptor: <tag> <description>Prints this is my first tag</description> <name>hello</name> <tag-class>jsp2.examples.simpletag.HelloTag</tag-class> <body-content>empty</body-content> </tag> JSP file: <%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-exampletaglib.tld" %> <HTML> <BODY> <H2>Simple Tag Handler</H2> <P> <B>My first tag prints</B>: <mytag:hello/> </BODY> </HTML>
02.11.2005 Lecture 8 / Andres Teder 26

JSP Simple Tags Tag Files


A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action Needs to have .tag extension

JSP Simple Tags Tag Files


Tag file: (hello.tag) Hello there. How are you doing? JSP File: <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> <HTML> <HEAD> <TITLE>JSP 2.0 Examples - Hello World Using a Tag File</TITLE> </HEAD> <BODY> <H2>Tag File Example</H2> <P> <B>The output of my first tag file is</B>: <tags:hello/> </BODY> </HTML>
27 02.11.2005 Lecture 8 / Andres Teder 28

02.11.2005

Lecture 8 / Andres Teder

When to use JSP pages


Use JSP for data presentation Use JSP for content that is partially fixed Templates

POST vs. GET


GET - retrieve whatever information (in the form of an entity) is identified by the Request-URI
Conditional GET Partial GET

POST - request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line
Includes a message body (key;value pairs)
02.11.2005 Lecture 8 / Andres Teder 29 02.11.2005 Lecture 8 / Andres Teder 30

POST vs. GET


GET form data is encoded into the URL POST form data is in the message body

Considerations when working with servlets


Frameworks
Struts Cocoon Spring JSF Velocity WebMacro
02.11.2005 Lecture 8 / Andres Teder 32

02.11.2005

Lecture 8 / Andres Teder

31

Servlet frameworks
Consider
The licence (GPL, LGPL, ) The feature list (Security, Persitence integration, Display technologies, ) The target group (Ecommerce sites, Portals, )

Custom Socket Programming

Port not a physical device, but an abstraction to facilitate communication between the client and the server Socket - an abstraction for the network software that enables communication out of and into this program

02.11.2005

Lecture 8 / Andres Teder

33

02.11.2005

Lecture 8 / Andres Teder

34

Client view on sockets


Data transferred in packets called datagrams
Header address, port, information for reliable transmission etc. Payload the data itself

Socket
Connection between two hosts
Connecting to a remote machine Sending data Receiving data Closing a connection Binding to a port Listening for incoming data Accepting connections from remote machines on the bound port
35 02.11.2005 Lecture 8 / Andres Teder 36

Datagrams are split across mutliple packets Sockets give an abstract view on network connections
02.11.2005 Lecture 8 / Andres Teder

Sockets in Java
1. Create a new socket with java.net.Socket() 2. The socket attempts to connect to the remote server 3. When the connection is established socketObj.getOutputStream() socketObj.getInputStream() Connection is full-duplex 4. Connection is closed (HTTP 1.0) after every request or can be left open (FTP)

java.net.Socket
Fundamental class for client-side TCP operations Different other classes URL, URLConnection, Applet end up using this class Socket(host,port)
Host = InetAddress or a String Port = int up to 65535

If opening sockets many times to the same host it is more efficient to reuse InetAddress
37 02.11.2005 Lecture 8 / Andres Teder 38

02.11.2005

Lecture 8 / Andres Teder

java.net.Socket
Socket(host,port,interface,localport) Obtaining information about sockets:
getInetAddress() getLocalPort()

java.net.Socket
If you want to only close one type of stream:
shutdownInput() shutdownOutput()

Sockets are closed when


socketObj.close() (recommended practice) one of the streams is closed the program ends socket is garbage collected
Lecture 8 / Andres Teder 39 02.11.2005 Lecture 8 / Andres Teder 40

02.11.2005

Socket properties
TCP_NODELAY packets sent as quickly as possible regardless of their size
Nagles Algorithm - as long as there is an sent packet for which the sender has received no acknowledgement, the sender should keep buffering its output until it has a full packet' s worth of output

Socket properties
SO_LINGER specifies what to do with datagrams that have not been sent when the socket is closed. Can specify a linger time (maximum is platform specific) SO_TIMEOUT the timeout for the read(), needs to be set before the blocking operation SO_RCVBUF, SO_SNDBUF the buffer size of the TCP stack
02.11.2005 Lecture 8 / Andres Teder 42

02.11.2005

Lecture 8 / Andres Teder

41

Socket properties
SO_KEEPALIVE when set, the client periodically sends an alive packet to make sure the server has not crashed SO_REUSEADDR -allows the server to bind to a port which is in TIME_WAIT state
02.11.2005 Lecture 8 / Andres Teder 43

Socket properties
OOBINLINE (Out of Band Data) reception of TCP urgent data, operating system interrupts the receiving process if this process has chosen to be notified about out-of-band data. Can decrease the performance of the server.

02.11.2005

Lecture 8 / Andres Teder

44

Server-side Sockets
java.net.ServerSocket 1. ServerSocket() is created on a particular port 2. Waits for connections using accept() 3. Communicates via Input/Output streams 4. Server, client or both close the connection 5. The server returns to step 2
02.11.2005 Lecture 8 / Andres Teder 45

Server Sockets
Incoming connections stored in a queue by the operating systems ServerSocket(port) ServerSocket(port,queuelength) ServerSocker(port,queuelength,bindaddre ss)

02.11.2005

Lecture 8 / Andres Teder

46

Server Socket Options


SO_TIMEOUT, SO_REUSEADDR, SO_RCVBUF

Secure Sockets
Java Secure Sockets Extension (JSSE) - a set of packages that enable secure Internet communications Included since JDK 1.4.x Optional package in older JDKs

02.11.2005

Lecture 8 / Andres Teder

47

02.11.2005

Lecture 8 / Andres Teder

48

Secure Sockets
SSL standard protocol proposed by Netscape for implementing cryptography SSL has two aims:
Authenticate the server and client using public key signatures and digital certificates Provide an encrypted connection for the client and server to exchange messages securely

Secure sockets
SSL uses symmetric (same key used to encrypt and decrypt) cryptography for data encryption SSL uses asymmetric or public key cryptography to authenticate the identities of the communicating parties and encrypt the session key when establishing session

02.11.2005

Lecture 8 / Andres Teder

49

02.11.2005

Lecture 8 / Andres Teder

50

SSL
Record protocol way in which messages passed between the client and server are encapsulated. Has a cipher suite associated. Cipher suite determines -The kind of key exchange algorithm used -The encryption algorithm used -The digest algorithm used Handshake protocol used to negotiate the type of connection the client and server can support, perform authentication and generate a bulk encr

SSL Cipher Suites


SSL_RSA_EXPORT_WITH_RC4_40_MD 5
RSA public key encryption for key exchange RC4 cipher for bulk data encryption RC4 cipher is using 40 bit key MD5 hashing for data integrity Is exportable outside the US (EXPORT)

02.11.2005

Lecture 8 / Andres Teder

51

02.11.2005

Lecture 8 / Andres Teder

52

SSL Handshake

SSL
More detailed view

02.11.2005

Lecture 8 / Andres Teder

53

02.11.2005

Lecture 8 / Andres Teder

54

JSSE Classes in JDK 1.5

Secure Sockets
SSLSocketFactory
createSocket(Socket s, String host, int port, boolean autoClose)

SSLServerSocketFactory
createSocket(Socket s, String host, int port, boolean autoClose)

02.11.2005

Lecture 8 / Andres Teder

55

02.11.2005

Lecture 8 / Andres Teder

56

UDP Datagrams and Sockets


UDP User Datagram Protocol -> quick but not reliable Some cases of using UDP:
DNS, DHCP Streaming NFS, TFTP, FSP

TCP vs. UDP


TCP call centre
You know that the other party hears what you are saying If the phone is busy or no one there find it out straight away Words arrive in a fixed order

UDP post office

Letters may arrive or not The order of arrival is not fixed The further you are the most likely is the loss of mail

02.11.2005

Lecture 8 / Andres Teder

57

02.11.2005

Lecture 8 / Andres Teder

58

Java and UDP


DatagramPacket(byte[] buf, int length,) DatagramSocket(port) There is no ServerSocket same socket can be used to send and receive data Socket is not dedicated to a single connection (there is no concept of a connection between two hosts) connect(InetAddress address, int port)
enables to talk to one host, default: not connected
02.11.2005 Lecture 8 / Andres Teder 59 02.11.2005

Datagram Socket
Options: SO_RCVBUF, SO_SNDBUF, SO_REUSEADDR, SO_TIMEOUT SO_BROADCAST - enables and disables the ability of the process to send broadcast messages

Lecture 8 / Andres Teder

60

Multicast Sockets
Unicast point to point Multicast broader than point to point but narrower than broadcast data goes to many hosts, but only to those who have shown interest Built on top of UDP In Java - MultiCastSocket
02.11.2005 Lecture 8 / Andres Teder 61

Multicasting
Useful when connecting many agents together on a common communication channel Audio,Video (videoconference) Multiplayer games Distributed Filesystems Database replication
Lecture 8 / Andres Teder 62

02.11.2005

MulticastSocket
1. 2. 3. 4. 5. Create socket Join a multicast group Send data to the members of the group Receive data from the group Leave multicast group

MulticastSocket
MulticastSocket ms = new MulticastSocket(); InetAddress sessAddr = InetAddress.getByName("224.2.76.24"); ms.joinGroup(sessAddr); ms.receive(DatagramPacket) ms.send() ms.leaveGroup(sessAddr)

02.11.2005

Lecture 8 / Andres Teder

63

02.11.2005

Lecture 8 / Andres Teder

64

Summary
Finished overview of Servlets Overview of JSP Custom sockets over TCP Secure sockets Custom sockets over UDP Multicasting

02.11.2005

Lecture 8 / Andres Teder

65

Вам также может понравиться