Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

Saturday, March 28, 2015

JSP web application dvelopment

Developing applications in JSP


Java Server Pages formally known as (JSP) is a great platform for developing web pages which support dynamic content that helps developers inserting java code in HTML pages by using genuine JSP tags, most of which start with <% and terminates with %>.

While developing application Java Server Page tags are used for a variety of purposes, they areas retrieving information from database or registering user preferences, accessing Java Beans components, passing control between pages and sharing information between requests, pages etc.

Java Server Pages (JSP)  has components as a category of Java Servlet which is designed to fulfill the role of a user interface for a Java web application. Web developers write JSP's as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Because of JSP, you can collect input data from users through web page forms, present records from a database or another source, and create web pages dynamically.


Why use JSP  in your application?


JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
Performance is obviously better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a different CGI files.

Key points for JSP use in your application :
  1. Java Server Pages are always compiled before it's processed by the server .
  2. Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
  3. Java Server Pages  can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
  4. Finally, Java Server Pages is an integral part of JavaEE, a complete platform for enterprise class applications. This means that Java Server Pages can play a part in the simplest applications to the most complex and demanding.


JSP File (index.jsp)

 <%  
  String theSharedObject = "JSP is cool";  
 application.setAttribute("message", theSharedObject);  
 %>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>Nirajan Ghimirey's Workshop</title>  
 </head>  
 <p>About Nirajan Ghimirey's Workshop</p>  
   Click <a href="application.jsp">here</a> to see this in action.  
 </body>  
 </html>  

JSP File (application.jsp)
 <%  
   // getAttribute() returns a java.lang.Object, so need to cast  
   String theSharedObject = (String) application.getAttribute("message");  
 %>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>Nirajan Ghimirey's Workshop</title>  
 </head>  
 <body>  
 <h2> This information from <i>application</i>object by another page.</h2>  
 <p>nirajanghimireyworkshop.blogspot.com is one of the best idea and a website which contains tutorials about web designing, web development, programming,and other skills.</p>  
 <p>  
       The message is <b><%= theSharedObject%></b>  
 </p>  
 </body>  
 </html>  


Server response in JSP

When a Web server responds to a HTTP request by the client browser, the response normally consists of a status line, some response headers, a blank line, and the document. A typical response looks like this :-

 HTTP/1.1 200 OK  
 Content-Type: text/html  
 Header2: ...  
 ...  
 HeaderN: ...  
  (Blank Line)  
 <!doctype ...>  
 <html>  
 <head>...</head>  
 <body>  
 ...  
 </body>  
 </html>  

Example:

JSP File (server-respone.jsp)
 <%@ page import="java.io.*,java.util.*" %>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>Nirajan Ghimirey's Workshop</title>  
 </head>  
 <body>  
 <center>  
 <h2>Example of server response </h2>  
 <%  
   // Set refresh, autoload time as 5 seconds  
 response.setIntHeader("Refresh", 5);  
   // Get current time  
   Calendar calendar = new GregorianCalendar();  
   String am_pm;  
 int hour = calendar.get(Calendar.HOUR);  
 int minute = calendar.get(Calendar.MINUTE);  
 int second = calendar.get(Calendar.SECOND);  
 if(calendar.get(Calendar.AM_PM) == 0)  
 am_pm = "AM";  
 else  
 am_pm = "PM";  
   String CT = hour+":"+ minute +":"+ second +" "+ am_pm;  
 out.println("Current Time is: " + CT + "\n");  
 %>  
 </center>  
 </body>  
 </html>  


A detail about client request in JSP

A brief in JSP client request 


When a browser from the client side requests for a web page, it send lots of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. Now this request are handled by important headers that is sent by our browser while sending the request.
Following are the important header information that comes from browser part .

