Dynamic Web programming with Servlets
Download
Report
Transcript Dynamic Web programming with Servlets
JSP – Dynamic Content Generation Made Simple
Gal Shachor
IBM Labs in Haifa
IBM Labs in Haifa
Agenda
2
JSP – What and Why?
My first JSP
JSP Fundamentals
JSP Directives and APIs
JSP and Tags
MVC (Model 2) Application
We did not talk about…
JSP
What is it? Why do we need it?
IBM Labs in Haifa
IBM Labs in Haifa
What is JSP?
JSP == Java Server Pages
A simplified way to generate dynamic web content
Simpler then Servlets (Java is not mandatory)
Editing tool friendly
Can be used to separate the coding of presentation and business
logic
JSP is based on Java and Servlet technologies
An HTML page with imbedded tags and Java Code.
At runtime the JSP page is translated into a Java Servlet
The runtime is usually encapsulated in a special JSP-Runtime
Servlet.
4
IBM Labs in Haifa
JSP – A standard
JSP is a Java Standard:
Defined by a group of companies led by JavaSoft.
Current version is 1.2, but previous versions are also in use (mainly
1.1).
Ongoing effort to improve JSP.
5
IBM Labs in Haifa
Why JSP?
Because it is needed!
In fact, there are several JSP like technologies both in the Java (as
well as non-Java) world
Servlets that generate HTML output hide the HTML inside Java.
Makes it hard for an HTML expert (!= Java expert) to fix stuff.
Lock the content in Java.
Makes look and feel changes to the site problematic.
The ability to script with Java and JavaBeans makes generating dynamic
content simpler.
The competitors (ASP/SSJS) provide an extremely !!! simple (and
appealing) method for generating dynamic content.
6
IBM Labs in Haifa
The JSP Syntax
Inline Java code delimited by <% and %>.
Also printing of expressions as text by using <%= %>.
Special tags to declare class wide variables and methods.
Special tags to use with JavaBeans.
Special tags to expose JSP services.
JSP directives to specify.
Interfaces implemented by the Servlet, classes it extends, packages
to import etc.
7
My first JSP
Hello World
IBM Labs in Haifa
IBM Labs in Haifa
Helloworld.jsp – The code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<%@ page language="java"
contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII" %>
<META name="GENERATOR" content="IBM WebSphere Studio">
<TITLE>helloworld.jsp</TITLE>
</HEAD>
<BODY>
<P> <% out.print("This is a sample JSP file"); %> </P>
</BODY>
</HTML>
9
IBM Labs in Haifa
Helloworld.jsp – Output
10
IBM Labs in Haifa
Helloworld.jsp – Observations
At first, the JSP file looks like a regular HTML page
HTML tags, doctype, etc.
There is a new <%@ page … %> “Tag” that has nothing to do with HTML
This is a JSP directive
We have some Java code enclosed between <% and %>
This is a JSP scriptlet
11
JSP Fundamentals
IBM Labs in Haifa
IBM Labs in Haifa
JSP Fundementals
Adding Java to a plain HTML page.
Scriptlets
Use JSP implicit variables.
To obtain information.
To write data back to the user.
Defining class wide variables and methods.
For initialization.
Commenting your scripts.
13
IBM Labs in Haifa
JSP Scriptlets
Scriptlets let the developer place inline Java code inside the HTML
General syntax: <% Java code %>
<% i++; %>
Expression placement lets the developer place a Java expression
(converted to a String) inline with the HTML
General syntax <%= expression %>
<%= new Date() %>
14
IBM Labs in Haifa
Scriptlets and Conditional HTML
Scriptlets can be used to implement conditional HTML
<% if(variable ) { %>
<h1> variable is true </h1>
<% } else { %>
<h1> variable is false </h1>
<% } %>
15
IBM Labs in Haifa
Scriptlets and Looping
Scriptlets can be used to implement loops inside the HTML.
<% for(int k = 0 ; k < 10 ; k++ ) { %>
<h1> variable’s value is <%= k %> </h1>
<% } %>
16
IBM Labs in Haifa
JSP Implicit Variables
JSP has several implicit variables that can be used freely within the
JSP page.
Available without prior declaration and definition.
Provides all the services and APIs that are available for the
servlet developer.
Some of the implicit variables are:
request – The HttpServletRequest object as arrived to the
service method.
response – The HttpServletResponse object as arrived to the
service method.
out – A JspWriter connected to the ServletOutputStream of
response.
session – The HttpSession object associated with the current
user-session.
17
IBM Labs in Haifa
Class Wide Declarations
Class wide can be used to define instance methods and variables in the
page.
These methods and variables end up defined in the class created
from the JSP file.
Class wide declarations are enclosed within a <%! %> pair.
Example usage can be creating initialization code.
<%!
int varname = 1;
void jspInit()
{
System.out.println("inside init");
}
%>
18
IBM Labs in Haifa
Comments in JSP
There are two types of comments in JSP.
HTML comments that should arrive to the client's browser.
These comments can contain JSP code and Scriptlets that are
executed.
<!-- <% out.print("My comment"); %> -->
Comments to the JSP page itself.
These comments and their content are not interpreted and will not
arrive to the client.
<%-- anything but a closing --%> ... --%>
19
IBM Labs in Haifa
Including Content – The include Directive
A tool for inclusion of content inside the JSP page at translation time.
General syntax:
<%@ Include file="relativeURLspec" %>
File points to a URI that identifies the resource to be included into the
JSP page.
Very useful for sites with specific headers footers etc.
20
IBM Labs in Haifa
Snoop.jsp
Uses scriptlets to present the request headers and form parameters sent
to the page
Employs scriptlets, implicit variables and comments
21
IBM Labs in Haifa
Snoop.jsp – The code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<%@ page language="java"
contentType="text/html; charset=WINDOWS-1255"
pageEncoding="WINDOWS-1255"
import="java.util.*" %>
<META name="GENERATOR" content="IBM WebSphere Studio">
<TITLE>JSP snoop page</TITLE>
</HEAD>
<BODY>
<H1>JSP Snoop page</H1>
…
22
IBM Labs in Haifa
Snoop.jsp – The code
<% Enumeration e = request.getHeaderNames();
if(e != null && e.hasMoreElements()) { %>
<H2>Request headers</H2>
<TABLE>
<TR>
<TH align=left>Header:</TH>
<TH align=left>Value:</TH>
</TR>
<% while(e.hasMoreElements()) {
String k = (String) e.nextElement(); %>
<TR>
<TD><%= k %></TD>
<TD><%= request.getHeader(k) %></TD>
</TR>
<% } %>
</TABLE>
<% } %>
23
IBM Labs in Haifa
Snoop.jsp – The code
<% e = request.getParameterNames();
if(e != null && e.hasMoreElements()) { %>
<H2>Request parameters</H2>
<TABLE>
<TR valign=top>
<TH align=left>Parameter:</TH>
<TH align=left>Value:</TH>
</TR>
<% while(e.hasMoreElements()) {
String k = (String) e.nextElement();
String val = request.getParameter(k); %>
<TR valign=top>
<TD><%= k %></TD>
<TD><%= val %></TD>
</TR>
<% } %>
</TABLE>
<% } %>
</BODY>
</HTML>
24
IBM Labs in Haifa
Snoop.jsp – Output
25
Directives and APIs
IBM Labs in Haifa
IBM Labs in Haifa
JSP Directives and APIs
JSP 1.0 provides directives and APIs to allow enhanced control over the
page.
Directives provides:
Declarative page control (caching for example).
Defining Java related page attributes.
The APIs provides:
Programmatic page control.
Access to information that was supplied by using directives
27
IBM Labs in Haifa
JSP Directives
Directives begin with <%@ and ends with %>
Directives have a type, attributes and values
<%@ type attribute="value" %>
For now the types are
page
include
taglib
<%@ page attribute="value">
28
IBM Labs in Haifa
JSP Page Directives
Page directives provides fine-grained control over the JSP Page
Buffering.
Session Usage.
Importing a Java class
Programming language used in the page
Required locale
…
<%@ page language="java"
contentType="text/html; charset=WINDOWS-1255"
pageEncoding="WINDOWS-1255"
import="java.util.*" %>
29
IBM Labs in Haifa
The taglib Directive
A syntax extension tool for JSP
General syntax
<%@ taglib uri="uriToTagLibrary" prefix="tagprefix" %>
uri - A URI that uniquely names the tag library
prefix - Defines the prefix for the tags in the tag library. The prefix
distinguishes the custom tag. For example myPrefix is the prefix in
the following tag <myPrefix:myTag/>
30
IBM Labs in Haifa
JSP APIs
Extends the servlet APIs to sign a better contract between the JSP
runtime and the JSP Developer.
Expose JSP related information and services to the developer.
JspWriter
Somewhat separate the JSP implementation internals from the
page generated Servlet.
Example PageContext, JspFactory
31
IBM Labs in Haifa
JspWriter
Provides many methods to write data to the user and to manipulate the
page buffer. For example:
clear()
flush()
getBufferSize()
isAutoFlush()
The JspWriter is useful when:
You are writing output from a scriptlet.
You want to control the page buffering.
32
IBM Labs in Haifa
Servlet Instantiation
The container instantiates a new Servlet in two occasions:
A user request service from a Servlet that was not
instantiated yet.
The Servlet is in the list of startup Servlets and the container
is starting.
A Servlet is instantiated in the following manner:
The container loads the Servlet’s class.
Using Class.newInstance() the container instantiates a new
instance of the Servlet.
33
JSP, Java Beans and Tags
IBM Labs in Haifa
IBM Labs in Haifa
JSP and JavaBeans
JavaBeans is the component model used for the Java language:
Portable.
Platform independent.
Written in Java.
Beans are:
Java classes.
Reusable software components.
You can combine several beans to create a bigger whole.
One of the main ideas in JSP is that developers can use JavaBeans to
separate the HTML view from the Java implementation code.
Developers integrate the JavaBeans into the JSP page using special
tags and Scriptlets.
35
IBM Labs in Haifa
Bean Tags in JSP
JSP introduces new tags to handle beans:
Attaching to a certain bean.
jsp:useBean
Initializing a bean.
Setting a bean attribute
jsp:setProperty
Getting a bean attribue.
jsp:getProperty
36
IBM Labs in Haifa
Beanmyname.jsp
Print a name as submitted by the user
Uses JavaBeans and JSP JavaBeans tags:
To parse the parameters sent
Print the parameters
37
IBM Labs in Haifa
Beanmyname.jsp – The code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<%@ page language="java"
contentType="text/html; charset=WINDOWS-1255"
pageEncoding="WINDOWS-1255"
import="NameBean"
%>
<META http-equiv="Content-Type"
content="text/html; charset=WINDOWS-1255">
<TITLE>beanmyname.jsp</TITLE>
</HEAD>
<jsp:useBean id="myusername" scope="page" class="NameBean">
<jsp:setProperty name="myusername" property="*" />
</jsp:useBean>
38
IBM Labs in Haifa
Beanmyname.jsp – The code
<BODY>
<H1>Print my name using JavaBeans</H1>
Your full name Is:
<jsp:getProperty name="myusername" property="name" />
<jsp:getProperty name="myusername" property="family" />
<H1>Send Your Name</H1>
<FORM method="GET" action="beanmyname.jsp">
<P>Your Name: <INPUT type="text" name="name" size="20"></P>
<P>Your Family: <INPUT type="text" name="family" size="20"></P>
<P><INPUT type="submit" value="Submit"> <INPUT type="reset"value="Reset"></P>
</FORM>
</BODY>
39
IBM Labs in Haifa
NameBean – The code
import java.io.Serializable;
public class NameBean implements Serializable {
String nameProperty = null;
String fnameProperty = null;
public void setName(String name) {
nameProperty = name;
}
public String getName() {
return nameProperty;
}
public void setFamily(String name) {
fnameProperty = name;
}
public String getFamily() {
return fnameProperty;
}
}
40
IBM Labs in Haifa
Beanmyname.jsp – Output
41
MVC (Model 2) Application
IBM Labs in Haifa
IBM Labs in Haifa
General Web Application Design Rules
Separate presentation and business logic.
JSP is only about presenting data.
The JSP file does not need to know where the data came from.
Separate the work done by the HTML and Java coders to eliminate
contention.
These are two different developers.
The tools used by the HTML/Java coders are not that good when it
comes to handle Java/HTML code.
Data access and business logic is done in Java.
JSP get to see the results of this business logic via JavaBeans/special
tags.
Servlets and JSP can interact in two access models known as Model-1
and Model-2
43
IBM Labs in Haifa
Java Server Pages Access Models
You can apply the JSP technology in two ways:
Model-1 – A user working in a client web browser makes a request
that is sent to a JSP (.jsp) file. The JSP file accesses server
components that generate dynamic content and displays the dynamic
content in the browser.
Model-2 – A user working in a client web browser makes a request
that is sent to a java Servlet that generates a result and stores the
result in component. The Servlet then calls a JSP file, which
accesses the component and displays the dynamic content in the
browser.
44
IBM Labs in Haifa
Model - 1
Model-1 is very simple to understand and itMakes generation of
simple pages simple.
But it also messy when a complex page is needed and tends to
require lots of Java code in the JSP file (a real no no from a
design point of view).
45
IBM Labs in Haifa
Model - 2
Model-2 is very clean, Makes generation of complex pages
simpler as it removes most of the Java code from the JSP file
and places most of the logic work in Java (where it belongs).
But its not as simple as Model-1 and is makes creation of simple
JSP files a bit complex.
46
Implementing Model-2
Advanced staff
IBM Labs in Haifa
IBM Labs in Haifa
Model 2 Implementation – RequestDispatcher
RequestDispatcher
Allows a Servlet to forward a request to another servlet (or JSP file)
or to include this servlet output in the response
Exposes the methods:
forward(ServletRequest, ServletResponse) – Forwards a request from
a servlet to another resource on the server.
include(ServletRequest, ServletResponse) – Includes the content of a
resource in the response.
Can be obtained using:
ServletContext.getRequestDispatcher(uri),
ServletContext.getNamedDispatcher(servletName),
ServletRequest.getRequestDispatcher(uri)
48
IBM Labs in Haifa
Model 2 Implementation – Passing Parameters
A servlet that uses a RequestDispatcher can pass parameters to the
resource using the ServletRequest object attributes
setAttribute(name, o) – Stores an attribute in this request.
removeAttribute(name) – Removes an attribute from this request.
getAttribute(name) – Returns the value of the named attribute as an
Object, or null if no attribute of the given name exists.
getAttributeNames() – Returns an Enumeration containing the
names of the attributes available to this request.
A dispatching servlet can then use the input parameters to perform some
business logic, obtain data and save it in beans and submit it to a JSP
file
Inside the JSP file tags can be used to extract the bean’s contents
49
IBM Labs in Haifa
Model2myname – Presenting name using Model 2
Same as beanmyname but:
A servlet constructs the
bean with parameters
Uses
RequestDispatcher to
include a View JSP in
the output
50
IBM Labs in Haifa
Model2Dispatcher Servlet – The code
package com.hrl.sample;
import
import
import
import
NameBean;
java.io.IOException;
javax.servlet.*;
javax.servlet.http.*;
public class Model2Dispatcher extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
...
51
IBM Labs in Haifa
Model2Dispatcher Servlet – The code
...
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final NameBean name = new NameBean();
name.setName(req.getParameter("name"));
name.setFamily(req.getParameter("family"));
req.setAttribute("myusername", name);
final RequestDispatcher disp =
req.getRequestDispatcher("model2myname.jsp");
disp.forward(req, resp);
}
}
52
IBM Labs in Haifa
Model2myname.jsp – The code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<%@ page language="java"
contentType="text/html; charset=WINDOWS-1255"
pageEncoding="WINDOWS-1255"
import="NameBean"
%>
<META http-equiv="Content-Type"
content="text/html; charset=WINDOWS-1255">
<TITLE>model2myname.jsp</TITLE>
</HEAD>
<jsp:useBean id="myusername" scope="request" class="NameBean"/>
...
53
IBM Labs in Haifa
Model2myname.jsp – The code
...
<BODY>
<H1>Print my name using MVC</H1>
Your full name Is:
<jsp:getProperty name="myusername" property="name" />
<jsp:getProperty name="myusername" property="family" />
<H1>Send Your Name</H1>
<FORM method="GET" action="Model2Dispatcher">
<P>Your Name: <INPUT type="text" name="name" size="20"></P>
<P>Your Family: <INPUT type="text" name="family" size="20"></P>
<P><INPUT type="submit" value="Submit"> <INPUT type="reset"value="Reset"></P>
</FORM>
</BODY>
54
We did not talk about…
Advanced staff
IBM Labs in Haifa
IBM Labs in Haifa
Lots of interesting staff (20/80 principle kicked in)
56
70% of the APIs and directives
Custom tags
Struts, WebWorks
…
End
IBM Labs in Haifa