jsp notes (java server page) rnsit notes

38
10MCA41 Topics in Enterprise Architecture - I 4th Semester Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 1 JSP - Java Server Pages Introduction JSP is one of the most powerful, easy-to-use, and fundamental tools in a Web-site developer's toolbox. JSP combines HTML and XML with Java servlet (server application extension) and JavaBeans technologies to create a highly productive environment for developing and deploying reliable, interactive, high-performance platform-independent Web sites. JSP facilitates the creation of dynamic content on the server. It is part of the Java platform's integrated solution for server-side programming, which provides a portable alternative to other server-side technologies, such as CGI. JSP integrates numerous Java application technologies, such as Java servlet, JavaBeans, JDBC, and Enterprise JavaBeans. It also separates information presentation from application logic and fosters a reusable- component model of programming. Advantages of JSP over Servlets 1. Servlet use println statements for printing an HTML document which is usually very difficult to use. JSP has no such tedious task to maintain. 2. JSP needs no compilation, CLASSPATH setting and packaging. 3. In a JSP page visual content and logic are seperated, which is not possible in a servlet. 4. There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages. 5. Usually with JSP, Java Beans and custom tags web application is simplified. Advantages of JSP over other Technologies 1. Active Server Pages (ASP) : ASP is a Microsoft technology. The dynamic part of JSP is written in Java, so it is more powerful and easier to use. Secondly, JSP is platform independent whereas ASP is not. 2. Pure Servlets : It is more convenient to write regular HTML than to have println statements that generate HTML. Allows separation of look from the content. In a JSP web designer can design web page separately and servlet programmers can insert the dynamic content separately. 3. Server-Side Includes (SSI) : SSI is widely supported technology for including externally defined pieces into a static web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for real programs that use form data, make database connection.

Upload: anujeet-singh

Post on 07-Feb-2016

168 views

Category:

Documents


6 download

DESCRIPTION

JSP, J2EE, MCA

TRANSCRIPT

Page 1: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 1

JSP - Java Server Pages

Introduction

JSP is one of the most powerful, easy-to-use, and fundamental tools in a Web-sitedeveloper's toolbox.

JSP combines HTML and XML with Java servlet (server application extension) andJavaBeans technologies to create a highly productive environment for developing anddeploying reliable, interactive, high-performance platform-independent Web sites.

JSP facilitates the creation of dynamic content on the server. It is part of the Java platform's integrated solution for server-side programming, which

provides a portable alternative to other server-side technologies, such as CGI. JSP integrates numerous Java application technologies, such as Java servlet, JavaBeans,

JDBC, and Enterprise JavaBeans. It also separates information presentation from application logic and fosters a reusable-

component model of programming.

Advantages of JSP over Servlets

1. Servlet use println statements for printing an HTML document which is usually verydifficult to use. JSP has no such tedious task to maintain.

2. JSP needs no compilation, CLASSPATH setting and packaging.3. In a JSP page visual content and logic are seperated, which is not possible in a servlet.4. There is automatic deployment of a JSP; recompilation is done automatically when

changes are made to JSP pages.5. Usually with JSP, Java Beans and custom tags web application is simplified.

Advantages of JSP over other Technologies

1. Active Server Pages (ASP) : ASP is a Microsoft technology. The dynamic part of JSP iswritten in Java, so it is more powerful and easier to use. Secondly, JSP is platformindependent whereas ASP is not.

2. Pure Servlets : It is more convenient to write regular HTML than to have printlnstatements that generate HTML. Allows separation of look from the content. In a JSPweb designer can design web page separately and servlet programmers can insert thedynamic content separately.

3. Server-Side Includes (SSI) : SSI is widely supported technology for includingexternally defined pieces into a static web page. JSP is better because it lets you useservlets instead of a separate program to generate that dynamic part. Besides, SSI is reallyonly intended for simple inclusions, not for real programs that use form data, makedatabase connection.

Page 2: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 2

4. JavaScript: JavaScript can generate HTML dynamically on the client. However, it canonly access client environment. JavaScript can't access server-side resources likedatabases, catalogs, pricing information etc.