Header
Description
Accept
This header says the MIME types that the browser or other clients can handle. Values of image/png or image/jpeg are the two most common possibilities.
Accept-Charset
This header says the character sets the browser can use to display the information. For example ISO-8859-1.
Accept-Encoding
This header talk about the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities.
Accept-Language
This header says the client's preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc.
Authorization
This header is used by clients to identify themselves when accessing password-protected Web pages.
Connection
This header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alivemeans that persistent connections should be used
Content-Length
This header is applicable only to POST requests and gives the size of the POST data in bytes.
Cookie
This header returns cookies to servers that previously sent them to the browser.
Host
This header specifies the host and port as given in the original URL.
If-Modified-Since
This header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available.
If-Unmodified-Since
This header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date.
Referer
This header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referer header when the browser requests Web page 2.
User-Agent
This header find out the browser or other client making the request and can be used to return different content to different types of browsers

Example:

JSP File (client-request.jsp)
 <%@ page import="java.io.*,java.util.*" %>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h2>HTTP Header Request Example</h2>  
 <table width="100%" border="1" align="center">  
 <trbgcolor="lightsalmon">  
 <th>Header Name</th><th>Header Value(s)</th>  
 </tr>  
 <%  
   Enumeration headerNames = request.getHeaderNames();  
 while(headerNames.hasMoreElements()) {  
    String paramName = (String)headerNames.nextElement();  
 out.print("<tr><td>" + paramName + "</td>\n");  
    String paramValue = request.getHeader(paramName);  
 out.println("<td> " + paramValue + "</td></tr>\n");  
   }  
 %>  
 </table>  
 </center>  
 </body>  
 </html>  


Friday, March 27, 2015

import and its brief in JSP

The <jsp:include> tag provides you facility to import content onto one of your JSP, but the content needs to reside within your web application. The import directive is used at compilation time and its concept is similar to the Java import class directive. The collection of multiple classes together organized in a hierarchy is referred to as a package.

Example:

JSP File (import.jsp)

 <%@ page import="java.io.*" %>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 <meta charset="UTF-8"/>  
 </head>  
 <body>  
 <h1>JSP import</h1>  
     Click to open/download file  
 <%  
       String file = application.getRealPath("/");  
       File f = new File(file);  
       String [] fileNames = f.list();  
       File [] fileObjects= f.listFiles();  
     %>  
 <ul>  
 <%  
 for (int i = 0; i <fileObjects.length; i++) {  
 if(!fileObjects[i].isDirectory()){  
     %>  
 <li>  
 <a href="<%= fileNames[i] %>"><%= fileNames[i] %></a>  
 &nbsp;&nbsp;&nbsp;&nbsp;  
      (<%= Long.toString(fileObjects[i].length()) %> bytes long)  
 <%  
         }  
       }  
     %>  
 </ul>  
 </body>  
 </html>  

Sending emails in JSP

Simple explained example for sending email via JSP

As like in PHP and other languages emails  too can be sent through JSP . For sending email  in JSP you must have JavaMail API and Java Activation Framework (JAF) installed in your machine. Now when you have installed these framework I have an example below that could be useful for you to send email from JSP.

First create an HTML Document ,
HTML Document (index.html)
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="utf-8" />  
 <title>Nirajanghimireyworkshop.blogspot.com- Sending Mail</title>  
 </head>  
 <body>  
 <form action="link.jsp" method="post">  
 <table cellspacing="2" cellpadding="2" border="1">  
 <tr>  
 <td>To:</td>  
 <td>  
 <input type="text" name="to" size="30" maxlength="30">  
 </td>  
 </tr>  
 <tr>  
 <td>From:</td>  
 <td>  
 <input type="text" name="from" size="30" maxlength="30">  
 </td>  
 </tr>  
 <tr>  
 <td>Subject</td>  
 <td>  
 <input type="text" name="subject" size="30" maxlength="30">  
 </td>  
 </tr>  
 <tr>  
 <td colspan="2">  
 <textarea cols="40" rows="10" name="body"></textarea>  
 </td>  
 </tr>  
 <tr>  
 <td>  
 <input type="submit" name="submit" value="Submit">  
 <input type="Reset">  
 </td>  
 </tr>  
 </table>  
 </form>  
 </body>  
 </html>  




