+ All Categories
Home > Documents > Java Enterprise Edition

Java Enterprise Edition

Date post: 01-Jan-2016
Category:
Upload: renee-frye
View: 38 times
Download: 1 times
Share this document with a friend
Description:
Java Enterprise Edition. Java EE Architecture. Tools Required. An IDE which helps Java Application Development , source code writing,compilation, integration and deployment of the components necesssary for Java EE. eg. NetBeans, Eclipse, Jbuilder, Jdeveloper etc. - PowerPoint PPT Presentation
114
Java Enterprise Edition
Transcript
Page 1: Java Enterprise Edition

Java Enterprise Edition

Page 2: Java Enterprise Edition

Java EE Architecture

Page 3: Java Enterprise Edition

Tools Required

• An IDE which helps Java Application Development , source code writing,compilation, integration and deployment of the components necesssary for Java EE. eg. NetBeans, Eclipse, Jbuilder, Jdeveloper etc.

• An Application Server which provides various containers to deploy components. eg. Glassfish, Tomcat, Jboss, Weblogic etc.

• A complete RDBMS (Oracle, MySQL, Sybase)

Page 4: Java Enterprise Edition

Servlet Introduction

• What is Servlet?• A java class which runs in a web server environment.• A compatible web server manages the execution of servlet with the help

of servlet engine when requested by client using an http request.• It gives an http response to the client which can be displayed on

browsers.

Page 5: Java Enterprise Edition

Why it should be used

• Why it should be used?• Efficiency• Persistency• Portability• Robustness• Extensibility• Security

Page 6: Java Enterprise Edition

Servlet Architecture

Page 7: Java Enterprise Edition

GenericServlet & HttpServlet

• A java class qualifies to be a Servlet if it extends javax.servlet.http.HttpServlet

• HttpServlet class is extended from GenericServlet class• GenericServlet.service() method has been defined as an

abstract method• The two objects that the service() method receives are

ServletRequest and ServletResponse• ServletRequest Object

• Holds information that is being sent to the servlet

• ServletResponse Object• Holds data that is being sent back to the client

Page 8: Java Enterprise Edition

GenericServlet & HttpServlet

• Unlike the GenericServlet, when extending HttpServlet, don’t have to implement the service() method. It is already implemented for you

• When HttpServlet.service( ) is invoked, it calls doGet( ) or doPost( ), depending upon how data is sent from the client

• HttpServletRequest and HttpServletResponse classes are just extensions of ServletRequest and ServletResponse with HTTP-specific information stored in them

Page 9: Java Enterprise Edition

Uninstantiated

Servlet LifeCycle

Instantiated

Initialized

ServicingRequests

IdleBusy

Success

Success

Request Serviced

Destroy

Destroy Request Recieved & all service threads idle

Unload

Failure

Page 10: Java Enterprise Edition

Servlet Life Cycle Methods

Page 11: Java Enterprise Edition
Page 12: Java Enterprise Edition
Page 13: Java Enterprise Edition

Servlet Methods

• The init Method• The init method is called when the servlet is first created and is not