5. Static HTML: Regular HTML cannot contain dynamic information. JSP is easy andconvenient. It is quite feasible to insert small amounts of dynamic data.

JSP Implicit Objects

SP Implicit Objects are the Java objects that the JSP Container makes available to developers ineach page and developer can call them directly without being explicitly declared. JSP ImplicitObjects are also called pre-defined variables.

JSP supports nine Implicit Objects which are listed below:

Object Descriptionrequest This is the HttpServletRequest object associated with the

request.response This is the HttpServletResponse object associated with the

response to the client.out This is the PrintWriter object used to send output to the client.session This is the HttpSession object associated with the request.application This is the ServletContext object associated with application

context.config This is the ServletConfig object associated with the page.pageContext This encapsulates use of server-specific features like higher

performance JspWriters.page This is simply a synonym for this, and is used to call the methods

defined by the translated servlet class.Exception The Exception object allows the exception data to be accessed by

designated JSP.

The request Object:

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Eachtime a client requests a page the JSP engine creates a new object to represent that request.

The request object provides methods to get HTTP header information including formdata, cookies, HTTP methods etc.

The response Object:

The response object is an instance of a javax.servlet.http.HttpServletResponse object. Justas the server creates the request object, it also creates an object to represent the responseto the client.

Page 3: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 3

The response object also defines the interfaces that deal with creating new HTTP headers.Through this object the JSP programmer can add new cookies or date stamps, HTTPstatus codes etc.

The out Object:

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used tosend content in a response.

The initial JspWriter object is instantiated differently depending on whether the page isbuffered or not. Buffering can be easily turned off by using the buffered='false' attributeof the page directive.

The JspWriter object contains most of the same methods as the java.io.PrintWriter class.However, JspWriter has some additional methods designed to deal with buffering. Unlikethe PrintWriter object, JspWriter throws IOExceptions.

Following are the important methods which we would use to write boolean char, int,double, object, String etc.

Method Descriptionout.print(dataType dt) Print a data type value

out.println(dataType dt) Print a data type value then terminate the line with newline character.

out.flush() Flush the stream.

The session Object:

The session object is an instance of javax.servlet.http.HttpSession and behaves exactlythe same way that session objects behave under Java Servlets.

The session object is used to track client session between client requests.

The application Object:

The application object is direct wrapper around the ServletContext object for thegenerated Servlet and in reality an instance of a javax.servlet.ServletContext object.

This object is a representation of the JSP page through its entire lifecycle. This object iscreated when the JSP page is initialized and will be removed when the JSP page isremoved by the jspDestroy() method.

By adding an attribute to application, you can ensure that all JSP files that make up yourweb application have access to it.

Page 4: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 4

The config Object:

The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapperaround the ServletConfig object for the generated servlet.

This object allows the JSP programmer access to the Servlet or JSP engine initializationparameters such as the paths or file locations etc.

The following config method is the only one you might ever use, and its usage is trivial:

config.getServletName();

This returns the servlet name, which is the string contained in the <servlet-name>element defined in the WEB-INF\web.xml file

The pageContext Object:

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. ThepageContext object is used to represent the entire JSP page.

This object is intended as a means to access information about the page while avoidingmost of the implementation details.

This object stores references to the request and response objects for each request. Theapplication, config, session, and out objects are derived by accessing attributes of thisobject.

The pageContext object also contains information about the directives issued to the JSPpage, including the buffering information, the errorPageURL, and page scope.

The PageContext class defines several fields, including PAGE_SCOPE,REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identifythe four scopes. It also supports more than 40 methods, about half of which are inheritedfrom the javax.servlet.jsp. JspContext class.

One of the important methods is removeAttribute, which accepts either one or twoarguments. For example, pageContext.removeAttribute ("attrName") removes theattribute from all scopes, while the following code only removes it from the page scope:

pageContext.removeAttribute("attrName", PAGE_SCOPE);

Page 5: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 5

The page Object:

This object is an actual reference to the instance of the page. It can be thought of as anobject that represents the entire JSP page.

The page object is really a direct synonym for this object.

The exception Object:

The exception object is a wrapper containing the exception thrown from the previouspage. It is typically used to generate an appropriate response to the error condition.

