Download presentation
Presentation is loading. Please wait.
1
Chapter-6 Java Server Page Notes
2
JSP Overview A JavaServer page (JSP) is a template for a Web page that uses Java code to generate an HTML document dynamically. JSPs are run in a server-side component known as a JSP container, which translates them into equivalent Java servlets. For this reason, servlets and JSP pages are intimately related. What’s possible in one is, in large part, also possible in another, although each technology has its individual strengths. Because they are servlets, JSP pages have all the advantages of servlets: ■ They have better performance and scalability than CGI scripts because they are persistent in memory and multithreaded. ■ No special client setup is required. ■ They have built-in support for HTTP sessions, which makes application programming possible.
3
■ They have full access to Java technology–network awareness, threads, and
database connectivity—without the limitations of client-side applets. But, in addition, JSP pages have advantages of their own: ■ They are automatically recompiled when necessary. ■ Because they exist in the ordinary Web server document space, addressing JSP pages is simpler than addressing servlets. ■ Because JSP pages are HTML-like, they have greater compatibility with Web development tools.
4
How JSP Works A JSP page exists in three forms:
■ JSP source code This is the form the developer actually writes. It exists in a text file with an extension of .jsp, and consists of a mix of HTML template code, Java language statements, and JSP directives and actions that describe how to generate a Web page to service a particular request. ■ Java source code The JSP container translates the JSP source code into the source code for an equivalent Java servlet as needed. This source code is typically saved in a work area and is often helpful for debugging. ■ Compiled Java class Like any other Java class, the generated servlet code is compiled into byte codes in a .class file, ready to be loaded and executed.
5
The JSP container manages each of these forms of the JSP page automatically, based on the timestamps of each file. In response to an HTTP request, the container checks to see if the .jspsource file has been modified since the .javasource was last compiled. If so, the container retranslates the JSP source into Java source and recompiles it. Figure 5-1 illustrates the process used by the JSP container. When a request for a JSP page is made, the container first determines the name of the class corresponding to the .jspfile. If the class doesn’t exist or if it’s older than the .jspfile (meaning the JSP source has changed since it was last compiled), then the container creates Java source code for an equivalent servlet and compiles it. If an instance of the servlet isn’t already running, the container loads the servlet class and creates an instance. Finally, the container dispatches a thread to handle the current HTTP request in the loaded instance.
7
Components of a JSP Page
A .jsp file can contain JSP elements, fixed template data, or any combination of the two. JSP elements are instructions to the JSP container about what code to generate and how it should operate. These elements have specific start and end tags that identify them to the JSP compiler. Template data is everything else that is not recognized by the JSP container. Template data (usually HTML) is passed through unmodified, so the HTML that is ultimately generated contains the template data exactly as it was coded in the.jsp file.
8
Elements of JSP Three types of JSP elements exist Directives
Scripting elements, including expressions, scriptlets, and declarations Actions
9
Directives Directives are instructions to the JSP container that describe what code should be generated. They have the general form directive-name [attribute="value" attribute="value" ...] %> The JSP 1.1 specification describes three standard directives available in all compliant JSP environments: page include Taglib
10
The page Directive The page directive is used to specify attributes for the JSP page as a whole. It has the following syntax: page [attribute="value" attribute="value" ...] %> where the attributes are any of those listed in Table
11
page Directive Example
import ="java.util.Date"%> contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Todays Date</title> </head><%Date date = new Date(); %> <body> <h1>Todays Date</h1> <p>Todays date :<%=date %></p> </body> </html>
12
Attributes of the Page Directive
Value Attribute The language used in scriptlets, expressions, and declarations. In JSP 1.1, the only valid value for this attribute is java. language The fully qualified name of the superclass of this JSP page. This must be a class that implements the HttpJspPage interface. The JSP specification warns against the use of this attribute without fully understanding its implications. extends A comma-separated list of one or more package.* names and/or fully qualified class names. This list is used to create corresponding import statements in the generated Java servlet. The following packages are automatically included and need not be specified:java.lang.* java.servlet.* java.servlet.jsp.* java.servlet.http.* Import true or false, indicating whether the JSP page requires an HTTP session. If the value is true, then the generated servlet will contain code that causes an HTTP session to be created (or accessed, if it already exists). The default value is true. session Specifies the size of the output buffer. Valid entries are nnnkb or none, where nnn is the number of kilobytes allocated for the buffer. The default value is 8kb. buffer true if the buffer should be automatically flushed when it is full, or false if a buffer overflow exception should be thrown. The default value is true. autoflush true if the page can handle simultaneous requestsfrom multiple threads, or false if it cannot. If false,the generated servlet declares that it implements the SingleThreadModelinterface. isThreadSafe A string that will be returned by the page’s getServletInfo()method. Info true if this page is intended to be used as another JSP’s error page. In that case, this page can be specified as the value of the errorPageattribute in the other page’s pagedirective. Specifying true for this attribute makes the exception implicit variable available to this page. The default value is false. isErrorPage Specifies the URL of another JSP page that will be invoked to handle any uncaught exceptions. The other JSP page must specify isErrorPage="true" in its pagedirective. errorPage Specifies the MIME type and, optionally, the character encoding to be used in the generated servlet. contentType Note: More than one page directive can be in a file and the attributes specified collectively apply to the whole file, but no attribute can be specified more than once, with the exception of the importattribute.
13
The include Directive The include directive merges the contents of another file at translation time into the .jsp source input stream, much like a #includeC preprocessor directive. The syntax is include file="filename" %> where filename is an absolute or relative pathname interpreted according to the current servlet context. Examples would be include file="/header.html" %> include file="/doc/legal/disclaimer.html" %> include file="sortmethod" %> The include directive contrasts with the <jsp:include>action ,which merges the output of another file at request time into the response output stream. Either element can be used to include standard headers and footers or other common text in JSP pages.
14
The taglib Directive The taglib directive makes custom actions available in the current page through the use of a tag library. The syntax of the directive is taglib uri="tagLibraryURI" prefix="tagPrefix" %> where the attributes are those listed here:
15
tagLibraryURI tagPrefix The URL of a Tag Library Descriptor. A unique prefix used to identify custom tags used later in the page
16
Expressions JSP provides a simple means for accessing the value of a Java variable or other expression and merging that value with the HTML in the page. The syntax is <%= exp %> where exp is any valid Java expression. The expression can have any data value, as long as it can be converted to a string. This conversion is usually done simply by generating an out.print()statement. For example, the JSP code The current time is <%= new java.util.Date() %>
17
Scriptlets A scriptlet is a set of one or more Java language statements intended to be used to process an HTTP request. The syntax of a scriptlet is <% statement; [statement; ...] %>
18
Scriptlet Example <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>IP Address</title> </head> <body> <%out.println("Your IP Address:"+request.getRemoteAddr()); %> </body> </html>
19
Declarations Like scriptlets, declarations contain Java language statements, but with one big difference: scriptlet code becomes part of the _jspService()method, whereas declaration code is incorporated into the generated source file outside the _jspService()method. The syntax of a declaration section is <%! statement; [statement; ...] %>
20
Implicit Objects Although scriptlets, expressions, and HTML template data are all incorporated into the _jspService()method, the JSP container writes the skeleton of the method itself, initializing the page context and several useful variables. These variables are implicitly available inside scriptlets and expressions (but not declarations). They can be accessed like any other variable, but do not have to be declared first. For example, the HttpServletRequestobject passed to _jspService()is available under the name request, as shown in the following scriptlet: <% String accountNumber = request.getParameter("acct"); if (accountNumber == null) { // ... handle the missing account number problem }%>
21
Implicit Variables Value Variable Name
The ServletRequestor HttpServletRequest being serviced. request The ServletResponseor HttpServletResponse that will receive the generated HTML output. response The PageContextobject for this page. This object is a central repository for attribute data for the page, request, session, and application. pageContext If the JSP page uses an HttpSession, it is available here under the name session. session The servlet context object. application
22
Implicit Variables Value Variable Name
The character output stream used to generate the output HTML. out The ServletConfigobject for this servlet context. config A reference to the JSP page itself. page An uncaught exception that causes the error page to be invoked. This variable is available only to pages with isErrorPage="true". exception
23
Standard Actions Actions are high-level JSP elements that create, modify, or use other objects. Unlike directives and scripting elements, actions are coded using strict XML syntax <tagname [attr="value" attr="value" ...] > ... </tag-name> or, if the action has no body, an abbreviated form: <tagname [attr="value" attr="value" ...] /> XML syntax requires the following: Every tag must have matching end tag or use the short form /> previously shown Attribute values must be placed in quotes Tags must nest properly: <A><B> ... </B></A> is legal, but <A><B> ...</A></B> is not.
24
Standard Actions Description Tag Name
Declares a Java Bean instance and associates it with a variable name. Syntax is<jsp:useBean id="name"[ type="type" ][ class="class" ][ beanName="beanName" ][scope="page|request|session|application"]> ...</jsp:useBean> <jsp:useBean> Sets the values of one or more properties of a bean previously declared with <jsp:useBean>. Syntax is <jsp:setProperty name="id"prop-expression/>where prop-expression is one of the following: property="*"property="propName"property="propName" param="parameterName" property="propName" value="value"property="propName" value=<%= expression %> <jsp:setProperty>
25
<jsp:getProperty>
Standard Actions Description Tag Name Returns the value of the specified property of a bean. Syntax is<jsp:getProperty name="id" property="name" /> <jsp:getProperty> Invokes another resource and merges its output stream with the JSP page output stream. Syntax is <jsp:include page="URL" flush="true" /> or, if parameters need to be passed:<jsp:include page="URL" flush="true"><jsp:param … /><jsp:param … />...<jsp:param ... /></jsp:include> <jsp:include>
26
Standard Actions Description Tag Name
Forwards this HTTP request to another JSP page or servlet for processing. Syntax is<jsp:forward page="URL" />or, if parameters need to be passed:<jsp:forward page="URL"><jsp:param ... /><jsp:param ... />...<jsp:param ... /></jsp:forward> <jsp:forward> Binds a value to a name and passes the binding to another resource invoked with <jsp:include>or <jsp:forward>. Syntax is<jsp:param name="name" value="value" /> <jsp:param>
27
Standard Actions Description Tag Name
Used to generate the appropriate HTML linkage for downloading the Java plugin:<jsp:plugintype="bean|applet"code="objectCode"codebase="objectCodebase"{ align="alignment" }{ archive="archiveList" }{ height="height" }{ hspace="hspace" }{ jreversion="jreversion" }{ name="componentName" }{ vspace="vspace" }{ width="width"}{ nspluginurl="url" }{ iepluginurl="url" } > { <jsp:params>{ <jsp:param name="name" value="value" />}+</jsp:params> }}</jsp:plugin> <jsp:plugin>
28
JSP Example Login Verification (index.jsp)
contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>UserName Password verification </h1> <form action="verify.jsp" method ="get"> Enter UserName:<input type="text" name="uname" value="" /><br> Enter Password:<input type="text" name="pass" value="" /><br> <input type="submit" value="submit" /> </form> </body> </html> Program using scriptlet, expression, declaration, directive , implicit object, and actions
29
verify.jsp <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%! String uname, pass;%> <% uname= request.getParameter("uname"); pass=request.getParameter("pass"); if (uname.equals("jazan")&& pass.equals("university")) {%> <jsp:forward page="welcome.jsp"/> <%} else Wrong UserName/Password, Try again!!! <jsp:include page ="index.jsp"/> <%}%> </body> </html>
30
welcome.jsp contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%! String uname, pass;%> <% uname= request.getParameter("uname"); pass=request.getParameter("pass"); %> Welcome, <%=uname%> <br> Your password is : <%=pass </body> </html>
31
Jsp and javabeans What Is a JavaBean?
The definition of a bean is purposely broad. A bean is simply a Java class that meets two requirements: It has a zero-argument constructor. It implements Serializable or Externalizable to make it persistent. Bean Properties In addition, most beans have properties. Properties are attributes of the bean for which the bean provides read and/or write methods. All access to the bean’s properties must be done through these methods; the underlying data field (if there is one) is private. Part of the JavaBeans programming model is the naming convention used for these methods. Unless you make special provision through a BeanInfoclass, the read method for a property is a public method named get<PropertyName>(), where <PropertyName> is the name of the property with the first letter converted to uppercase. Similarly, the write method, if there is one, is named set<PropertyName>().
32
Example Using jsp & javabeans
//index.jsp contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form action="first.jsp" method ="get"> Enter Usn:<input type="text" name="usn" value="" /><br> Enter Name:<input type="text" name="name" value="" /><br> Enter Course:<input type="text" name="course" value="" /><br> <input type="submit" value="submit" /> </form> </body> </html>
33
StudentBean.java package bean; public class StudentBean { private String usn; public String getUsn() { return usn; } public void setUsn(String usn) { this.usn = usn; private String name; public String getName() { return name;
34
public void setName(String name) { this
public void setName(String name) { this.name = name; } private String course; public String getCourse() { return course; public void setCourse(String course) { this.course = course;
35
first.jsp contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <jsp:useBean id="stud" scope="request" class="bean.StudentBean"/> <jsp:setProperty name="stud" property="*"/> <jsp:forward page="display.jsp"/> </body> </html>
36
welcome.jsp contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <jsp:useBean id="stud" scope="request" class="bean.StudentBean"/> Usn:<jsp:setProperty name="stud" property="usn"/> Name:<jsp:setProperty name="stud" property="name"/> Couse:<jsp:setProperty name="stud" property="course"/> </body> </html>
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.