called again for each user request.public void init() throws ServletException { // Initialization code...}public void init(ServletConfig config) throws ServletException { super.init(config); // Initialization code...}

Page 14: Java Enterprise Edition

Servlet Methods

• The service Method• The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and

calls doGet, doPost, doPut, doDelete, etc., as appropriate. public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { // Servlet Code}

Page 15: Java Enterprise Edition

Servlet Method

• The doGet, doPost, and doXxx Methods• These methods contain the real meat of your servlet.• Ninety-nine percent of the time, you only care about GET and/or

POST requests, so you override doGet and/or doPost. However, if you want to, you can also override doDelete for DELETE requests, doPut for PUT, doOptions for OPTIONS, and doTrace for TRACE.

Page 16: Java Enterprise Edition

Servlet Method

• The destroy Method• The server may decide to remove a previously loaded servlet

instance, perhaps because it is explicitly asked to do so by the server administrator, or perhaps because the servlet is idle for a long time. Before it does, however, it calls the servlet’s destroy method.

• This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. Be aware, however, that it is possible for the Web server to crash.

Page 17: Java Enterprise Edition

Servlet Architecture

The Request Object• Encapsulates all request information from the client

• request headers• form data and query parameters• other client data {session info, cookies, path ...etc.}

The Response Object• Encapsulates all data sent back to client

• response headers• OutputStream to write data to the client• setting cookies

http://localhost:8080/examples/

Page 18: Java Enterprise Edition

Servlet Architecture

• Request Object Methods• String getContextPath()• Cookies[] getCookies()• String getHeader(String headerName)• Enumeration getHeaderNames()• Enumeration getHeaders(String header)• String getParameter(String parameterName)• String[] getparameterValues(String parameterNames)• Enumeration getParameterNames()• String getQueryString()• HttpSession getSession()

Page 19: Java Enterprise Edition

Servlet Architecture

• Response Object Methods• void setStatus(int statusCode);statusCode can be SC_OK, SC_MOVED_TEMPORARILYSC_NOT_FOUND, SC_BAD_REQUEST.• void sendError(int code, String msg)• void sendRedirect(String url)• void addCookie(Cookie)• void setContentLength(int contentLength)• void setContentType(String contentType)

Page 20: Java Enterprise Edition

Servlet Architecture

• Content Type• application/msword• application/octet-stream (unrecognised binary data)• application/pdf• application/zip• text/html• image/gif• image/jpeg• video/mpeg• video/quicktime

Page 21: Java Enterprise Edition

Servlet Architecture

The HttpSession Object

• Allows for the storage of transient, session data• Easy way to identify a single user between page requests• Servlets can obtain data from session, modify and store it again• Typical Example - Online Store

• Customer profile information• Shopping Cart

• protected void processRequest(HttpServletRequest request, HttpServletResponse response)

• { HttpSession session = request.getSession(); • ..... }

Page 22: Java Enterprise Edition

HttpSession Methods

• public Object getAttribute(String name) • Extracts a previously stored value from a session object. Returns null if no value is associated

with given name.• public void setAttribute(String name, Object value) • Associates a value with a name. • public void removeAttribute(String name) • Removes any values associated with designated name. • getAttributeNames()• public void invalidate()• public boolean isNew()• public void setMaxInactiveInterval(int seconds)• public String getId()

Page 23: Java Enterprise Edition

Structure of web.xml

Page 24: Java Enterprise Edition

Accessing Initialization ParametersServletConfig

1 ServletConfig Object is used for accessing the servlet related information.

• ServletConfig object is accessible in init() and obtain it with getServletConfig() of javax.servlet.Servlet interface.

ServletConfig sc = getServletConfig();

ServletConfig methods• getInitParameter()• getInitParameterNames()• getServletContext()• getServletName()

Page 25: Java Enterprise Edition

Accessing InitializationParameters

Servlet Context

• There is one instance object of the ServletContext interface associated with each Web application deployed into a container.

• <context-param> <param-name>Developer</param-name> <param-value>[email protected]</param-value> </context-param>

• getInitParameter()• getInitParameterNames()• setAttribute()• getAttribute()• getAttributeNames()• removeAttribute()

Page 26: Java Enterprise Edition

Handling Cookies

For adding cookieCookie cookie = new Cookie("cookieName", "cookieValue");response.addCookie(cookie);For retrieving / reading cookie Cookie[] cookies = request.getCookies(); if(cookies != null) { for(int i=0; i < cookies.length; i++) { Cookie thisCookie = cookies[i]; if (thisCookie.getName().equals("cookieName")) { String value = thisCookie.getValue(); }

}}

Page 27: Java Enterprise Edition

Handling Cookies

Setting cookie LifeCookie userCookie = new Cookie("user", "uid1234");userCookie.setMaxAge(60*60*24*365); // 1 yearresponse.addCookie(userCookie);

Page 28: Java Enterprise Edition

Dispatching Requests

• The key to letting servlets forward requests or include external content is to use a RequestDispatcher.

• Obtain a RequestDispatcher by calling the getRequestDispatcher method of ServletContext, supplying a URL relative to the server root.

String url = "/presentation";RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);

dispatcher.forward(request, response);dispatcher.include(request, response);

Page 29: Java Enterprise Edition

Dispatching Requests

• RequestDispatcher Methods• void forward(ServletRequest request, ServletResponse response)• void include(ServletRequest request, ServletResponse response)• The forward method is used when a request is going to be serviced

by other resource such as JSP or servlet.• The include method includes the output from another resources in

the current output.• The important thing is that it is not a redirection. So the fact that

the response came from another servlet is transparent to the client.

Page 30: Java Enterprise Edition

Servlet Filters

• Since Servlet API 2.3, most significant part of API 2.3• Filters are not servlets; they do not actually create a response.• They are preprocessors of the request before it reaches a servlet,

and/or postprocessors of the response leaving a servlet. • In a sense, filters are a mature version of the old "servlet chaining"

concept.• Practical filter ideas include • authentication filters, • logging and auditing filters, • image conversion filters, • data compression filters, encryption filters,

tokenizing filters, filters that trigger resource access events, XSLT filters that transform XML content, or MIME-type

chain filters (just like servlet chaining).

Page 31: Java Enterprise Edition

Servlet Filters

• A filter can:• Intercept a servlet's invocation before the servlet is called• Examine a request before a servlet is called.• Modify the request headers and request data by providing a

customized version of the request object that wraps the real request

• Modify the response headers and response data by providing a customized version of the response object that wraps the real response

• Intercept a servlet's invocation after the servlet is called• We can configure a filter to act on a servlet or group of servlets;

Page 32: Java Enterprise Edition

Servlet Filters

• A filter implements javax.servlet.Filter and defines its three methods:• void setFilterConfig(FilterConfig config)

• server calls setFilterConfig() once to set the filter's configuration object

• FilterConfig getFilterConfig()

• Returns the filter's configuration object• FilterConfig interface has methods to retrieve the filter's name, its

init parameters, and the active servlet context.• void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

• Performs the actual filtering work

Page 33: Java Enterprise Edition

Servlet Filters

Page 34: Java Enterprise Edition

Servlet Filters

• To use this filter, you must declare it in the web.xml deployment descriptor using the <filter>tag, as shown below:

<filter> <filter-name>timerFilter</filter-name> <filter-class>TimerFilter</filter-class></filter><filter-mapping> <filter-name>timerFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>

Page 35: Java Enterprise Edition

Servlet Specifications

• Java Servlet API 2.2• Servlets are now part of the Java Enterprise Edition specification• Servlets now embrace the notion of pluggable Web applications, which can

be configured and deployed in a server-independent manner• Rules have been provided that define how servlets can be distributed across

multiple back-end servers• Response output buffering has been added• Control over HTTP headers has been enhanced• New styles of request dispatching have been added• More advanced error handling can now be used

Page 36: Java Enterprise Edition

Servlet Specifications

• Distributed applications• The Servlet 2.2 specification dictates that, for an app marked as

distributable in its deployment descriptor, there will be a single ServletContext instance per JVM.

• This means the context attributes cannot be used to share global information. Global information in a distributed app needs to be stored externally from the Web server, as is the case in database or EJB component.

• For applications marked as distributable, Servers will use session affinity to efficiently manage user state across multiple back-end servers. This means that all requests that are part of a single session from a particular user are to be handled by only one JVM at a time.

• All objects placed into a session by servlets in a distributed app must implement Serializable

Page 37: Java Enterprise Edition

Servlet Specifications

• Response buffering• One of the most useful features added in version 2.2 of the servlet

API is response buffering. A servlet now has control over whether the server buffers its response, and may dictate how large a buffer the server can use.

• Five new methods • setBufferSize(int size)• getBufferSize()• isCommitted()• reset()• flushBuffer()

• It sends content in the buffer to the client and commits the response.

Page 38: Java Enterprise Edition

Servlet Specifications

• Support for double headers• There's a new method in HttpServletRequest called getHeaders() that can

return multiple values for a given header. This was needed because some headers, such as Accept-Language, can send multiple header values:

• Accept-Language: en• Accept-Language: fr• Accept-Language: ja

• The new addHeader(String name, String value) method sets the header to the given value. While the traditional setHeader() method would replace any existing value or values, addHeader() leaves current settings alone and just sets an additional value. There's also addIntHeader(String name, int value) and addDateHeader(String name, long date).

Page 39: Java Enterprise Edition

Servlet Specifications

• Better dispatching• Finally, Java Servlet API 2.2 provides more convenient request

dispatching.• There's a new getNamedDispatcher(String name) method in

ServletContext that lets a servlet dispatch to a component specified by its registered name instead of a full URI path. This allows dispatching to a component that may not be publicly accessible on any URI path

Page 40: Java Enterprise Edition

Servlet Specifications

• Java Servlet API 2.3• Servlets now require JDK 1.2 or later• A filter mechanism has been created (finally!)• The technique to express inter-JAR dependencies has been

formalized• Rules for class loading have been clarified• New error and security attributes have been added• The HttpUtils class has been deprecated• Several DTD behaviors have been expanded and clarified

Page 41: Java Enterprise Edition

Servlet Specifications

• Inter-JAR dependencies• A WAR file (Web application archive file, added in API 2.2) requires various

other JAR libraries to exist on the server and operate correctly. For example, a Web application using the ParameterParser class needs cos.jar in the classpath. A Web application using WebMacro needs webmacro.jar.

• Before API 2.3, either those dependencies had to be documented (as if anyone actually reads documentation!) or each Web application had to include all its required jar files in its own WEB-INF/lib directory (unnecessarily bloating each Web application).

• Servlet API 2.3 lets you express JAR dependencies within the WAR using the WAR's META-INF/MANIFEST.MF entry.

• If a dependency can't be satisfied, a server can politely reject the Web application at deployment time instead of causing an obscure error message at runtime.

Page 42: Java Enterprise Edition

Servlet Specifications

• Class loaders

• In API 2.3, a servlet container, will ensure that classes in a Web application not be allowed to see the server's implementation classes. In other words, the class loaders should be kept separate.

• It eliminates the possibility of a collision between Web application classes and server classes.

Page 43: Java Enterprise Edition

Servlet Specifications

• Error and Security• You can configure a Web application so that certain error status codes or exception types

cause specific pages to be displayed• <web-app>

<!-- ..... -->• <error-page>

<error-code> 404 </error-code> <location> /404.html

</location>• </error-page>• <error-page>

<exception-type> javax.servlet.ServletException </exception-type> <location> /servlet/ErrorDisplay </location>

• </error-page>• <!-- ..... -->• </web-app>

Page 44: Java Enterprise Edition

Servlet Specifications

• Error and Security• Servlet API 2.3 adds two new request attributes that can help a servlet make an informed

decision about how to handle secure HTTPS connections. • For requests made using HTTPS, the server will provide these new request attributes:• javax.servlet.request.cipher_suite

• A String representing the cipher suite used by HTTPS, if any• javax.servlet.request.key_size

• An Integer representing the bit size of the algorithm, if any• A servlet can use those attributes to programmatically decide if the connection is secure

enough to proceed. An application may reject connections with small bitsizes or untrusted algorithms.

• Another addition, getAuthType() method that returns the type of authentication used to identify a client has been defined to return one of the four new static final String constants in the HttpServletRequest class: BASIC_AUTH, DIGEST_AUTH, CLIENT_CERT_AUTH, and FORM_AUTH.

Page 45: Java Enterprise Edition

Servlet Specifications

• DTD (Document Type Defination) clarifications• Finally, Servlet API 2.3 ties up a few loose ends regarding the web.xml deployment

descriptor behavior. It's now mandated that you trim text values in the web.xml file before use. (In standard non-validated XML, all white space is generally preserved.) This rule ensures that the following two entries can be treated identically:

<servlet-name>hello<servlet-name>and<servlet-name> hello</servlet-name>

Page 46: Java Enterprise Edition

Servlet Specifications

Java Servlet Specification 2.4• On March 7, 2003, Sun Microsystems (working with the JSR (Java

Specification Request) 154 expert group) published the "Proposed Final Draft 2" of the Servlet 2.4 specification

1. Upgraded supports for Http, J2SE, and J2EE: Servlet 2.4 depends on Http1.1 and J2SE 1.3.

2. Additional ServletRequest methods : In Servlet 2.4 four new methods are added in the ServletRequest

• getRemotePort(): It returns the IP source port of the client.• getLocalName(): It returns the host name on which the request was recieved.• getLocalAddr(): It returns the IP address on which the request was recieved. • getLocalPort(): It returns the IP port number.

Page 47: Java Enterprise Edition

Servlet Specifications

Java Servlet Specification 2.4 (contd..)3. New Support for Internationalization and charset choice: To provide support of

internationization, Servlet 2.4 has added two new methods in the ServletResponse interface.

• setCharacterEncoding(String encoding): The purpose of this method is to set the response's character encoding. This method helps us to pass a charset parameter to setContentType(String) or passing a Locale to setLocale(Locale). We can now avoid setting the charset in the setContentType("text/html;charset=UTF-8") as setCharacterEncoding() method pairs with the pre-existing getCharacterEncoding() method to manipulate and view the response's character encoding.

• getContentType(): It is responsible for returning the response's content type. The content type can be dynamically set with a combination of setContentType(), setLocale(), and setCharacterEncoding() calls, and the method getContentType() provides a way to view the generated type string.

Page 48: Java Enterprise Edition

Servlet Specifications

Java Servlet Specification 2.4 (contd..)4. New features has been added in RequestDispatcher: In Servlet 2.4 five new

request attributes has been added for providing extra information during a RequestDispatcher forward() call. This features has been added is Servlet 2.4 to know the true original request URI. The following request attributes are:

• javax.servlet.forward.request_uri• javax.servlet.forward.context_path• javax.servlet.forward.servlet_path• javax.servlet.forward.path_info• javax.servlet.forward.query_string

Page 49: Java Enterprise Edition

Servlet Specifications

Java Servlet Specification 2.4 (contd..)5. In Servlet 2.4 the SingleThreadModel interface has been deprecated.

6. HttpSession details and interaction with logins has been clarified: The new method HttpSession.logout() has been added in Servlet 2.4. Now session allows zero or negative values in the <session-timeout> element to indicate sessions should never time out.

7. Welcome file behavior and Classloading has been clarified. In servlet 2.4 welcome file can be a servlet.

8. The web.xml file now uses XML Schema: Version 2.4 servers must still accept the 2.2 and 2.3 deployment descriptor formats, but all new elements are solely specified in Schema.

Page 50: Java Enterprise Edition

Servlet Specifications

Java Servlet Specification 2.5• On September 26, 2005, Sun Microsystems and the Java Specification

Request 154 Expert Group issued a maintenance release of the Servlet API. This release added several new features and changes, and made enough of an impact on servlets to justify a bump in the version number to Servlet 2.5.

• Apache Tomcat version 6.0 implements the Servlet 2.5 • Jetty server and Sun's GlassFish server also implements Servlet 2.5

Page 51: Java Enterprise Edition

Servlet Specifications

Changes introduced in Servlet 2.51.) A new dependency on J2SE 5.0Servlet 2.5 specification now lists J2SE 5.0 (JDK 1.5) as its minimum platform