Fundamental JSP Tags

JSP tags are an important syntax element of Java Server Pages which start with "<%" and endwith "%>" just like HTML tags. JSP tags normally have a "start tag", a "tag body" and an "endtag". JSP tags can either be predefined tags or loaded from an external tag library.

Fundamental tags used in Java Server Pages are classified into the following categories:-

Declaration tag Expression tag Directive tag Scriptlet tag Comments

Declaration tag

The declaration tag is used within a Java Server page to declare a variable or method that can bereferenced by other declarations, scriptlets, or expressions in a java server page. A declarationtag does not generate any output on its own and is usually used in association with Expression orScriplet Tags.

Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration.

Syntax :- <%! Declaration %>

Example: <%! int var = 1; %><%! int x, y ; %>

Page 6: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 6

Expression tag

An expression tag is used within a Java Server page to evaluate a java expression at request time.The expression enclosed between "<%=" and "%>" tag elements is first converted into a stringand sent inline to the output stream of the response.

Syntax :- <%= expression %>

Example: <%= new java.util.Date() %>

Directive tag

Directive tag is used within a Java Server page to specify directives to the application server .The directives are special messages which may use name-value pair attributes in the formattr="value".

Syntax :- <%@directive attribute="value" %>

Where directive may be:

1. page: page is used to provide the information about it.Example: <%@page language="java" %>

2. include: include is used to include a file in the JSP page.Example: <%@ include file="/header.jsp" %>

3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to definedour own tags).Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>

Scriptlet tag

A Scriptlet tag is used within a Java Server page to execute a java source code scriplet which isenclosed between "<%" and "%>" tag elements. The output of the java source code scripletspecified within the Scriptlet tag is executed at the server end and is inserted in sequence withrest of the web document for the client to access through web browser.

Syntax :- <% java code %>

Comments

Comments tag is used within a Java Server page for documentation of Java server page code.Comments surrounded with "<%/*" and "*/%" tag elements are not processed by JSP engine andtherefore do not appear on the client side web document but can be viewed through the webbrowser’s "view source" option.

Syntax :- <%-- comment -- %>

Page 7: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 7

JSP Action Tags

The JSP action tag is used to transfer the control between pages and is also used to enable the useof server side JavaBeans. It is not good idea to write the java code inside JSP page, to come overJSP comes with predefined actions tags which can be used to either link to a Java Bean set itsproperties, or get its properties.

The JSP actions provide an abstraction that can be used to easily encapsulate common tasks. TheJSP actions are specific tags that affect the runtime of the JSP and the response sent back to theclient. The JSP actions normally create or act on objects.

Below is list of JSP actions tags:

<jsp:include> <jsp:forward> <jsp:param> <jsp:useBean> <jsp:setProperty> <jsp:getProperty>

The JSP include action

The JSP include action tag used to include a static file or send a request to a dynamic file.

<jsp:include page="page URL" flush="true" />

The JSP forward action

The JSP forward action used to forward a client request to an HTML file, JSP file, or servlet forprocessing.

<jsp:forward page="page URL" />

The JSP param action

The JSP param action used to pass the request parameter to destination page, while including orforwarding using include or forward action tag.

Example of param action in jsp:include action

<jsp: include page="page URL" ><jsp:param name="parameterName" value="parameterValue" />

Page 8: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 8

</jsp: include >Example of param action in jsp:forward action

<jsp:forward page="page URL" ><jsp:param name="parameterName" value="parameterValue" />

</jsp:forward>

The JSP useBean action

The JSP useBean used to instantiates a java bean with a specific name and scope.

<jsp:useBean id="person" scope="session" class="com.java.connect.Person" />

The JSP setProperty action

The JSP action setProperty action use to sets a property value or values in a bean.

<jsp:setProperty name=" person " property="username" value="Mahendra" />

The JSP getProperty action

The JSP getProperty action use to get the value of a bean property so that you can display it in aresult page.

<jsp:useBean id="person" scope="session" class="com.java.connect.Person" />The username is <jsp:getProperty name="person" property="username" />

Page 9: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 9

JSTL

