JSP Java Server Pages -By Yogita Nirmal.

1 JSP Java Server Pages -By Yogita Nirmal ...
Author: Isaac Patrick
0 downloads 3 Views

1 JSP Java Server Pages -By Yogita Nirmal

2 A JSP page consists of HTML tags and JSP tags.JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to servlet because it provides more functionality than servlet such as expression language, jstl etc. A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tag etc.

3 Advantages of JSP over ServletExtension to Servlet JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy. 2) Easy to maintain JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic. 3) Fast Development: No need to recompile and redeploy If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application. 4) Less code than Servlet In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc.

4 Life Cycle OF JSP

5 <%@ directive attribute="value" %>JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form: Directives can have a number of attributes which you can list down as key-value pairs and separated by commas. The blanks between symbol and the directive name, and between the last attribute and the closing %>, are optional. directive attribute="value" %>

6 Directive DescriptionThere are three types of directive tag: Directive Description page ... %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements 2. include ... %> Includes a file during the translation phase. 3. taglib ... %> Declares a tag library, containing custom actions, used in the page

7 Attributes of Page Directivesimport contentType extends info buffer language isELIgnored isThreadSafe autoFlush session pageEncoding errorPage isErrorPage

8 2)import The import attribute is used to import class,interface or all the members of a package.It is similar to import keyword in java class or interface.Example of import attribute          Today is: <%= new Date() %>        

9 2)contentType The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.The default value is "text/html;” Example of contentType attribute          Today is: <%= new java.util.Date() %>        

10 3)Extends The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely used. 4)Info This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo() method of Servlet interface.

11 Example of info attribute         Today is: <%= new java.util.Date() %>         The web container will create a method getServletInfo() in the resulting servlet.For example: public String getServletInfo() {     return "composed by Sonoo Jaiswal";    }  

12 5)Buffer The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The default size of the buffer is 8Kb. Example of buffer attribute          Today is: <%= new java.util.Date() %>     

13 6)Language 7)isELIgnoredThe language attribute specifies the scripting language used in the JSP page. The default value is "java". 7)isELIgnored We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e. Expression Language is enabled by default. We see Expression Language later.

14 9)errorPage Example of errorPage attribute //index.jsp The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be redirected to the error page. Example of errorPage attribute //index.jsp             <%= 100/0 %>        

15 10)isErrorPage The isErrorPage attribute is used to declare that the current page is the error page. Note: The exception object can only be used in the error page. Example of isErrorPage attribute //myerrorpage.jsp             Sorry an exception occured!
  
The exception is: <%= exception %>        

16 --END--

17 JSP State Management

18 HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. Still there are following three ways to maintain session between web client and web server:

19 Hidden Form Fields: A web server can send a hidden HTML form field along with a unique session ID as follows: This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers. This could be an effective way of keeping track of the session but clicking on a regular () hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.

20 URL Rewriting: You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. For example, with the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client. URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.

21 Cookies: A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.

22 <%@ page session="false" %>The session Object: JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows: page session="false" %> The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession().

23

24

25 Session Tracking Example:page import="java.io.*,java.util.*" %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD");

26 // Check if this is new comer on your web page.if (session.isNew()) { title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); %>

27 Session Tracking

Session Tracking

28

Session info Value
id <% out.print( session.getId()); %> Creation Time <% out.print(createTime); %>
Time of Last Access <% out.print(lastAccessTime); %>
User ID <% out.print(userID); %> Number of visits <% out.print(visitCount); %>

29 Deleting Session Data:When you are done with a user's session data, you have several options: Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Delete the whole session: You can call public void invalidate() method to discard an entire session. Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes

30 --END--

31 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 To create a custom tag we need three things: 1) Tag handler class: In this class we specify what our custom tag will do when it is used in a JSP page. 2) TLD file: Tag descriptor file where we will specify our tag name, tag handler class and tag attributes. 3) JSP page: A JSP page where we will be using our custom tag. Example: In the below example we are creating a custom tag MyMsg which will display the message “This is my own custom tag” when used in a JSP page. Tag handler class: A tag handler class should implement Tag/IterationTag/ BodyTag interface or it can also extend TagSupport/BodyTagSupport/SimpleTagSupport class. All the classes that support custom tags are present inside javax.servlet.jsp.tagext. 

32 package pack1; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class Details extends SimpleTagSupport { public void doTag() throws JspException, IOException /*This is just to display a message, when * we will use our custom tag. This message * would be displayed */ JspWriter out = getJspContext().getOut(); out.println("This is my own custom tag"); }

33 TLD File This file should present at the location: Project Name/WebContent/WEB-INF/and it should have a .tld extension.  tag: custom tag name. In this example we have given it as MyMsg  tag: Fully qualified class name. Our tag handler class Details.java is in package pack1 so we have given the value pack1.Details. message.tld 1.0 2.0 My Custom Tag MyMsg pack1.Details empty