requirement. While this limits Servlet 2.5 to those platforms with J2SE 5.0 implementations, this change means that all the new language features from J2SE 5.0 (generics, autoboxing, an improved for loop, a new enum type, static importing, varargs, and metadata annotations) are guaranteed available to Servlet 2.5 programmers.

Traditionally, servlet and JEE releases have moved forward at the measured pace of one JDK level at a time, but this time, the servlet release skipped version 1.4. The expert groups considered the double jump to be justified because J2SE 5.0 offered one compelling feature that the servlet and JEE specifications wanted to use themselves: annotations.

Page 52: Java Enterprise Edition

Servlet Specifications

Java Servlet Specifications 2.5 (contd..)2.) Support For annotations: Annotations provide a mechanism for

decorating java code constructs (classes, methods, fields, etc.) with metadata information. Annotations are mark code in such a way that code processors may alter their behavior based on the metadata information.

Here's a simple Web service annotation example: import javax.jws.WebService;

import javax.jws.WebMethod;

@WebServicepublic class HelloWorldService {

@WebMethodpublic String helloWorld() {

return "Hello World!";

}}

Page 53: Java Enterprise Edition

Servlet Specifications

Java Servlet Specifications 2.5 (contd..)3.) Several web.xml convenience:• While writing a <filter-mapping>, we can now use an asterisk in a <servlet-name>