The Java Server Pages Standard Tag Library (JSTL) is a collection of useful JSP tags whichencapsulates core functionality common to many JSP applications.

JSTL has support for common, structural tasks such as iteration and conditionals, tags formanipulating XML documents, internationalization tags, and SQL tags. It also provides aframework for integrating existing custom tags with JSTL tags.

The JSTL tags can be classified, according to their functions, into following JSTL tag librarygroups that can be used when creating a JSP page:

Core Tags Formatting tags SQL tags XML tags

Core Tags

The core group of tags are the most frequently used JSTL tags. Following is the syntax to includeJSTL Core library in your JSP:

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

The Core JSTL Tags are further classified into 3 types:

General-Purpose tags Control and looping tags Network tags

General-purpose tags

c: out

The <c:out> tag displays the result of an expression, similar to the way <%= %> works with adifference that <c:out> tag lets you use the simpler "." notation to access properties. Forexample, to access customer.address.street just use tag is <c:outvalue="customer.address.street"/>.

The <c:out> tag can automatically escape XML tags so they aren't evaluated as actual tags.

Page 10: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 10

Attribute:

The <c:out> tag has following attributes:

Attribute Description Required Defaultvalue Information to output Yes Nonedefault Fallback information to output No bodyescapeXml True if the tag should escape special XML characters No true

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:out> Tag Example</title></head><body><c:out value="${'sample'}"/></body></html>

This would produce following result:

sample

c: set

The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is helpful because itevaluates an expression and uses the results to set a value of a JavaBean or a java.util.Mapobject.

Attribute:

The <c:set> tag has following attributes:

Attribute Description Required Defaultvalue Information to save No bodytarget Name of the variable whose property should be modified No Noneproperty Property to modify No Nonevar Name of the variable to store information No Nonescope Scope of variable to store information No Page

If target is specified, property must also be specified.

Page 11: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 11

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:set> Tag Example</title></head><body><c:set var="salary" scope="session" value="${2000*2}"/><c:out value="${salary}"/></body></html>

This would produce following result:

4000

c: catch

The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it.Simply it is used for error handling and to deal more gracefully with the problem.

Attribute:

The <c:catch> tag has following attributes:

Attribute Description Required Default

var The name of the variable to hold the java.lang.Throwable ifthrown by elements in the body. No None

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:catch> Tag Example</title></head><body>

<c:catch var ="catchException"><% int x = 5/0;%>

</c:catch>

<c:if test = "${catchException != null}"><p>The exception is : ${catchException} <br />There is an exception: ${catchException.message}</p>

</c:if>

</body></html>

Page 12: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 12

This would produce following result:

The exception is : java.lang.ArithmaticException: / by zeroThere is an exception: / by zero

c: remove

The <c:remove> tag removes a variable from either a specified scope or the first scope where thevariable is found (if no scope is specified). This action is not normally particularly helpful, but itcan aid in ensuring that a JSP cleans up any scoped resources it is responsible for.

Attribute: The <c:remove> tag has following attributes:

Attribute Description Required Defaultvar Name of the variable to remove Yes Nonescope Scope of the variable to remove No All scopes

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:remove> Tag Example</title></head><body><c:set var="salary" scope="session" value="${2000*2}"/><p>Before Remove Value: <c:out value="${salary}"/></p><c:remove var="salary"/><p>After Remove Value: <c:out value="${salary}"/></p></body></html>

This would produce following result:

Before Remove Value: 4000After Remove Value:

Page 13: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 13

Conditional and Looping Tags

c: if

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><html><head><title>Using the Core JSTL tags</title></head><body><h2>Here are the available Time Zone IDs on your system</h2><jsp:useBean id="zone" class="ZoneWrapper" /><jsp:useBean id="date" class="java.util.Date" />

<c:if test="${date.time != 0}" >

<c:out value="Phew, time has not stopped yet...<br /><br />" escapeXml="false" />

</c:if><c:set var="zones" value="${zone.availableIDs}" scope="session" />

<c:forEach var="id" items="${zones}">

<c:out value="${id}<br />" escapeXml="false" />

</c:forEach>

</body></html>

import java.util.TimeZone;