34 Above we have created a custom tag named MyMsgAbove we have created a custom tag named MyMsg. Here we will be using it. Note: taglib directive should have the TLD file path in uri field. Above we have created the message.tld file so we have given the path of that file. Choose any prefix and specify it in taglib directive’s prefix field. Here we have specified it as myprefix. Custom tag is called like this: . Our prefix is myprefix and tag name is MyMsg so we have called it as  in the below JSP page. taglib prefix="myprefix" uri="WEB-INF/message.tld"%> Custom Tags in JSP Example

35 Above we have created a custom tag named MyMsgAbove we have created a custom tag named MyMsg. Here we will be using it. Note: taglib directive should have the TLD file path in uri field. Above we have created the message.tld file so we have given the path of that file. Choose any prefix and specify it in taglib directive’s prefix field. Here we have specified it as myprefix. Custom tag is called like this: . Our prefix is myprefix and tag name is MyMsg so we have called it as  in the below JSP page. taglib prefix="myprefix" uri="WEB-INF/message.tld"%> Custom Tags in JSP Example

36 --END--

37 Exception Handling by using elements of Page DirectiveChecked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Exception Handling by using elements of Page Directive In JSP, there are two ways to perform exception handling: By errorPage and isErrorPage attributes of page directive By  element in web.xml file

38 There are 3 files: index.jsp for input values process.jsp for dividing the two numbers and displaying the result error.jsp for handling the exception index.jsp    No1: No1:      process.jsp <%      String num1=request.getParameter("n1");   String num2=request.getParameter("n2");   int a=Integer.parseInt(num1);   int b=Integer.parseInt(num2);   int c=a/b;   out.print("division of numbers is: "+c);   %>  

39 Exception Handling by Specifying the error-page element in web.xmlerror.jsp   

Sorry an exception occured!

   Exception is: <%= exception %>   Exception Handling by Specifying the error-page element in web.xml This approach is better because you don't need to specify the errorPage attribute in each jsp page. Specifying the single entry in the web.xml file will handle the exception. In this case, either specify exception-type or error-code with the location element. If you want to handle all the exception, you will have to specify the java.lang.Exception in the exception-type element. There are 4 files: web.xml file for specifying the error-page element index.jsp for input values process.jsp for dividing the two numbers and displaying the result error.jsp for displaying the exception

40 Web.xml java.lang.Exception /error.jsp

41 --END--

42 JSP STANDARD TAG LIBRARYJSTL JSP STANDARD TAG LIBRARY The JavaServer 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 JSTL allows you to program your JSP pages using tags, rather than the scriptlet code that most JSP programmers used to. JSTL can do nearly everything that regular JSP scriptlet code can do.  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" %>

43 There are following Core JSTL Tags: Tag DescriptionLike <%=..>,but for expressions. Sets the result of an expression evaluation in a 'scope' Removes a scoped variable (from a particular scope, if specified). Catches any Throwable that occurs in its body and optionally exposes it. Simple conditional tag which evalutes its body if the supplied condition is true. Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by and Subtag of that includes its body if its condition evalutes to 'true'. Subtag of that follows tags and runs only if all of the prior conditions evaluated to 'false'. The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality .

44 Program 1: There are following Core JSTL Tags: Redirects to a new URL.prefix="ab" uri="http://java.sun.com/jsp/jstl/core" %

JSTL

No = No = Tag Description Redirects to a new URL.

45 Program 2 prefix="ab" uri="http://java.sun.com/jsp/jstl/core" %

Enter Your Name


46 Program 3 prefix="ab" uri="http://java.sun.com/jsp/jstl/core" %

Enter No and check whether it is even or odd


Enter No

47 Program 4 prefix="ab" uri="http://java.sun.com/jsp/jstl/core" %>

For loop

Enter No



48 Program 5 prefix="ab" uri="http://java.sun.com/jsp/jstl/core" %

Program to demonstrate the use of choose in jstl

1.Facebook 2.Twitter 3.Google
Enter your choice

49 Program 5 continues…

50 Program 6 prefix="ab" uri="http://java.sun.com/jsp/jstl/core" %> <%int x=100/0;%>

51 Program 7 uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> uri="http://java.sun.com/jsp/jstl/sql" prefix="s" %>

52 Program 7 continues..

BookID
Name Author
Price

53 Program 7 continues.. sql="insert into book values('${a}','${b}','${c}','${d}')">

54 Program 7 continues.. sql="update book set bname='${b}',author='${c}',price='${d}' where bookid='${a}'"> sql="delete from book where bookid='${a}'"> out.println(""); { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://slideplayer.com/12243693/72/images/54/Program+7+continues..+%3Cc%3Aif+test%3D+%24%7Bparam.b2%21%3Dnull%7D+%3E+%3Cs%3Aupdate+dataSource%3D+%24%7Bdb%7D.jpg", "name": "Program 7 continues.. sql= delete from book where bookid= ${a} > out.println(