which will represent all servlets as well as JSP. Previously we used to do<filter-mapping>

<filter-name>FilterName</filter-name><servlet-name>FilterName</

servlet-name> </filter-mapping>

Now,<filter-mapping>

<filter-name>FilterName</filter-name><servlet-name>*</servlet-name>

</filter-mapping>

Page 54: Java Enterprise Edition

Summary

We have covered• JEE Architecture• Servlet Introduction & Advantages• Servlet Request & Response model• Servlet Life Cycle Methods• Servlet Architecture

• Request• Response• Cookies

• Dispatching Requests• Filters• Servlet Specifications

SessionServletConfigServletContext

Page 55: Java Enterprise Edition

JSP Introduction

What is JSP ? • JSP technology allows you to easily create web content that has both static

and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology.

Main reasons to use JSP: • Multi platform Component reuse by using Javabeans and EJB. • By having a separation of presentation and implementation,web designers

work only on the presentation and Java developers concentrate on implementing the application.

Page 56: Java Enterprise Edition

Life Cycle of JSP

Page 57: Java Enterprise Edition

Life Cycle of JSP Pages

JSP Document

.java file

.class file

.class file ready to run

Response Document

Translation

Compilation

Reinitialization

Subsequent User Requests

Page 58: Java Enterprise Edition