public class ZoneWrapper {

public ZoneWrapper() {}

public String[] getAvailableIDs() {

return TimeZone.getAvailableIDs();

}

}

Page 14: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 14

c: choose

The <c:choose> works like a Java switch statement in that it lets you choose between a numberof alternatives. Where the switch statement has case statements, the <c:choose> tag has<c:when> tags. A a switch statement has default clause to specify a default action and similarway <c:choose> has <c:otherwise> as default clause.

Attribute:

The <c:choose> tag does not have any attribute. The <c:when> tag has one attributes which is listed below. The <c:otherwise> tag does not have any attribute.

The <c:when> tag has following attributes:

Attribute Description Required Defaulttest Condition to evaluate Yes None

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:choose> Tag Example</title></head><body><c:set var="salary" scope="session" value="${2000*2}"/><p>Your salary is : <c:out value="${salary}"/></p><c:choose>

<c:when test="${salary <= 25000}">Salary is very low.

</c:when><c:when test="${salary > 25000}">

Salary is good.</c:when><c:otherwise>

No comment...</c:otherwise>

</c:choose></body></html>

This would produce following result:

Your salary is: 4000Salary is very low.

Page 15: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 15

c: forEach

These tags exist as a good alternative to embedding a Java for, while, or do-while loop via ascriptlet. The <c:forEach> tag is the more commonly used tag because it iterates over acollection of objects. The <c:forTokens> tag is used to break a string into tokens and iteratethrough each of the tokens.

Attribute:

The <c:forEach> tag has following attributes:

Attribute Description Required Defaultitems Information to loop over No Nonebegin Element to start with (0 = first item, 1 = second item, ...) No 0end Element to end with (0 = first item, 1 = second item, ...) No Last elementstep Process every step items No 1var Name of the variable to expose the current item No NonevarStatus Name of the variable to expose the loop status No None

The <c:forTokens> tag has similar attributes as <c:forEach> except one additional attributedelims which specifies sharacters to use as delimiters.

Attribute Description Required Defaultdelims Characters to use as delimiters Yes None

Example for <c:forEach>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:forEach> Tag Example</title></head><body><c:forEach var="i" begin="1" end="5">

Item <c:out value="${i}"/><p></c:forEach></body></html>

This would produce following result:

Item 1Item 2Item 3Item 4Item 5

Page 16: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 16

c: forTokens

Example for <c:forTokens>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:forTokens> Tag Example</title></head><body><c:forTokens items="Zara,nuha,roshy" delims="," var="name">

<c:out value="${name}"/><p></c:forTokens></body></html>

This would produce following result:

Zaranuharoshy

Network tags

c: import

The <c:import> tag provides all of the functionality of the <include> action but also allows forinclusion of absolute URLs.

For example, using the import tag allows for inclusion of content from a different Web site or anFTP server.

Attribute:

The <c:import> tag has following attributes:

Attribute Description Required Defaulturl URL to retrieve and import into the page Yes None

context / followed by the name of a local web application No Currentapplication

charEncoding Character set to use for imported data No ISO-8859-1var Name of the variable to store imported text No Print to pagescope Scope of the variable used to store imported text No Page

varReader Name of an alternate variable to exposejava.io.Reader No None

Page 17: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 17

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:import> Tag Example</title></head><body><c:import var="data" url="http://www.tutorialspoint.com"/><c:out value="${data}"/></body></html>

Above example would fetch complete content from tutorialspoint.com/index.htm and wouldstore in variable data which will be printed eventually.

c: redirect

The <c:redirect> tag redirects the browser to an alternate URL by providing automatically URLrewriting, it supports context-relative URLs, and it supports the <c:param> tag.

Attribute:

The <c:redirect> tag has following attributes:

Attribute Description Required Defaulturl URL to redirect the user's browser to Yes Nonecontext / followed by the name of a local web application No Current application

Example:

If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first asshown below:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:redirect> Tag Example</title></head><body><c:redirect url="http://www.photofuntoos.com"/></body></html>

Above example would redirect request to http://www.photofuntoos.com

Page 18: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 18

c: url

