JSP Notes (Java Server Page) RNSIT Notes

November 26, 2017 | Author: Anujeet Singh | Category: Java Server Pages, Html Element, Java Servlet, Xslt, Sql
Share Embed Donate


Short Description

JSP, J2EE, MCA...

Description

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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 reusablecomponent 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. Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

1

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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: request

Object

response out session application config pageContext page Exception

Description This is the HttpServletRequest object associated with the request. This is the HttpServletResponse object associated with the response to the client. This is the PrintWriter object used to send output to the client. This is the HttpSession object associated with the request. This is the ServletContext object associated with application context. This is the ServletConfig object associated with the page. This encapsulates use of server-specific features like higher performance JspWriters. This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. 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. Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

2

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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. Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

3

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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 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);

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

4

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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 "" 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 "" surrounding the declaration. Syntax :- Example:

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

5

10MCA41

Topics in Enterprise Architecture - I

4th Semester

Expression tag An expression tag is used within a Java Server page to evaluate a java expression at request time. The expression enclosed between "" tag elements is first converted into a string and sent inline to the output stream of the response. Syntax :-



Example:

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 :- Where directive may be: 1. page: page is used to provide the information about it. Example: 2. include: include is used to include a file in the JSP page. Example: 3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags). Example:

Scriptlet tag A Scriptlet tag is used within a Java Server page to execute a java source code scriplet which is enclosed between "" 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 :-

Comments Comments tag is used within a Java Server page for documentation of Java server page code. Comments surrounded with " 25000}"> Salary is good. No comment...

This would produce following result: Your salary is: 4000 Salary is very low.

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

14

10MCA41

Topics in Enterprise Architecture - I

4th Semester

c: forEach These tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet. The tag is the more commonly used tag because it iterates over a collection of objects. The tag is used to break a string into tokens and iterate through each of the tokens. Attribute: The tag has following attributes: Attribute items begin end step var varStatus

Description Information to loop over Element to start with (0 = first item, 1 = second item, ...) Element to end with (0 = first item, 1 = second item, ...) Process every step items Name of the variable to expose the current item Name of the variable to expose the loop status

Required No No No No No No

Default None 0 Last element 1 None None

The tag has similar attributes as except one additional attribute delims which specifies sharacters to use as delimiters. Attribute Description delims Characters to use as delimiters

Required Default Yes None

Example for : Tag Example Item

This would produce following result: Item Item Item Item Item

1 2 3 4 5

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

15

10MCA41

Topics in Enterprise Architecture - I

4th Semester

c: forTokens Example for : Tag Example

This would produce following result: Zara nuha roshy

Network tags c: import The tag provides all of the functionality of the 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 tag has following attributes: Attribute url

Description URL to retrieve and import into the page

context

/ followed by the name of a local web application

charEncoding Character set to use for imported data var Name of the variable to store imported text scope Scope of the variable used to store imported text Name of an alternate variable to expose varReader java.io.Reader Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

Required Default Yes None Current No application No ISO-8859-1 No Print to page No Page No

None 16

10MCA41

Topics in Enterprise Architecture - I

4th Semester

Example: Tag Example

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 tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the tag. Attribute: The tag has following attributes: Attribute url context

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

Example: If you need to pass parameters to a tag, use the tag to create the URL first as shown below: Tag Example

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

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

17

10MCA41

Topics in Enterprise Architecture - I

4th Semester

c: url The 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 param tag. Attribute: The tag has following attributes: Attribute value context var scope

Description

Required Base URL Yes / followed by the name of a local web application No Name of the variable to expose the processed URL No Scope of the variable to expose the processed URL No

Default None Current application Print to page Page

Example: Tag Example TEST

This would produce following result: TEST

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

18

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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:

Following is the list of Formatting JSTL Tags: Tag

Basavaraju R, Asst. Professor

Description To render numerical value with specific precision or format. Parses the string representation of a number, currency, or percentage. Formats a date and/or time using the supplied styles and pattern Parses the string representation of a date and/or time Loads a resource bundle to be used by its tag body. Stores the given locale in the locale configuration variable. Loads a resource bundle and stores it in the named scoped variable or the bundle configuration variable. Specifies the time zone for any time formatting or parsing actions nested in its body. Stores the given time zone in the time zone configuration variable To display an internationalized message. Sets the request character encoding

Dept. of MCA, RNSIT

19

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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:

Following is the list of SQL JSTL Tags: Tag

Basavaraju R, Asst. Professor

Description Creates a simple DataSource suitable only for prototyping Executes the SQL query defined in its body or through the sql attribute. Executes the SQL update defined in its body or through the sql attribute. Sets a parameter in an SQL statement to the specified value. Sets a parameter in an SQL statement to the specified java.util.Date value. Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.

Dept. of MCA, RNSIT

20

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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.

Following is the list of XML JSTL Tags: Tag

Basavaraju R, Asst. Professor

Description Like , but for XPath expressions. Use to parse XML data specified either via an attribute or in the tag body. Sets a variable to the value of an XPath expression. Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored. To loop over nodes in an XML document. Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by and Subtag of that includes its body if its expression evalutes to 'true' Subtag of that follows tags and runs only if all of the prior conditions evaluated to 'false' Applies an XSL transformation on a XML document Use along with the transform tag to set a parameter in the XSLT stylesheet

Dept. of MCA, RNSIT

21

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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 and you want to use it in the following fashion without a body:

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.

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

22

10MCA41

Topics in Enterprise Architecture - I

4th Semester

Create a following tag library file: custom.tld. 1.0 2.0 Example TLD rnsit CollegeTag empty

Now it's time to use above defined custom tag in our JSP program as follows: A sample custom tag

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 and you want to use it in the following fashion with a body: This is message body

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();

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

23

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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: 1.0 2.0 Example TLD with Body Hello HelloTag scriptless

Now let us call above tag with proper body as follows: A sample custom tag This is message body

This will produce following result: This is message body

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

24

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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;

Basavaraju R, Asst. Professor

Dept. of MCA, RNSIT

25

10MCA41

Topics in Enterprise Architecture - I

4th Semester

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
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF