This document provides an overview of Java Server Pages (JSP) technology. It discusses JSP's advantages over other technologies like servlets and its ability to combine HTML, XML, and Java code. It also describes the implicit objects available in JSP like request, response, out, and session. Finally, it outlines fundamental JSP tags like declaration, expression, directive, and scriptlet tags.
This document provides an overview of Java Server Pages (JSP) technology. It discusses JSP's advantages over other technologies like servlets and its ability to combine HTML, XML, and Java code. It also describes the implicit objects available in JSP like request, response, out, and session. Finally, it outlines fundamental JSP tags like declaration, expression, directive, and scriptlet tags.
10MCA41 Topics in Enterprise Architecture - I 4th Semester
BasavarajuR, 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. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 2 4. JavaScript: JavaScript can generate HTML dynamically on the client. However, it can only access client environment. JavaScript can't access server-side resources like databases, catalogs, pricing information etc. 5. Static HTML: Regular HTML cannot contain dynamic information. JSP is easy and convenient. 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 in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables. JSP supports nine Implicit Objects which are listed below: Object Description request 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. Each time 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 form data, cookies, HTTP methods etc. The response Object: The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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, HTTP status codes etc. The out Object: The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response. The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered='false' attribute of 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. Unlike the PrintWriter object, JspWriter throws IOExceptions. Following are the important methods which we would use to write boolean char, int, double, object, String etc. Method Description out.print(dataType dt) Print a data type value out.println(dataType dt) Print a data type value then terminate the line with new line character. out.flush() Flush the stream. The session Object: The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the 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 the generated 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 is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method. By adding an attribute to application, you can ensure that all JSP files that make up your web application have access to it. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 4 The config Object: The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters 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. The pageContext object is used to represent the entire JSP page. This object is intended as a means to access information about the page while avoiding most of the implementation details. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object. The pageContext object also contains information about the directives issued to the JSP page, 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 identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class. One of the important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope: pageContext.removeAttribute("attrName", PAGE_SCOPE); 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 an object 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 previous page. 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 end with "%>" just like HTML tags. JSP tags normally have a "start tag", a "tag body" and an "end tag". 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 be referenced by other declarations, scriptlets, or expressions in a java server page. A declaration tag does not generate any output on its own and is usually used in association with Expression or Scriplet Tags. Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration. Syntax :- <%! Declaration %> Example: <%! int var = 1; %> <%! int x, y ; %> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 string and 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 form attr="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 defined our 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 is enclosed between "<%" and "%>" tag elements. The output of the java source code scriplet specified within the Scriptlet tag is executed at the server end and is inserted in sequence with rest 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 and therefore do not appear on the client side web document but can be viewed through the web browsers "view source" option. Syntax :- <%-- comment -- %> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 use of server side JavaBeans. It is not good idea to write the java code inside JSP page, to come over JSP comes with predefined actions tags which can be used to either link to a Java Bean set its properties, or get its properties. The JSP actions provide an abstraction that can be used to easily encapsulate common tasks. The JSP actions are specific tags that affect the runtime of the JSP and the response sent back to the client. 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 for processing. <jsp:forward page="page URL" /> The JSP param action The JSP param action used to pass the request parameter to destination page, while including or forwarding 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" /> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 a result page. <jsp:useBean id="person" scope="session" class="com.java.connect.Person" /> The username is <jsp:getProperty name="person" property="username" /> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 9 JSTL The Java Server Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags. The JSTL tags can be classified, according to their functions, into following JSTL tag library groups 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 include JSTL 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 a difference that <c:out> tag lets you use the simpler "." notation to access properties. For example, to access customer.address.street just use tag is <c:out value="customer.address.street"/>. The <c:out> tag can automatically escape XML tags so they aren't evaluated as actual tags. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 10 Attribute: The <c:out> tag has following attributes: Attribute Description Required Default value Information to output Yes None default Fallback information to output No body escapeXml 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 it evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object. Attribute: The <c:set> tag has following attributes: Attribute Description Required Default value Information to save No body target Name of the variable whose property should be modified No None property Property to modify No None var Name of the variable to store information No None scope Scope of variable to store information No Page If target is specified, property must also be specified. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 if thrown 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> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 12 This would produce following result: The exception is : java.lang.ArithmaticException: / by zero There is an exception: / by zero c: remove The <c:remove> tag removes a variable from either a specified scope or the first scope where the variable is found (if no scope is specified). This action is not normally particularly helpful, but it can 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 Default var Name of the variable to remove Yes None scope 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: 4000 After Remove Value: 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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="f alse" /> </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(); } } 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 number of 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 similar way <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 Default test 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: 4000 Salary is very low. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 a scriptlet. The <c:forEach> tag is the more commonly used tag because it iterates over a collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the tokens. Attribute: The <c:forEach> tag has following attributes: Attribute Description Required Default items Information to loop over No None begin Element to start with (0 = first item, 1 = second item, ...) No 0 end Element to end with (0 = first item, 1 = second item, ...) No Last element step Process every step items No 1 var Name of the variable to expose the current item No None varStatus Name of the variable to expose the loop status No None The <c:forTokens> tag has similar attributes as <c:forEach> except one additional attribute delims which specifies sharacters to use as delimiters. Attribute Description Required Default delims 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 1 Item 2 Item 3 Item 4 Item 5 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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: Zara nuha roshy Network tags c: import The <c:import> tag provides all of the functionality of the <include> action but also allows for inclusion of absolute URLs. For example, using the import tag allows for inclusion of content from a different Web site or an FTP server. Attribute: The <c:import> tag has following attributes: Attribute Description Required Default url URL to retrieve and import into the page Yes None context / followed by the name of a local web application No Current application charEncoding Character set to use for imported data No ISO-8859-1 var Name of the variable to store imported text No Print to page scope Scope of the variable used to store imported text No Page varReader Name of an alternate variable to expose java.io.Reader No None 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 would store in variable data which will be printed eventually. c: redirect The <c:redirect> tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the <c:param> tag. Attribute: The <c:redirect> tag has following attributes: Attribute Description Required Default url URL to redirect the user's browser to Yes None context / 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 as shown 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 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 automatically performs URL rewriting when necessary. The var attribute specifies the variable that will contain the 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 any parameters specified by children paramtag. Attribute: The <c:url> tag has following attributes: Attribute Description Required Default value Base URL Yes None context / followed by the name of a local web application No Current application var Name of the variable to expose the processed URL No Print to page scope 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 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 for internationalized 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, or percentage. <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 variable or the bundle configuration variable. <fmt:timeZone> Specifies the time zone for any time formatting or parsing actions nested 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 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 sql attribute. <sql:update> Executes the SQL update defined in its body or through the sql attribute. <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.Date value. <sql:transaction > Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 parsing XML, 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 tag body. <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 its body. 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 mutually exclusive conditional operations, marked by <when> and <otherwise> <x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true' <x:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of 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 XSLT stylesheet 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 tag is 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 just as you would the built-in tags you learned about in earlier chapter. The JSP 2.0 specification introduced Simple Tag Handlers for writing these custom tags. To write a customer tab you can simply extend SimpleTagSupport class and override the doTag() 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 the following 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 us create 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 using getJspContext() method and uses it to send " RNS Institute of Technology " to the current JspWriter object. 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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. Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion 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(); 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 before being written to the JspWriter associated with the tag. Now accordingly we need to change TLD file 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 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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 attribute name must be unique for a particular tag. required This specifies if this attribute is required or optional. It would be false 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 is assumed 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 to JavaBean 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; 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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; } } 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 28 Output Nested Tags JSP program to implement nested tags using TagSupport class 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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; } } 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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( ) { 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 33 </custom:parent > </body> </html> Output: 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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"/> 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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; } 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, 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: 10MCA41 Topics in Enterprise Architecture - I 4th Semester BasavarajuR, Asst. Professor Dept. of MCA, RNSIT 38 Output:
1.INTRODUCTION
A voice browser is a “device which interprets a (voice) markup language and is capable of generating voice output and/or interpreting voice input,and possibly other input/output modalities." The definition of a voice browser, above, is a broad one.The fact that the system deals with speech is obvious given the first word of the name,but what makes a software system that interacts with the user via speech a "browser"?The information that the system uses (for either domain data or dialog flow) is dynamic and comes somewhere from the Internet.
From an end-user's perspective, the impetus is to provide a service similar to what graphical browsers of HTML and related technologies do today, but on devices that are not equipped with full-browsers or even the screens to support them. This situation is only exacerbated by the fact that much of today's content depends on the ability to run scripting languages and 3rd-party pl
1.INTRODUCTION
A voice browser is a “device which interprets a (voice) markup language and is capable of generating voice output and/or interpreting voice input,and possibly other input/output modalities." The definition of a voice browser, above, is a broad one.The fact that the system deals with speech is obvious given the first word of the name,but what makes a software system that interacts with the user via speech a "browser"?The information that the system uses (for either domain data or dialog flow) is dynamic and comes somewhere from the Internet.
From an end-user's perspective, the impetus is to provide a service similar to what graphical browsers of HTML and related technologies do today, but on devices that are not equipped with full-browsers or even the screens to support them. This situation is only exacerbated by the fact that much of today's content depends on the ability to run scripting languages and 3rd-party pl