JSP Elements

There are three types of elements:

• Directives

• Scripting elements

• Standard Actions

Page 59: Java Enterprise Edition

JSP Elements

• Directives• Page Directive• Include Directive

• Taglib Directive

• Scripting Elements• Comment Element• Declaration Element• Scriptlets• Expression Element

• Standard Actions

Page 60: Java Enterprise Edition

JSP Directives

• JSP Supports what is called JSP directives.• JSP directives are like SSI and not written in Java.• They look like: <%@ directive %>• There are three directives defined by JSP; include, page, and taglib

• JSP directive affects the overall structure of the servlet that results from the JSP page.

Page 61: Java Enterprise Edition

JSP Directives

1) Page Directive

• The page directive lets you control the structure of the servlet by importing classes, customizing the servlet superclass, setting the content type, and the like.

• A page directive can be placed anywhere within the document.

Page 62: Java Enterprise Edition

Page Directive

• Syntax• <%@ page

[ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*}, ..." ] [ session="true | false" ] [ buffer="none | 8kb | sizekb" ] [ autoFlush="true | false" ] [ isThreadSafe="true | false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType=" text/html” ]

[ isErrorPage="true | false" ]

%>

Page 63: Java Enterprise Edition

Page Directive

• Examples:<%@ page language=“java” import=“java.util.*,java.sql.*” contentType=”text/html” session=true page buffer=”8kb” autoFlash=true isThreadSafe=”true” info=”hi” errorPage=”error.jsp” isErrorPage=”false” %>

<%@ include file=“filename”%>

Page 64: Java Enterprise Edition

2.) Include Directive

• Lets you insert a file into the servlet class at the time the JSP file is translated into a servlet.

• An include directive should be placed in the document at the point at which you want the file to be inserted.

• Syntax• <%@ include file="Relative URL" %>• Example• <%@ include file="Navbar.jsp" %>• <%@ include file="Footer.jsp" %>

Page 65: Java Enterprise Edition

3.) Taglib Directive

• It can be used to define custom markup tags;Syntax• <%@ taglib url=“path” prefix=“tag_prefix” %>

Page 66: Java Enterprise Edition

Scripting Elements

1) Comment Element2) Declaration Element3) Scriptlets4) Expression Element

Scripting elements are the elements in a page that can be used to embed Java code in the JSP file. They are commonly used for object manipulation and performing computation that affects the generated content.

Page 67: Java Enterprise Edition

Scripting Elements

• Comment Element• Used to clarify the logic of the JSP code.

1 <%-- Your Comment --%>2 Example:

<%-- This is to display today’s date on the page --%>

<%

out.print(new java.util.Date());

%>

Page 68: Java Enterprise Edition

Scripting Elements

• Declaration Element• It has the form

<%! Your declaration %>

• It is used to declare class members; variables or methods. It does not have any other code than declaratives.

• Class members created here will last forever as long as the class object is alive.

1Example:<%!

int x = 0;

int square(int x){return x * x;

}

%>

Page 69: Java Enterprise Edition

Scripting Elements

Scriptlets• A scriptlet is a piece of Java code sandwiched between <% and %>• A scriptlet can make use of any java API as long as it is appropriate for the

web purpose.• Example:

<%for(int i=1; i <= 10; i++){

out.print(“hello world!<br>”);

}

%>

