570 likes | 798 Views
JSP – Dynamic Content Generation Made Simple. Gal Shachor. Agenda. 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?. What is JSP?. JSP == Java Server Pages
E N D
JSP – Dynamic Content Generation Made Simple Gal Shachor
Agenda • 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?
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.
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.
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.
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.
My first JSP Hello World
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>
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
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.
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() %>
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> <% } %>
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> <% } %>
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.
<%! int varname = 1; void jspInit() { System.out.println("inside init"); } %> <%! int varname = 1; void jspInit() { System.out.println("inside init"); } %> 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"); } %>
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 --%> ... --%>
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.
Snoop.jsp • Uses scriptlets to present the request headers and form parameters sent to the page • Employs scriptlets, implicit variables and comments
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> …
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> <% } %>
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>
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
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">
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.*" %>
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/>
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
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.
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.
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.
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
Beanmyname.jsp • Print a name as submitted by the user • Uses JavaBeans and JSP JavaBeans tags: • To parse the parameters sent • Print the parameters
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>
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>
NameBean – The code import java.io.Serializable; publicclass NameBean implements Serializable { String nameProperty = null; String fnameProperty = null; publicvoid setName(String name) { nameProperty = name; } public String getName() { return nameProperty; } publicvoid setFamily(String name) { fnameProperty = name; } public String getFamily() { return fnameProperty; } }
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
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.
Model-1 is: • Very simple to understand. • Makes generation of simple pages simple. • Similar to other technologies such as ASP. • But it also: • Messy when a complex page is needed. • Tend to require lots of Java code in the JSP file (a real no no from a design point of view). 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).
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.
Implementing Model-2 Advanced staff
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)
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
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