The <c:url> tag formats a URL into a string and stores it into a variable. This tag automaticallyperforms URL rewriting when necessary. The var attribute specifies the variable that will containthe formatted URL.

The JSTL url tag is just an alternative method of writing the call to the response.encodeURL()method. The only real advantage the url tag provides is proper URL encoding, including anyparameters specified by children param tag.

Attribute:

The <c:url> tag has following attributes:

Attribute Description Required Defaultvalue Base URL Yes Nonecontext / followed by the name of a local web application No Current applicationvar Name of the variable to expose the processed URL No Print to pagescope Scope of the variable to expose the processed URL No Page

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title><c:url> Tag Example</title></head><body><a href="<c:url value="/jsp/index.htm"/>">TEST</a></body></html>

This would produce following result:

TEST

Page 19: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 19

Formatting tags

The JSTL formatting tags are used to format and display text, the date, the time, and numbers forinternationalized Web sites. Following is the syntax to include Formatting library in your JSP:

<%@ taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt" %>

Following is the list of Formatting JSTL Tags:

Tag Description<fmt:formatNumber> To render numerical value with specific precision or format.

<fmt:parseNumber> Parses the string representation of a number, currency, orpercentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern<fmt:parseDate> Parses the string representation of a date and/or time<fmt:bundle> Loads a resource bundle to be used by its tag body.<fmt:setLocale> Stores the given locale in the locale configuration variable.

<fmt:setBundle> Loads a resource bundle and stores it in the named scoped variableor the bundle configuration variable.

<fmt:timeZone> Specifies the time zone for any time formatting or parsing actionsnested in its body.

<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable<fmt:message> To display an internationalized message.<fmt:requestEncoding> Sets the request character encoding

Page 20: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 20

SQL tags

The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)such as Oracle, mySQL, or Microsoft SQL Server.

Following is the syntax to include JSTL SQL library in your JSP:

<%@ taglib prefix="sql"uri="http://java.sun.com/jsp/jstl/sql" %>

Following is the list of SQL JSTL Tags:

Tag Description<sql:setDataSource> Creates a simple DataSource suitable only for prototyping

<sql:query> Executes the SQL query defined in its body or through the sqlattribute.

<sql:update> Executes the SQL update defined in its body or through the sqlattribute.

<sql:param> Sets a parameter in an SQL statement to the specified value.

<sql:dateParam> Sets a parameter in an SQL statement to the specified java.util.Datevalue.

<sql:transaction > Provides nested database action elements with a sharedConnection, set up to execute all statements as one transaction.

Page 21: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 21

XML tags

The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.Following is the syntax to include JSTL XML library in your JSP.

The JSTL XML tag library has custom tags for interacting with XML data. This includes parsingXML, transforming XML data, and flow control based on XPath expressions.

<%@ taglib prefix="x"uri="http://java.sun.com/jsp/jstl/xml" %>

Following is the list of XML JSTL Tags:

Tag Description<x:out> Like <%= ... >, but for XPath expressions.

<x:parse> Use to parse XML data specified either via an attribute or in the tagbody.

<x:set > Sets a variable to the value of an XPath expression.

<x:if > Evaluates a test XPath expression and if it is true, it processes itsbody. If the test condition is false, the body is ignored.

<x:forEach> To loop over nodes in an XML document.

<x:choose>Simple conditional tag that establishes a context for mutuallyexclusive conditional operations, marked by <when> and<otherwise>

<x:when > Subtag of <choose> that includes its body if its expression evalutesto 'true'

<x:otherwise > Subtag of <choose> that follows <when> tags and runs only if allof the prior conditions evaluated to 'false'

<x:transform > Applies an XSL transformation on a XML document

<x:param > Use along with the transform tag to set a parameter in the XSLTstylesheet

Page 22: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 22

JSP - Custom Tags

A custom tag is a user-defined JSP language element. When a JSP page containing a custom tagis translated into a servlet, the tag is converted to operations on an object called a tag handler.The Web container then invokes those operations when the JSP page's servlet is executed.

JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page justas you would the built-in tags you learned about in earlier chapter. The JSP 2.0 specificationintroduced Simple Tag Handlers for writing these custom tags.