Page 70: Java Enterprise Edition

Scripting Elements

• Expression Element• It has the format <%= your expression %>• An expression in this context is not a complete java statement; it is just a part of it. • Example:

<p> The square of <%= x%> is <%= square(x) %> as calculated by a JSP program.</p>

Page 71: Java Enterprise Edition

Standard Actions

• Affect the runtime behaviour of JSP• Affect the Response sent back 2 the client• Allow the transfer of control between pages• Action tags use constructs in XML syntax. They control the

behaviour of the servlet engine. They are typically used for• Dynamically Insert a file• Reuse Javabean Component• Forward the user to other page• Access parameters sent with request to do database look up

Page 72: Java Enterprise Edition

Standard Actions

• Syntax1. Include<jsp:include page=”pageURL” flush=”true/false” /> <jsp:param name=”<name1>” value=” val1”/> <jsp:param name=”<name2>” value=” val2”/></jsp:include>

Page 73: Java Enterprise Edition

Standard Actions

• Syntax (contd..)2. Forward<jsp:forward page=”page url “/> <jsp:param name=”<name1>” value=” val1“/> <jsp:param name=”<name2>” value=” val2“/></jsp:include>

Page 74: Java Enterprise Edition

Standard Actions

• Syntax (contd..)3. Plugin - Downloads a plugin to the client Web browser to execute

an applet or Bean. <jsp:plugin type="bean|applet" code="classFileName" codebase="classFileDirectoryName" [ name="instanceName" ] [ archive="URIToArchive, ..." ] [ height="displayPixels" ] [ width="displayPixels" ] [ <jsp:params> [ <jsp:param name="parameterName" value="parameterValue" /> ] </jsp:params> ] [ <jsp:fallback> text message for user </jsp:fallback> ]

</jsp:plugin>

Page 75: Java Enterprise Edition

Standard Actions

• Syntax (contd..)

Example – plugin

<jsp:plugins type=”applet” code=”HelloWorld.class” codebase=”/html”><jsp:params>

<jsp:param name=”times” value=”5” /> </jsp:params>

</jsp:plugins>

Page 76: Java Enterprise Edition

Standard Actions• Syntax (contd..)

4. UseBean

Locates or instantiates a Bean with a specific name and scope. <jsp:useBean id="beanInstanceName" scope="page | request | session | application" { class="package.class" | type="package.class" | class="package.class" type="package.class" | beanName="{package.class | <%= expression %>}" type="package.class" }</jsp:useBean>

Page 77: Java Enterprise Edition

Standard Actions

• Syntax (contd..)

We can get the value of property by<jsp:getProperty name=”formBean” property=”userName” />

We can set the value of property by<jsp:setProperty name=”formBean” property=”userName” value=”vinay” />

Page 78: Java Enterprise Edition

Implicit Objects

• To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, sometimes called implicit objects.

• request• response• pageContext• session

application out config page

Page 79: Java Enterprise Edition

Implicit Objects

Page 80: Java Enterprise Edition

Implicit Objects

Page 81: Java Enterprise Edition

Summary

• We have covered• Jsp Introduction• Jsp Life-Cycle and Life-Cycle Methods• Jsp Elements

• Implicit Objects

Jsp Directives

Page Directive

Include Directive

Taglib Directive

Scriptng Elements

Comment

Declaration

Scriptlets

Expressions

Standard Actions

Include

Forward

Plugin

useBean

request response pageContext session

application out config page

Page 82: Java Enterprise Edition

EL (Expression Language)

• The Expression Language provides a way to simplify expressions in JSP.

• EL provides the ability to use run-time expressions outside JSP scripting elements.

• We have seen that Scripting elements are the elements in a page that can be used to embed Java code in the JSP file. They are commonly used for object manipulation and performing computation that affects the generated content.

• JSP 2.0 adds EL expressions as a scripting element.

Page 83: Java Enterprise Edition

EL (Expression Language)

Advantage• With the addition of EL to the JSP toolkit, the code can be

written using a simpler syntax yet achieving the same results as the JSP elements.

• Another advantage of EL expressions is its use in scriptless JSP pages that do not permit the usage of any of the scripting element subforms.

• If you want a clear seperation between your presentation and business logic, then you also have the choice to force the page to go scriptless.

• By enforcing scriptless pages, the dynamic behavior of JSP pages must be provided through other elements such as JavaBeans, EL expressions, Custom actions and standard tag libraries.

Page 84: Java Enterprise Edition

EL (Expression Language)

• To use EL in jsp use need to set

1isELIgnored="false” in page directive.2Default Value is false.

Valid expressions can include

•Literals•Operators•Variables (beans, arrays, lists, and collections)• implicit objects•Function Calls

We will look at each of these valid expressions seperately:

Page 85: Java Enterprise Edition

EL (Expression Language)

Literals

• The JSP Expression language defines the following literals that can be used in expressions:

• Example• ${3*8}

Boolean Integer Float String Null

Page 86: Java Enterprise Edition

