Monday, March 30, 2015

Badges in Bootstrap


Badges are similar to labels in Bootstrap,badges are mostly used to focus unread objects. They can also be used in links, navs and more other by adding span class: badge. Please test the example for more clearance in it .

Example:



 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8"/>  
   <title>joeandy's workshop</title>  
   <meta name="viewport" content="width=device-width, initial-scale=1"/>  
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>  
 </head>  
 <body>  
 <div class="container">  
 <h4>Badges in active state pills </h4>  
 <ul class="nav nav-pills">  
   <li class="active"><a href="#">Home <span class="badge">42</span></a></li>  
   <li><a href="#">Profile</a></li>  
   <li><a href="#">Message <span class="badge">3</span></a></li>  
 </ul>  
 <br>  
 </div>  
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>  
 </body>  
 </html>  


Sunday, March 29, 2015

Using the affix plugin in Bootstrap and its detailed example

 Bootstrap Affix Plugin


 Bootstrap affix plugin  allows a <div> to become affixed to the location on a particular page in a particular section. It can be included with the help of affix.js or  bootstrap.js  while working in bootstrap. It is helpful working for toggle pin off and pin on using this plugin and it is mostly used to make <div> affixed to a particular section or location of a page.
  
Below here is a sample example I wrote it so you could check on the usage and implementation structure, I hope it's not a hard nut to crack. If you have any queries  please leave a comment in the comment box.

 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8"/>  
   <title>Nirajan Ghimirey's Workshop</title>  
   <meta name="viewport" content="width=device-width, initial-scale=1" />  
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />  
 </head>  
 <body>  
 <div class="container">  
 <header class="well text-center">  
 <h1>Welcome to My Blog.</h1>  
 <p class="text-success">This is the example of Affix Plug-in</p>  
 </header>  
 <div id="myNav" data-spy="affix" data-offset-top="60"  
    data-offset-bottom="200">  
    <div class="col-md-3">  
      <ul class="nav nav-tabs nav-stacked affix" data-spy="affix"  
       data-offset-top="190">  
       <li class="active"><a href="#one">Home</a></li>  
       <li><a href="#two">Labels</a></li>  
       <li><a href="#three">Directory</a></li>  
        <li><a href="#four">Articles</a></li>  
      </ul>  
    </div>  
    <div class="col-sm-9">  
      <h2 id="one">Home</h2>  
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.  
      Nam eu sem tempor, varius quam at, luctus dui. Mauris magna  
      metus, dapibus nec turpis vel, semper malesuada ante.  
      </p>  
      <p>Vestibulum quis quam ut magna consequat faucibus.  
      Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus  
      dictum risus. Pellentesque viverra sagittis quam at mattis.  
      Suspendisse potenti. Aliquam sit amet gravida nibh,  
      facilisis gravida odio. </p>  
      <hr>  
      <h2 id="two">Lables</h2>  
      <p> Nullam hendrerit justo non leo aliquet imperdiet. Etiam  
      in sagittis lectus. Suspendisse ultrices placerat accumsan.  
      Mauris quis dapibus orci. In dapibus velit blandit pharetra  
      tincidunt. </p>  
      <p>Vestibulum consectetur scelerisque lacus, ac fermentum  
      lorem convallis sed. Nam odio tortor, dictum quis malesuada at,  
      pellentesque vitae orci. </p>  
      <hr>  
      <h2 id="three">Directory</h2>  
      <p>Integer pulvinar leo id risus pellentesque vestibulum.  
      Sed diam libero, sodales eget sapien vel, porttitor bibendum  
      enim. Donec sed nibh vitae lorem porttitor blandit in nec ante.  
      Pellentesque vitae metus ipsum. Phasellus sed nunc ac sem  
      malesuada condimentum. Etiam in</p>  
      <p>Phasellus vitae suscipit justo. Mauris pharetra feugiat  
      ante id lacinia. Etiam faucibus mauris id tempor egestas. Duis  
      luctus turpis at accumsan tincidunt.</p>  
      <hr>  
      <h2 id="four">Articles</h2>  
      <p> Nullam hendrerit justo non leo aliquet imperdiet. Etiam  
      in sagittis lectus. Suspendisse ultrices placerat accumsan.  
      Mauris quis dapibus orci. In dapibus velit blandit pharetra  
      tincidunt. </p>  
      <p>Vestibulum consectetur scelerisque lacus, ac fermentum  
      lorem convallis sed. Nam odio tortor, dictum quis malesuada at,  
      pellentesque vitae orci. </p>  
    </div>  
   </div>  
 </div>  
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>  
 </body>  
 </html> 


Deserialization in JSON

JSON being a data exchange and interchange format, this was designed for running in JavaScript on websites. Serialization of JSON can be done in many of modern web programming and developing languages like PHP, ASP.NET, PERL, Python etc. JSONpickle is a python library for serialization and deserialization of complex python objects to and from JSON. Similarly ASP.NET, PHP etc. has their own libraries and methods for deserialization of data/objects  in JSON.