To write a customer tab you can simply extend SimpleTagSupport class and override thedoTag() method, where you can place your code to generate content for the tag.

Create "rnsit" Tag:

Consider you want to define a custom tag named <ex:rnsit> and you want to use it in thefollowing fashion without a body:

<ex:rnsit />

To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let uscreate CollegeTag class as follows:

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

public class CollegeTag extends SimpleTagSupport{

public void doTag() throws JspException, IOException{JspWriter out = getJspContext().getOut();out.println("RNS Institute of Technology");

}}

Above code has simple coding where doTag() method takes the current JspContext object usinggetJspContext() method and uses it to send " RNS Institute of Technology " to the currentJspWriter object.

Page 23: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 23

Create a following tag library file: custom.tld.

<taglib><tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version><short-name>Example TLD</short-name><tag>

<name>rnsit</name><tag-class> CollegeTag </tag-class><body-content>empty</body-content>

</tag></taglib>

Now it's time to use above defined custom tag <rnsit/> in our JSP program as follows:

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%><html>

<head><title>A sample custom tag</title>

</head><body>

<ex:rnsit/></body>

</html>

Try to call above JSP and this should produce following result:

RNS Institute of Technology

Accessing the Tag Body

You can include a message in the body of the tag as you have seen with standard tags. Consideryou want to define a custom tag named <ex:Hello> and you want to use it in the followingfashion with a body:

<ex:Hello>This is message body

</ex:Hello>

Let us make following changes in above our tag code to process the body of the tag:

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

public class HelloTag extends SimpleTagSupport{

StringWriter sw = new StringWriter();

Page 24: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 24

public void doTag()throws JspException, IOException{

getJspBody().invoke(sw);getJspContext().getOut().println(sw.toString());

}}

In this case, the output resulting from the invocation is first captured into a StringWriter beforebeing written to the JspWriter associated with the tag. Now accordingly we need to change TLDfile as follows:

<taglib><tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version><short-name>Example TLD with Body</short-name><tag>

<name>Hello</name><tag-class> HelloTag</tag-class><body-content>scriptless</body-content>

</tag></taglib>

Now let us call above tag with proper body as follows:

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%><html>

<head><title>A sample custom tag</title>

</head><body>

<ex:Hello>This is message body

</ex:Hello></body>

</html>

This will produce following result:

This is message body

Page 25: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 25

Custom Tag Attributes

You can use various attributes along with your custom tags.

The properties for an attribute:

Property Purpose

name The name element defines the name of an attribute. Each attributename must be unique for a particular tag.

required This specifies if this attribute is required or optional. It would befalse for optional.

rtexprvalue Declares if a runtime expression value for a tag attribute is valid

type Defines the Java class-type of this attribute. By default it isassumed as String

description Informational description can be provided.fragment Declares if this attribute value should be treated as a JspFragment.

To accept an attribute value, a custom tag class needs to implement setter methods, identical toJavaBean setter methods as shown below:

Tag handler class (lab11.java)

package jsp;

import java.io.IOException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.TagSupport;

public class lab11 extends TagSupport{

String msg;int start, end;

Page 26: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 26

public void setmsg(String m){

msg=m;}public void setstart(int s){

start=s;}public void setend(int e){

end=e;}

public int doStartTag(){

JspWriter out=pageContext.getOut();try{

out.println("Hello:"+msg);for(int i=start;i<=end;i++){

if(i%2==0)out.println("<br/>"+i);

}out.println("<br/>");

}catch(IOException e){

}return SKIP_BODY;

}

public int doEndTag(){

JspWriter out=pageContext.getOut();try{

out.println("\n Tag closed");}catch(IOException e){

}return SKIP_PAGE;

}}

Page 27: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 27

new_lib.tld

<taglib ><tlib-version>1.0</tlib-version><short-name>new_lib</short-name><uri>/WEB-INF/tlds/new_lib</uri>

<tag><name>enumber</name><tag-class>jsp.lab11</tag-class><attribute>

<name>msg</name><required>true</required>

</attribute><attribute><name>start</name><required>true</required>

</attribute><attribute>

<name>end</name><required>true</required>