EL (Expression Language)• Operators• Arithmetic: +, - (binary), *, /, div, %, mod, - (unary)• Logical: and, &&, or, ||, !, not• Relational: ==, eq, !=, ne, <, lt, >, gt, <=, le, >=, ge • Comparisons may be made against other values, or against boolean, string,

integer, or floating point literals.• empty: The empty operator is a prefix operation that can be used to

determine if a value is null or empty.• Conditional: A ? B : C. Evaluate B or C, depending on the result of the

evaluation of A.• Example• ${ (6 * 5) + 5 } <%-- evaluates to 35 --%>• ${empty name}

${3 div 4} ${10 mod 4}

Page 87: Java Enterprise Edition

EL (Expression Language)• Variables

• The web container evaluates a variable that appears in an expression by looking up its value according to the behavior of PageContext.findAttribute(String). For example, when evaluating the expression ${product}, the container will look for product in the page, request, session, and application scopes and will return its value. If product is not found, null is returned.

• A variable that matches one of the implicit objects described in Implicit Objects will return that implicit object instead of the variable's value.

• Properties of variables are accessed using the . (dot) operator and can be nested arbitrarily.

Page 88: Java Enterprise Edition

EL (Expression Language)

• Variable (contd..)

• The JSP expression language defines a set of implicit objects, many of which are available in JSP scriplets and expressions:

• pageContext• param• paramValues• header• headerValues• cookie• initParam

8 pageScope

9 requestScope

10 sessionScope

11 applicationScope

Page 89: Java Enterprise Edition

EL Implicit Objects

• pageContext• The context for the JSP page.• It can be used to access the JSP implicit objects such as

request, response, session, out, servletContext etc. • For Example, ${pageContext.response} evaluates to the

response object for the page.Example ${pageContext.session.id}

Page 90: Java Enterprise Edition

EL Implicit Objects

param

• Maps a request parameter name to a single value.• The expression $(param.name) is equivalent to

request.getParameter (name)First.jsp First Name: <input type='text' name='Name'/> Last Name: <input type='text' name='Address'/> <input type='submit' value='Submit'/>Second.jsp

Name is : ${param.Name}Address is : ${param.Address}

Page 91: Java Enterprise Edition

EL Implicit Objects

paramValues

• maps a request parameter name to an array of values.• The expression ${paramvalues.name) is equivalent to

request.getParamterValues(name)

header

• maps a request header name to a single header value• The expression ${header.name} is equivalent to

request.getHeader(name).

Page 92: Java Enterprise Edition

EL Implicit Objects

headerValues

• maps a request header name to an array of values• The expression ${headerValues.name} is equivalent to

request.getHeaderValues(name).

initParam

• maps a context initialization parameter name to a single value

Page 93: Java Enterprise Edition

EL Implicit Objectscookie

• maps cookie names to a single cookie object.

• The expression ${cookie.name.value} returns the value of the first cookie with the given name. If the request contains multiple cookies with the same name, then you should use the ${headerValues.name} expression.

Example

addCookies.java

Cookie c=new Cookie("name","test");

res.addCookie(c);

Test.jsp

Name : ${cookie["name"]}

Value : ${cookie["name"].value}

1 A client request to the server can contain one or more cookies.

Page 94: Java Enterprise Edition

EL Implicit Objects

pageScope

• maps page-scoped variable names to their values.• An EL expression can access an object, with a page scope in the

JSP, with ${pageScope.objectName} • An attribute of the object can be accessed using $

{pageScope.objectName.attributeName}.

ExampleAccessing a page-scoped attribute named as firstName: ${pageScope.firstName}

Page 95: Java Enterprise Edition

EL Implicit Objects

requestScope

• maps request-scoped variable names to their values.• This object allows for access to the attributes of the request

object. • An EL expression can access an object, with a request scope in

the JSP, with ${requestScope.objectName} • An attribute of the object can be accessed using $

{requestScope.objectName.attributeName}ExampleAccessing a request-scoped attribute named as firstName: ${requestScope.firstName}

Page 96: Java Enterprise Edition

EL Implicit Objects

sessionScope

• maps session-scoped variable names to their values.• This object allows for access to the attributes of the session

object. Example• <% session.setAttribute (''name", "John Doe"); %>• ${sessionScope.name} <%-- evaluates to John Doe --%>• <%= session.getAttribute("name"); %> <%-- This is an equivalent

scripting expression --%>

Page 97: Java Enterprise Edition

EL Implicit Objects

applicationScope

• maps application-scoped variable names to their values.• This implicit object allows for access to objects with application

scope.

Page 98: Java Enterprise Edition

EL (Expression Language)

Function CallsDefining Functions:

• The JSP expression language allows you to define a function that can be invoked in an expression.

public class MyFunctions {public static String toCaps( String text ) { return text.toUpperCase(); } }

Page 99: Java Enterprise Edition

EL (Expression Language)

Function Calls (contd..)Using Functions:

XML:<uri>testFunctionsURI</uri><function> <name>toCaps</name> <function-class>mypkg.MyFunctions</function-class> <function-signature>String toCaps( java.lang.String)</function-

signature></function>

Page 100: Java Enterprise Edition

EL (Expression Language)

Function Calls (contd..)Using Functions: (contd..)

JSP:

<%@ taglib prefix="myFunctionTest" uri="testFunctionsURI"%>${myFunctionTest.toCaps("testingCaps")}

Page 101: Java Enterprise Edition

EL (Expression Language)

• Another Example<jsp:useBean id="someName" type="somePackage.someClass" scope="request, session, or application"/><jsp:getProperty name="someName" property="someProperty"/>• The above code can be changed to

${someName.someProperty}

Page 102: Java Enterprise Edition

Summary

• In EL, we have covered

• EL Introduction• EL Advantages• EL Valid Expressions

• Literals• Operators• Variables (beans, arrays, lists, and collections)• implicit objects• Function Calls

Page 103: Java Enterprise Edition

JSTL

• JSTL (JSP Standard Tag Libraries) is a collection of JSP tags developed by Java Community Process.

• The goal of JSTL is to simplify JavaServer Pages programming. • To achieve this goal, JSTL also provides custom tags for many

common JSP page authoring tasks that require scripting statements to manipulate server side dynamic data.

Page 104: Java Enterprise Edition

JSTL

JSTL offers tags through following tag libraries: core - Basic scripting functions xml - XML processing fmt - Internationalization of formatting sql - Data base accessing Custom – User defined tags

JSTL Components• JSTL has three major areas for Web designers.• Core tag libraries• Additional tag libraries• The expression language

Page 105: Java Enterprise Edition

JSTL

• To understand how JSTL works, a very simple example, using JSTL to display "Hello world!". Here is my JSP source code:

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

<body> <c:out value="Hello world!"/>

</body></html>

Page 106: Java Enterprise Edition

JSTLcustom tag library

Components That Make A TAG LIBRARY(i) The Tag Handler Class– Java code that says what to output– Must implement javax.servlet.jsp.tagext.TagSupport

– Goes in same directories as servlet class files and beans(ii) The Tag Library Descriptor File– XML file describing tag name, attributes, and implementing tag handler class– Goes under WEB-INF(iii) The JSP File– Imports a tag library (referencing URL of descriptor file)– Defines tag prefix & – Uses tags

Page 107: Java Enterprise Edition

JSTL

(I) Defining Tag Handler class•Extend the TagSupport class•Import needed packages

import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import java.io.*;

•Override doEndTag– Obtain the JspWriter with getJspContext().getOut()– Use the JspWriter to generate output– Code gets called at request time

Page 108: Java Enterprise Edition

JSTL

(II) Defining Tag Library Descriptor

Page 109: Java Enterprise Edition

JSTL

(II) Defining Tag Library Descriptor (contd..)•Start with XML header•Top-level element is taglib

– Just use tlib-version and short-name as in example•Each tag defined by tag element with:

description, which gives short info. Optional.name, which defines the base tag name.tag-class, which gives the fully qualified class name of the tag handler.

•body-content, which specifies if tag is standalone or contains content between start and end tag.•You can have multiple tag entries in each TLD file.•Put TLD file somewhere under WEB-INF

Page 110: Java Enterprise Edition

JSTL

(III) Using Tags<%@page import="RandomPack.RandomTagClasses"

contentType="text/html" pageEncoding="UTF-8"%><%@ taglib uri="/WEB-INF/tlds/MyRandTag" prefix="random" %><html> <head> <title>Random Page</title> </head> <body> <br/>First Random Value : <random:RandomTagClasses

myrandombound="100"/></body></html>

Page 111: Java Enterprise Edition

Goals Of JSTL

It is designed to be:• Portable - An action described in a tag library must be usable in any JSP container.• Simple - Unsophisticated users must be able to understand and use this

mechanism. Vendors of JSP functionality must find it easy to make it available to users as actions.

• Expressive - The mechanism must support a wide range of actions, including nested actions, scripting elements inside action bodies, and creation, use, and updating of scripting variables.

• Usable from different scripting languages - Although the JSP specification currently only defines the semantics for scripts in the Java programming language, we want to leave open the possibility of other scripting languages.

• Built upon existing concepts and machinery - We do not want to reinvent what exists elsewhere. Also, we want to avoid future conflicts whenever we can predict them.

Page 112: Java Enterprise Edition

Ajax in Java EE

• Ajax can be integrated into a Java EE Web application.• Ajax may require one to introduce large amounts of JavaScript which

tends to mix concerns by introducing monolithic JSPs. In doing so developers faces following pitfalls:• Client side scripting may not be enabled• Cross browser support increases code requirements• Security• Difficulties integrating with Web frameworks• Use of taglibs that don't support asynchronous communications• Threading and other browser-related features• Impact on performance• Testing

Page 113: Java Enterprise Edition

Ajax in Java EE

• Echo3 Web Framework• http://echo.nextapp.com/site/echo3

• Dojo toolkit• http://dojotoolkit.org/demos

• Jmaki• https://ajax.dev.java.net/screencast/jMakiDemo.html

• Gwt• http://www.gwtsite.com/demos/effects/EffectsDemo.html

• IceFaces (Ajax for java EE)• http://www.icefaces.org/main/demos/

Page 114: Java Enterprise Edition

Recommended