The above file is skeleton for interface to send email using JSP main fnctions and workings are done throught the below file.

JSP File (link.jsp)
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="utf-8" />  
 <title>Nirajanghimireyworkshop.blogspot.com-JSP Mail Sending</title>  
 </head>  
 <body>  
 <%@ page import="java.util.*" %>  
 <%@ page import="javax.mail.*" %>  
 <%@ page import="javax.mail.internet.*" %>  
 <%@ page import="javax.activation.*" %>  
 <%  
   String host = "localhost";  
   String to = request.getParameter("to");  
   String from = request.getParameter("from");  
   String subject = request.getParameter("subject");  
   String messageText = request.getParameter("body");  
 booleansessionDebug = false;  
   Properties props = System.getProperties();  
 props.put("mail.host", host);  
 props.put("mail.transport.protocol", "smtp");  
   Session mailSession = Session.getDefaultInstance(props, null);  
 mailSession.setDebug(sessionDebug);  
   Message msg = new MimeMessage(mailSession);  
 msg.setFrom(new InternetAddress(from));  
 InternetAddress[] address = {new InternetAddress(to)};  
 msg.setRecipients(Message.RecipientType.TO, address);  
 msg.setSubject(subject);  
 msg.setSentDate(new Date());  
 msg.setText(messageText);  
 Transport.send(msg);  
 out.println("Mail was sent to " + to);  
 out.println(" from " + from);  
 out.println(" using host " + host + ".");  
   %>  
 </body>  
 </html>  

Data handling in JSP explained with example

What is JSP Date Handling ?

In this tutorial I have tried to explain a certain criteria on JSP data handling, no doubt this tutorial would take you through Java provided Date class which is available in java.util package, this class encapsulates the current date and time. The Date class supports two constructors. The first constructor initializes the object with the current date and time.

Example:

JSP File (date.jsp)

 <%@ page import="java.io.*,java.util.*" %>  
 <%@ page import="javax.servlet.*,java.text.*" %>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>Nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h1>Example for handling date and time </h1>  
 <h3>Current date and time: </h3>  
 <%  
   Date date = new Date();  
 out.print(date.toString());  
 %>  
 <h2> Formatting date </h2>  
 <h3>Current date and time: </h3>  
 <%  
   Date dNow = new Date( );  
 SimpleDateFormatft =  
 newSimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");  
 out.print(ft.format(dNow));  
 %>  
 </center>  
 </body>  
 </html>  

example for cookies in JSP

Brief about cookies in JSP

Cookies are text files stored in client computer and are used for tracking information and authentication purpose, JSP transparently supports HTTP cookies sing underlying servlet technology. 

This process includes following stuffs :

  1. Server sends a set of cookies to the client browser.
  2. Client browser stores and prompt to save or not.
  3. Next time when the client visits the same address the cookies are used to get the information of the user last saved.


Setting Cookies in JSP

Example:


JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <h2> Nirajan Ghimirey's Workshop Login Form </h2>  
 <form action="setcookie.jsp" method="POST">  
 <label>Name</label><input type="text" name="full_name">  
 <br />  
 <label>Email: </label><input type="text" name="email" /><br/>  
 <input type="submit" value="Submit" />  
 </form>  
 </body>  
 </html>  

Use below script to set cookie in JSP project.

JSP File (setcookie.jsp)
 <%  
   // Create cookies for name and email.     
   Cookie fullname = new Cookie("full_name",  
 request.getParameter("full_name"));  
   Cookie email = new Cookie("email",  
 request.getParameter("email"));  
   // Set expiry date after 24 Hrs for both the cookies.  
 fullname.setMaxAge(60 * 60 * 24);  
 email.setMaxAge(60 * 60 * 24);  
   // Add both the cookies in the response header.  
 response.addCookie(fullname);  
 response.addCookie(email);  
 %>  
 <html>  
 <head>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h1>Setting Cookies Example</h1>  
 </center>  
 <p><b>Full Name: </b>  
 <%= request.getParameter("full_name")%>  
 </p><p><b>Email: </b>  
 <%= request.getParameter("email")%>  
 </p>  
 </body>  
 </html>  