</attribute></tag>

</taglib>

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="t" uri="/WEB-INF/tlds/new_lib.tld"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<t:enumber msg="Even numbers are" start="1" end="10" ></t:enumber>

</body>

</html>

Page 28: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 28

Output

Nested Tags

JSP program to implement nested tags using TagSupport class

Page 29: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 29

ParentTagHandler.java

package tag;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

public class ParentTagHandler extends TagSupport

{

private String sports;

public int doStartTag() throws JspException

{

return EVAL_BODY_INCLUDE;

}

public String getSports( )

{

return sports;

}

public void setSports (String sport)

{

this.sports = sport;

}

}

Page 30: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 30

ChildTagHandler.java

package tag;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.Tag;

import javax.servlet.jsp.tagext.TagSupport;

public class ChildTagHandler extends TagSupport

{

public Tag parent;

private String sports;

public int doStartTag() throws JspException

{

ParentTagHandler parentTag = (ParentTagHandler) parent;

if (getSports( ).equals(parentTag.getSports()))

{

return EVAL_BODY_INCLUDE;

}

return SKIP_BODY;

}

public void setParent(Tag parent)

{

this.parent = parent;

}

public String getSports( )

{

Page 31: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 31

return sports;

}

public void setSports (String sports)

{

this.sports = sports;

}

}

nested.tld

<taglib >

<tlib-version>1.0</tlib-version>

<short-name>nested</short-name>

<uri>/WEB-INF/tlds/nested</uri>

<tag>

<name>parent</name>

<tagclass>tag.ParentTagHandler</tagclass>

<bodycontent>scriptless</bodycontent>

<attribute>

<name>sports</name>

<required>true</required>

</attribute>

</tag>

<tag>

Page 32: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 32

<name>child</name>

<tagclass>tag.ChildTagHandler</tagclass>

<bodycontent>scriptless</bodycontent>

<attribute>

<name>sports</name>

<required>true</required>

</attribute>

</tag>

</taglib>

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="custom" uri="/WEB-INF/tlds/nested.tld" %>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<custom:parent sports="Cricket">

<custom:child sports ="Cricket">Rahul Dravid </custom:child>

<custom:child sports ="Chess">Vishwanathan Anand </custom:child>

<custom:child sports ="Tennis">Mahesh Boopathi </custom:child>

Page 33: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 33

</custom:parent >

</body>

</html>

Output:

Page 34: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 34

JSP program to get student information through a html and create a java bean class,populate bean and display the same information through another jsp.

student.html

<html><head>

<title>Student Info</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head><body><center><br/><br/>

<form action="index.jsp" method="post">Enter Name: <input type="text" name="sname"/><br/>Enter USN : <input type="text" name="usnno"/><br/>Enter Branch: <input type="text" name="branch"/><br/><br/><input type="submit" value="submit"/>

</form></center>

</body></html>

Page 35: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 35

index.jsp

<%@page 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="stu" scope="request" class="jsp.Student"/>

<jsp:setProperty name="stu" property="*"/>

<jsp:forward page="view.jsp" />

</body>

</html>

view.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Student Page</title>

</head>

<body>

<jsp:useBean id="stu" scope="request" class="jsp.Student"/>

Page 36: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 36

<center> <b>STUDENT DETAILS</b><br/>

Name: <jsp:getProperty name="stu" property="sname"/><br/>

USN :<jsp:getProperty name="stu" property="usnno"/><br/>

Branch: <%out.print(stu.getbranch());%>

</center>

</body>

</html>

Student.java

package jsp;

public class Student

{

String sname, usnno, branch;

public void setsname(String s)

{

sname=s;

}

public String getsname()

{

return sname;

}

public void setusnno(String u)

{

usnno=u;

}

Page 37: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 37

public String getusnno()

{

return usnno;

}

public void setbranch(String b)

{

branch=b;

}

public String getbranch()

{

return branch;

}

}

Input:

Page 38: JSP Notes (Java Server Page) RNSIT Notes

10MCA41 Topics in Enterprise Architecture - I 4th Semester

Basavaraju R, Asst. Professor Dept. of MCA, RNSIT 38

Output: