A Gentle Introduction to Java Server Pages John Selmys Seneca College July 2010
What is JSP? Tool for developing dynamic web pages developed by SUN (now Oracle) High-level abstraction of Java Servlets - extension to Java Servlets Combination of Java Scriptlets and a markup language such as HTML Server side scripting language Current version is 2.1 as of July 2010
A Java Server Page Java code embedded into a HTML page capable of generating dynamic content Syntax takes the form of JSP tags File extension becomes.jsp Application server compiles, loads and executes the Java code First page view (generation) may be slow but succeeding ones are much faster
Application Server Capable of running JSP Apache Tomcat IBM Websphere Oracle Glassfish Redhat Jboss Eclipse Jetty Apple WebObjects Adobe Jrun
JSP Syntax XML-like tags are the syntax of JSP Start with < and end with > Similar to HTML tags Start tag body End tag May be predefined beginning with jsp: May be loaded from a tag library
JSP Elements Directive Declaration Scriptlet Expression Comment Action Custom
JSP Directives <%@... %> Instructs the app server (JSP engine) how to set up this java server page Examples <%@ page language= java %> <%@ include file= url %> <%@ taglib uri= uri-to-taglib %>
JSP Declarations <%!... %> Declares variables and methods to be used in later java code Examples <%! int i = 0; %> <%! Apple anapple = new Apple( red ); %> <%! int AddNumbers(int x, int y) { return x+y; } %> <%! char c; %>
JSP Scriptlets <%... %> Contains Java code fragments Example <% out.println( Hello World! ); %> <% String name = request.getparameter( name ); if(name!= null && name.length() > 0) { %> <%@ include file = answer.jsp %> <% } %>
JSP Expressions <%=... %> Value of expression is converted to a string and inserted into the data stream sent to the client. Examples <%= 2+2 %> <%= 2==2 %> <%= new java.util.date() %> <%= request.getremotehost() %> <%= (int)(math.random()*100)+1 %>
JSP Comments <%--... --%> Some comments may be visible to the client while others are not Examples <%-- Comment is not visible on client --%> <%-- Comment is visible on client >
JSP Action Tag <jsp:action... /> Actions are built into the servlet container adding functionality to ease development. include param forward plugin fallback getproperty setproperty usebean
JSP Action Tag <jsp:action... /> Examples <jsp:include page= first.jsp /> <jsp:forward page= checkout.jsp /> <jsp:usebean id= mybean class= org.example.mybean scope= session /> <jsp:getproperty name= mybean property= myproperty />
JSP Custom Tag <prefix:name... /> User defined language element Examples <%@ taglib uri= mytags prefix= ct %> <ct:getname name= thename %>
JSP Implicit Objects CLASS/INTERFACE javax.servlet.servletcontext javax.servlet.servletconfig java.language.throwable javax.servlet.jsp.jspwriter java.language.object javax.servlet.jsp.pagecontext javax.servlet.servletrequest javax.servlet.servletresponse javax.servlet.http.httpsession application config exception out page PageContext request response session OBJECT
application Used to share data between all JSP Examples: application.getattribute( name ); application.getmajorversion(); application.getserverinfo(); application.setvalue( servername, abc.com );
config Used to pass config data to servlet during initialization Example: Data is defined in web.xml file config.getinitparameter( colour );
exception Used for exception handling Example: www.easywayserver.com
out Used to send output to client Examples: out.write("hello World!"); out.clear(); out.newline(); out.flush();
page Is a reference to the current JSP essentially this Not normally used
PageContext Used to get and put scope data relating to the current JSP Four scopes page data destroyed when JSP completes request data destroyed when request completes session data destroyed when session is destroyed application data destroyed when web application is destroyed
PageContext Example: www.roseindia.net
request Used to get data that the client passed to the server during a HTTP request. Data such as Cookie Header Attribute (returns an object) Method Parameter (returns a string) etc.
request Example: www.roseindia.net Example: www.easywayserver.com Example: www.easywayserver.com
response Used to send a response back to the client Creating cookies Creating HTTP headers Setting content type Redirecting work flow
response Examples: response.sendredirect("http://yahoo.com"); response.setcontenttype("application/pdf"); response.addcookie(cookie roseindia) ; response.addheader("author", "Seneca") ;
session Used to store data associated with a particular user session Example: www.easywayserver.com
Expression Language (EL) A scripting language Access to JavaBeans through JSP Available since JSP 2.0 Use servlet to populate your bean Use redirect forward to xfer control to JSP Use EL to use the bean
Expression Language (EL) To access the bean inside your JSP use either <jsp:usebean id="b" class="mybean" scope="application" /> If bean does not exist it will be created <jsp:include page="/myservlet" />
Expression Language (EL) Syntax ${... } Expression is inside the braces Value is computed and inserted into output stream Container finds variables by scope page, request, session, and application Variables can even be other objects
Expression Language (EL) Variables on LHS of dot are Beans or Maps which use (key,value) for access
Expression Language (EL) Implicit Objects pagescope requestscope sessionscope applicationscope parm parmvalues header headervalues cookie initparam pagecontext
Expression Language (EL) The [... ] operator LHS can be a bean, map, list, array... is a string so use If LHS is a Bean then... is a property Map then... is a unique key Array then... is an index List then... is an index
Expression Language (EL) Examples <%= request.getheader( host ) %> ${header[ host ]} ${header.host}
Expression Language (EL) Literals Boolean: true and false Integer: as in Java Floating point: as in Java String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\. Null: null
Expression Language (EL) Operators (other than dot and [ ] ) Arithmetic: +, - (binary), *, / and div, % and mod, - (unary) Logical: and, &&, or,, not,! Relational: ==, eq,!=, ne, <, lt, >, gt, <=, ge, >=, le Empty: Conditional: A? B : C
Expression Language (EL) Precedence high to low and left [ ]. ( ) - (unary) not! Empty * / div % mod + - (binary) < > <= >= lt gt le ge ==!= eq ne && and or? :
Expression Language (EL) Reserved Words and eq gt true instanceof or ne le false empty not lt ge null div mod
Beans JavaBean: reusable software components for Java that can be manipulated visually in a builder tool EJB: server-side model that encapsulates the business logic of an application
Enterprise Java Beans Have public default constructors May have get/set methods Properties are optional May require serialization
EJB Container Provides Component pooling Resource management Transaction management Security Persistence Client management
EJB Containers Apache Geronimo Oracle Glassfish Adobe Jrun Red Hat Jboss IBM Websphere Eclipse Jetty
Enterprise Java Beans Types 1. Session 2. Message-Driven 3. JPA (Java Persistence API) EJB 3.0 Replaces CMP (Container Managed Persistence) Replaces Entity bean 4. Multimedia (future?)
Session Bean Created by client Exists on the server inside the EJB container Performs functions for the client eg. database access eg. computations Destroyed when session ends
Session Bean Stateless Statefull Can be thought of as the same bean used by all users (sessions). Allows concurrent access to the bean Each session has its own copy of the bean Instance variables hold the state of the bean
Stateless Session Bean Example: openejb.apache.org EJB 3.0 uses annotations no need for deployment descriptor file (ejb-jar.xml) Must implement local or remote interfaces or both
Example Developing a Simple Calculator Web Service cwiki.apache.org
Example Accessing EJB in Web applications cwiki.apache.org
Message-Driven Beans Use JMS (Java Message Service) technology Allows J2EE applications to process messages asynchronously Similar to event-driven paradigm Messages may be sent by any J2EE component application client another enterprise bean others
Example Message-Driven Beans www.thedevinfo.com
JPA Beans Java Persistent API Framework to manage relational data in J2EE applications Entity beans give persistent access to database tables Geronimo uses OpenJPA
Example Developing bean managed persistence with JPA cwiki.apache.org