Process for reading cookies in JSP.

Reading Cookies

Example:
<!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h1>Reading Cookies</h1>  
 </center>  
 <%  
   Cookie cookie = null;  
 Cookie[] cookies = null;  
   // Get an array of Cookies associated with this domain  
 cookies = request.getCookies();  
 if( cookies != null ){  
 out.println("<h2>Cookies Name and Value</h2>");  
 for (int i = 0; i <cookies.length; i++){  
 cookie = cookies[i];  
 out.print("Name : " + cookie.getName( ) + ", ");  
 out.print("Value: " + cookie.getValue( )+" <br/>");  
    }  
 }else{  
 out.println("<h2>No cookies founds</h2>");  
  }  
 %>  
 </body>  
 </html> 

JSP File (index.jsp)

<!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h1>Reading Cookies</h1>  
 </center>  
 <%  
   Cookie cookie = null;  
 Cookie[] cookies = null;  
   // Get an array of Cookies associated with this domain  
 cookies = request.getCookies();  
 if( cookies != null ){  
 out.println("<h2>Cookies Name and Value</h2>");  
 for (int i = 0; i <cookies.length; i++){  
 cookie = cookies[i];  
 out.print("Name : " + cookie.getName( ) + ", ");  
 out.print("Value: " + cookie.getValue( )+" <br/>");  
    }  
 }else{  
 out.println("<h2>No cookies founds</h2>");  
  }  
 %>  
 </body>  
 </html> 

Script for deleting cookie in JSP.

Delete Cookies

Example:

JSP File (index.jsp)

<!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h1>Reading Cookies</h1>  
 </center>  
 <%  
   Cookie cookie = null;  
 Cookie[] cookies = null;  
   // Get an array of Cookies associated with this domain  
 cookies = request.getCookies();  
 if( cookies != null ){  
 out.println("<h2> Cookies Name and Value</h2>");  
 for (int i = 0; i <cookies.length; i++){  
 cookie = cookies[i];  
 if((cookie.getName( )).compareTo("full_name") == 0 ){  
 cookie.setMaxAge(0);  
 response.addCookie(cookie);  
 out.print("<b>Deleted cookie: </b> " +  
 cookie.getName( ) + "<br/>");  
      }  
 out.print("Name : " + cookie.getName( ) + ", ");  
 out.print("Value: " + cookie.getValue( )+" <br/>");  
    }  
 }else{  
 out.println(  
    "<h2>No cookies founds</h2>");  
  }  
 %>  
 </body>  
 </html>  


Working with sessions in JSP

Session in JSP

JSP has HttpServlet interface that helps to identify user and store their session credentials . There are many methods for using session object that can be used in JSP.

S.N.
Methods & Description
1
public Object getAttribute(String name)
This method returns the object bound with the specified name in this session, or null if no object is bound under the name.
2
public Enumeration getAttributeNames()
This method returns an Enumeration of String objects containing the names of all the objects bound to this session.
3
public long getCreationTime()
This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
4
public String getId()
This method returns a string containing the unique identifier assigned to this session.
5
public long getLastAccessedTime()
This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
6
publicintgetMaxInactiveInterval()
This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
7
public void invalidate()
This method invalidates this session and unbinds any objects bound to it.
8
publicbooleanisNew()
This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
9
public void removeAttribute(String name)
This method removes the object bound with the specified name from this session.
10
public void setAttribute(String name, Object value) 
This method binds an object to this session, using the name specified.
11
public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Example:

JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <form action="process.jsp">  
 <input type="text" name="uname" placeholder="Enter Your Name">  
 <input type="submit" value="go"><br/>  
 </form>  
 </body>  
 </html>

JSP File (process.jsp)