Below is a basic example that is simple enough to explain about deserialization of JSON using PHP as a root language.

PHP Script (deserialization.php)



 <?PHP  
 $json='{"Andy":1,"Joe":2,"James":3,"Niraj":4,"Kumar":5,"Katrina":6}';  
 echo "<pre>";  
 var_dump(json_decode($json));  
 var_dump(json_decode($json,true));  
 echo "</pre>";  
 ?>

JSON in PERL explained with example

Using JSON with PERL :


Dealing with JSON in Perl is more complex comparing to other as Perl being a type less language. However, JSON can be either encoded or decoded using PERL for this operation, JSON module must be installed first.JSON-2.53.tar.gz searching it would let you get a module for PERL of JSON. You will find JSON functions to operate with JSON data using PERL.

JSON Function:

Encode_json : It converts PERL structure which is given in to a UTF-8 encoded, binary string.
syntax:
$json_text = encode_json ($perl_scalar );
or
$json_text = JSON->new->utf8->encode($perl_scalar);


Example for encoding JSON in PERL:

Perl File (encode.pl)
#!/perl/bin/perl  
 print "Example of encode\n";  
 use JSON;  
 my %rec_hash = ('PHP' => 1, 'SEO' => 2, 'JS' => 3, 'JSON' => 4, 'Project' => 5);  
 my $json = encode_json \%rec_hash;  
 print "$json\n";  
 Decode_json : It decodes the JSON string.  
 syntax:  
 $perl_scalar=decode_json $json_text  
 or  
 $perl_scalar= JSON->new->utf8->decode($json_text)  

Example for decoding JSON in PERL:

Perl File (decode.pl)
 #!/perl/bin/perl  
 print "Example of decode\n";  
 use JSON;  
 use Data::Dumper;  
 $json = '{"JSON":1,"JavaScript":2,"SEO":3,"HTML":4,"CSS":5}';  
 $content = decode_json($json);  
 print Dumper($content); 



Saturday, March 28, 2015

Google webmaster and analytic for seo

Google Web Master For SEO

Google is one of the the leading company in internet and its search engine is used most widely around world. Google provides webmaster tools for generating site report and maintaining you site. 

Google webmaster facilities you with following feature:

  1. Site Dashboard:  This provides the summery of your site or page.
  2. Search Appearance: This helps by providing the summary about your website or web page search appearance. It also provides you the details of site links and the HTML improvement you should make on your site.
  3. Search Traffic: It provides you the traffic that visits you site in regular and the traffic that are searching relevant keywords.
  4. Google Index: It shows your links and pages and where they are ranked in Google index.
  5. Crawl: This provides you the information about crawling and how deep Google has dug your site and took the summary of links and documents.
  6. Security Issue: It provides you with issues that you might have or you are having with security features.
Using these listed features you can very well keep an eye in your website. Particularly this tool in Search Engine Optimization has revolutionized the Search Engine Optimization trends. Beside thee there are also various tools and tabs that you can find in webmaster tool provided by Google that helps you maintain and smooth function your web sites.

  1. This tools helps you be informed about Site health , from this section you can keep an eye on your website and its health, how well optimized is your site and what are the errors that are not being seen by you but crawlers are finding, etc. can be very well optimized
  2. This Optimization of Anchors can be made easy by checking all your hyperlinks and anchor tags using webmaster tool. The more optimized your anchors are the more friendly and genuine your website it.
  3. Sitemap Submission is a vital thing while you come in ground for Search Engine Optimization, if a site map is not submitted in Google Web Master tool you wont be provided by many information like queries that are made and redirected to your page/ websites, users organic searches and etc.
  4. Google Webmaster keeps you alert about errors you have in your site with details and probably thee errors are URL Structure , Site Navigation etc.
Now, as we all have known how precise and important and handy is Google Webmaster tool and its potentials that helps us optimizing our site and making them healthy . I would like to move forward to  next section 


Google Analytic

For the purpose of ease and proficient Search Engine Optimization there are lots of tools that can be found over internet, among them Google Analytic is  outrageous and outstanding. Being easy to use and user friendly any one who hung with this tool for about an hour can understand 67% of the functionality  and methods to use them.

 Google analytic provides you with following features:

  1. It provides you with Demographics
  2. It provides you with Audience Overview
  3. You can do Cohort Analysis
  4. It provides you the Real-Time from where you can view real time traffic to the site.
Beside them you are also facilitated with other tools that will certainly help you watch over your users visits, ages of the users, gender, traffic source, etc.

If you are into this optimization job and want to track and make it easy for yourself I personally along with almost 80% web masters would recommend you into these tools by Google that are so friendly and handy for even a starter to them. Not only its recommended but  Google is one of the the leading company in internet and its search engine is used most widely around world, so why follow others when you have Google.




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>