<!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <%   
 String name=request.getParameter("uname");  
 out.println("<h3>You have Enter on nirajanghimireyworkshop.blogspot.com</h3>");  
 out.print("Welcome "+name);   
 session.setAttribute("user",name);  
  %>  
 <br/>  
 <a href="data.jsp">Next Page</a>  
 </body>  
 </html>

JSP File (data.jsp)

<!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <%   
 String name=(String)session.getAttribute("user");   
 out.print("Hello "+ "<b>"+name + "</b>" +"<br/>");   
 out.println ("You can learn HTML, CSS, JSP, etc.");  
 %>  
 </body>  
 </html> 

include function in JSP

Include Function in JSP :

As like in other programming JSP also has include function in it ,the include directive is mostly  used to includes a file during the translation phase. This directive says the container to merge the content of other external files with the current JSP during the translation phase. Include directives can be coded  anywhere in your JSP page

Example:

JSP File (header.jsp)

<%!  
 intpageCount = 0;  
 voidaddCount() {  
 pageCount++;  
  }  
 %>  
 <% addCount(); %>  
 <html>  
 <head>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h3>This the header part</h3>  
 <p>You have visited this site <%= pageCount %> times.</p>  
 </center>  
 <br/><br/>  

JSP File (footer.jsp)

<br/><br/>  
 <center>  
 <h3>This is footer part</h3>  
 </center>  
 </body>  
 </html>  

JSP File (index.jsp)

  <%@ include file="header.jsp" %>  
 <center>  
 <h3>This is body part</h3>  
 <p>nirajanghimireyworkshop.blogspot.com</p>  
 </center>  
 <%@ include file="footer.jsp" %>  

form processing in jsp with get and post examples

Using JSP form processing can be one, using some basic HTTP functions, Get Method, Post Method, beside them it also uses some simple processing logics and elements served in JSP.

GET method:
Example:

JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <h2>Login form </h2>  
 <div>  
 <form action="get.jsp" method="GET">  
         Name <input type="text" name="full_name">  
 <br />  
         Email: <input type="text" name="email" /><br/>  
         Password: <input type="password" name="password" /><br/>  
 <input type="submit" value="Submit" />  
 </form>  
 </div>  
 </body>  
 </html>  

JSP File (get.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h1>Welcome to Nirajan Ghimirey's Workshop </h1>  
 <p><b>Your Name:</b>  
 <%= request.getParameter("full_name")%>  
 </p>  
 <p><b>Your Email</b>  
 <%= request.getParameter("email")%>  
 </p>  
 <p><b>Your Password</b>  
 <%= request.getParameter("password")%>  
 </p>  
 </body>  
 </html>  

Below here is an example for post method, this example uses post method for user log in.

POST Method:

JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <h2> Login form </h2>  
 <div>  
 <form action="get.jsp" method="POST">  
         Name <input type="text" name="full_name">  
 <br /><br />  
         Email: <input type="text" name="email" /><br/><br />  
         Password: <input type="password" name="password" /><br/>  
 <input type="submit" value="Submit" />  
 </form>  
 </div>  
 </body>  
 </html> 

JSP File (post.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h1>Welcome to Nirajan Ghimirey Workshop </h1>  
 <p><b>Your Name:</b>  
 <%= request.getParameter("full_name")%>  
 </p>  
 <p><b>Your Email</b>  
 <%= request.getParameter("email")%>  
 </p>  
 <p><b>Your Password</b>  
 <%= request.getParameter("password")%>  
 </p>  
 </body>  
 </html> 

exceptions and example for exception in JSP

There are certain errors that you have in JSP and they are:

  1. Checked Exceptions: This exceptions are typically known as a user error problem which a programmer cannot see or which cannot be foreseen by the programmer. Ex: a file that is need to be opened by a program but the file is not found .
  2. Run-time Exception: It is a exception that occurs when some error are  avoided by a programmer.
  3. Errors: These are not exception but are clearly errors that might arise apart form user or programmer limit.


Example:

JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
   <head>  
     <title>nirajanghimireyworkshop.blogspot.com</title>  
   </head>  
   <body>  
     <%  
       try {  
         int num = 1;  
         num = num / 0;  
         out.println("The answer is " + num);  
       } catch (Exception e) {  
         out.println("An exception occurred: " + e.getMessage());  
       }  
     %>  
   </body>  
 </html> 

Directives in JSP

Brief about Directives in JSP:

Directives are direction providers which also provides instructions to the container and help finding files and methods and etc. They tell how to handle a particular request and JSP processing.There are three directives and they are:


The page Directive: This directives are used to provide information to container which belongs to the present JSP page , page Directive might be coded anywhere in the page.The attributes for page directive are:


Attribute
Purpose
buffer
This specifies a buffering model for the output stream.
autoFlush
It controls the behavior of the servlet output buffer.
contentType
This defines the character encoding scheme.
errorPage
This defines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPage
It indicates if this JSP page is a URL specified by another JSP page's errorPage attribute.
extends
This specifies a superclass that the generated servlet must extend
import
This specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.
info
This defines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafe
This defines the threading model for the generated servlet.
language
This defines the programming language used in the JSP page.
session
This specifies whether or not the JSP page participates in HTTP sessions
isELIgnored
This specifies whether or not EL expression within the JSP page will be ignored.
isScriptingEnabled
It determines if scripting elements are allowed for use.


The include Directive:  These Directives are used to include files during translation phase.


The taglib Directive : The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.


JSP data types and it's example

Data types in JSP are listed below with brief in them:
  1. Byte: This is an 8-bit signed teo’s compliment integer. It has minimum value of -128 and maximum value of 127.
  2. Short:  This data types  are 16-bit signed two’s compliment integer. It has a minimum value of -32,768 and maximum value of 32,767.
  3. Int: it is 32-bit signed two’s compliment integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647.
  4. Long: This data types are 64-bit signed two’s compliment integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807.
  5. Float: It is single-precision 32-bit IEEE 754 floating point. Its ange of values is beyond the scope.
  6. Double: it is double-precision 64-bit IEEE 754 floating point, Its range of value is beyond the scope.
  7. Boolean: it has only two possible values either a true or a false.
  8. Char: it is 16-bit Unicode character. It has minimum value of '\u0000' (or 0) and maximum value of '\uffff' i.e. 65,535.


Example:
JSP File (datatype.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 <meta charset="UTF-8">  
 </head>  
 <body>  
 <h2>Example of Data Types in JSP</h2>  
 <%  
 int a;  
 float b;  
 doublec,d;  
     a=10;b=30; c=b;d=a+c;  
 out.println("c = "+ c +"<br/>");  
 out.println("d = " + (int)d);  
    %>  
 </body>  
 </html>

Continue in JSP

Continue statement in JSP ? 

In JSP continue  is a statement and this statement is used to carry on loops or to exit from a switch . It can be used within a for, while, do –while etc.

Example:

JSP File (continue.jsp)
 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>nirajanghimireyworkshop.blogspot.com</title>  
 <meta charset="UTF-8"/>  
 </head>  
 <body>  
 <h2>Continue Statement in JSP</h2>  
 <%  
 int i;  
 for (i= 0;i< 20;i++) {  
 if(i==5){  
 out.println("continue <br/>");  
 continue;  
       }  
 out.println("X = " + i+ "<br/>");  
    }  
   %>  
 </body>  
 </html> 

class in JSP

A brief about class in JSP

Class can be refereed as a blueprint from which individual objects are created in Java. Class contains any of variable types  and  methods which are members of the class. It can contain any number of methods for accessing the values of various kinds of methods.

  1. Local Variables :  These are variables defined inside methods, construct or blocks are called local variables. These variables will be declared and initialized within the method and the variables will be destroyed when the methods has completed.
  2. Instance variables: Instance variables are those variables  which are within a class but outside any methods. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  3. Class variables: These variables are variables declared with in a class, outside any method, with the static keyword.


Example:
JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
   <head>  
     <title>nirajanghimireyworkshop.blogspot.com</title>  
   </head>  
   <body>  
     <%!  
       javax.servlet.jsp.JspWriter localOut;  
       class BaseClass  
       {  
         public void start() throws java.io.IOException  
         {  
           localOut.println("Starting...<br/>");  
         }  
       }  
       class DerivedClass extends BaseClass  
       {  
         public void drive() throws java.io.IOException  
         {  
           localOut.println("Deriving...<br/>");  
         }  
       }  
     %>    
     <%  
       localOut = out;    
       out.println("Example of Classes <br/>");  
       DerivedClass a = new DerivedClass();  
       a.start();  
       a.drive();  
     %>  
   </body>  
 </html> 

Break statement in JSP

JSP Break Statement:

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Example:

JSP File (break.jsp)

 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>Nirajanghimireyworkshop.blogspot.com</title>  
 <meta charset="UTF-8"/>  
 </head>  
 <body>  
 <h2>this is an example of break</h2>  
 <%  
     int x = 1;  
     while (x>0) {  
       if(x==5){  
         out.println("Example of break");  
       break;  
       }  
       out.println("X = " + x + "<br/>");  
       x++;  
     }  
   %>  
 </body>  
 </html>  

Array in JSP

A brief in JSP Array !

JSP does not have array structure as JSP is not a complete programming language. JSP doesn't have array structure but array are declared using Java can be used in JSP. In JSP arrays are used to storeseveral data types in a series that can be string,int,dynamic data, vector etc.

Single Dimension Array:

Single dimensional array is a list of variables of same type that are accessed by a common name. An individual variable in the array is called an array element. Arrays forms a way to handle groups of related data. 

JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
   <head>  
     <title>nirajanghimireyworkshop.blogspot.com</title>  
   </head>  
   <body>  
     <%  
       double arr[];  
       arr = new double[100];  
       arr[5] = 4.5;  
       out.println("Array index [3] holds " + arr[5]);  
     %>  
   </body>  
 </html>  
Multi Dimensional Array:

In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences. 

JSP File (index.jsp)

 <!DOCTYPE html>  
 <html>  
   <head>  
     <title>nirajanghimireyworkshop.blogspot.com</title>  
   </head>  
   <body>  
     <%  
       double arr[][] = new double[2][10];  
       arr[0][1] = 19.3;  
       arr[1][2] = 45.02;  
       out.println("Array index [0][1] holds " + arr[0][1] + "<br/>");  
       out.println("Array index [1][2] holds " + arr[1][2]);  
     %>  
   </body>  
 </html> 

What is JSP action ?

JSP Action :

To talk on JSP action , it can be defined as components that  are used to  construct XML syntax to control the behavior of the servlet engine. These components can be used for dynamically inserting of a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.

The syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />

Action elements are predefined functions and there are following JSP actions available in JSP:

Syntax
Purpose
jsp:include
It includes a file at the time the page is requested
jsp:useBean
It finds or instantiates a JavaBean
jsp:setProperty
This sets the property of a JavaBean
jsp:getProperty
This inserts the property of a JavaBean into the output
jsp:forward
This forwards the requester to a new page
jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:element
It defines XML elements dynamically.
jsp:attribute
This defines dynamically defined XML element's attribute.
jsp:body
Defines dynamically defined XML element's body.
jsp:text
Use to write template text in JSP pages and documents.

Common Attributes:

There are two common attributes that are used for all Action elements: the id attribute and the scope attribute.

  1. Id attribute: This attribute uniquely identifies the Action element, and it allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext.
  2. Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b) request, (c)session, and (d) application.


Example:

JSP File (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>Nirajanghimirey.blogspot.com</title>  
 </head>  
 <body>  
 <center>  
 <h2>This is the example of action.</h2>  
 <jsp:include page="link.jsp" flush="true" />  
 </center>  
 </body>  
 </html> 

JSP File (link.jsp)

<p>Current Time: <%= (new java.util.Date()).toLocaleString()%></p>