Tuesday, February 20, 2018

JSP Exception handling

In this post you will learn how to handle errors from within the same page.The JSP page can use try and catch blocks to capture the exception so that it can take appropriate action that is based on the exception type.Before going through exception handling in JSP, let’s understand what is exception and how it is different from errors.

Exception:
These are nothing but the abnormal conditions which interrupts the normal flow of execution. Mostly they occur because of the wrong data entered by user. It is must to handle exceptions in order to give meaningful message to the user so that user would be able to understand the issue and take appropriate action.

Error:

It can be a issue with the code or a system related issue. We should not handle errors as they are meant to be fixed.

Fortunately, JSP has an elegant solution for error handling built in. Many developers never
take advantage of this feature and continue to code each exception handler individually. With
JSP, you can create a single page that will handle every uncaught exception in your system. If
your JSP code throws an exception not handled within a try-catch block, it'll forward the
exception, and control, to a page you specify using a JSP page directive.

There are 2 ways to perform exception handling in jsp:

1. Using isErrorPage and errorPage attribute of page directive.using iserror
2. using standard try..catch block

create an error page:

an error page should take an exception, report it to a system
administrator, and display a meaningful message to the user. The first thing you need to do,
however, is declare that the page to be used is an error page. You do this using the isErrorPage

page directive as follows:

<%@ page isErrorPage="true" %>

If any exception occurs in the main JSP page the control will be transferred to the page mentioned in errorPage attribute.

The handler page should have isErrorPage set to true in order to use exception implicit object. That’s the reason we have set the isErrorPage true for showerror.jsp.

index.jsp:

<%@ page errorPage="showerror.jsp" %>
<html>
<head>
  <title>exception handling in jsp</title>
</head>
<body>
<%
     //Declared and initialized two integers
     int x = 45;
     int y = 0;

     //It should throw Arithmetic Exception
     int div = x/y;
%>
</body>
</html>

showerror.jsp:

<%@ page isErrorPage="true" %>
<html>
<head>
  <title>Display the Exception Message here</title>
</head>
<body>
   <h2>showerror.jsp</h2>
   <i>An exception has occurred in the index.jsp Page.
   Please fix the errors. Below is the error message:</i>
   <b><%= exception %></b>
</body>
</html>

Output:

 


 
2. Using try..catch block just like we used in core java

<html>
<head>
   <title>using try..catch </title>
</head>
<body>
  <%
   try{
      int i = 111;
      i = i / 0;
      out.println("The answer is " + i);
   }
   catch (Exception e){
      out.println("An exception occurred: " + e.getMessage());
   }
  %>
</body>
</html>

Output:
An exception occurred: java.lang.ArithmeticException:/byzero

Saturday, February 17, 2018

Advantages of Cloud Computing

In this post you will learn advantages of Cloud Computing.Cloud computing is on demand delivery of IT resources(Hardware,software and Applications)through the internet.Suppose we want to start an IT company,so as a part of the infrastructure,we would require various software and hardware like servers,hard disks,routers etc. Not all business can afford high cost IT infrastructure.Here cloud computing comes into the picture.

The goal of cloud computing is to allow users to take benefit from all of these technologies, without the need for deep knowledge about or expertise with each one of them. The cloud aims to cut costs, and helps the users focus on their core business instead of being impeded by IT obstacles.The main enabling technology for cloud computing is virtualization. Virtualization software separates a physical computing device into one or more "virtual" devices, each of which can be easily used and managed to perform computing tasks. With operating system–level virtualization essentially creating a scalable system of multiple independent computing devices, idle computing resources can be allocated and used more efficiently. Virtualization provides the agility required to speed up IT operations, and reduces cost by increasing infrastructure utilization. Autonomic computing automates the process through which the user can provision resources on-demand. By minimizing user involvement, automation speeds up the process, reduces labor costs and reduces the possibility of human errors.

How does Cloud Computing solve this problem:

Small companies(IT or non-IT) give contract to cloud service providers to handle their servers and it's responsibility of cloud service providers to maintain the server and provide backup facilities. It's efficiency storing the data,computation and less maintenance cost has attracted bigger businesses to convert their maintenance cost into profit. Let's consider the example of any automobile company,they never hire engineers to maintain their servers rather than they give contract to cloud service providers like IBM and Amazon.

Advantages:

cost saving:
The most significant cloud computing benefit is cost saving. The cloud is available at much cheaper rates and lowers the company's IT expenses. It eliminaes investment in software,hardware,server licensing fees,data storage,software updates,management etc..It allows users to pay for only what they use and according to the demand the charges get increased.

Accessibility:

We can access our data from anywhere via Internet connection

Mobility: 

Cloud computing allows mobile access to corporate data via smartphones and devices, which, considering over 2.6 billion smartphones are being used globally today, is a great way to ensure that no one is ever left out of the loop. Staff with busy schedules, or who live a long way away from the corporate office, can use this feature to keep instantly up-to-date with clients and coworkers.

Through the cloud, you can offer conveniently accessible information to sales staff who travel, freelance employees, or remote employees, for better work-life balance. Therefore, it's not surprising to see that organizations with employee satisfaction listed as a priority are up to 24 percent more likely to expand cloud usage.

Backup and recovery:

Since all our data is stored in the cloud,so the process of backing it up and restoring the same is much easier than storing the same on physical device. The various cloud service providers offer reliable and flexible backup/recovery solutions. Hence cloud make the process of backup and recovery much simpler than other traditional methods of data storage.

Unlimited Storage:

Depending upon the payment mode,the client can store data on cloud

Increased collaboration:

If your business has two employees or more, then you should be making collaboration a top priority. After all, there isn't much point to having a team if it is unable to work like a team. Cloud computing makes collaboration a simple process. Team members can view and share information easily and securely across a cloud-based platform. Some cloud-based services even provide collaborative social spaces to connect employees across your organization, therefore increasing interest and engagement. Collaboration may be possible without a cloud computing solution, but it will never be as easy, nor as effective.

Reliability:
 Cloud computing is more reliable and consistent. Most providers offer a service which guarantees 24/7  availability. Companies can add or subtract resources based on their need.

Automatic software updates: 

For those who have a lot to get done, there isn't anything more irritating than having to wait for system update to be installed. Cloud-based applications automatically refresh and update themselves, instead of forcing an IT department to perform a manual organization-wide update. This saves valuable IT staff time and money spent on outside IT consultation. PCWorld lists that 50 percent of cloud adopters cited requiring fewer internal IT resources as a cloud benefit.

Watch the Video for more Details:  Advantages and Disadvantages of Cloud Computing


Friday, February 16, 2018

Java Break and Continue Statements with example

In this post you will learn about break and continue statements in java with some examples.
The break statement is used to "break" out of the innermost switch, for, while, or do-while statement body. When it is executed, a break statement causes the flow of control to jump to the next line after the loop or switch to the body containing the break.

The typical use of a break statement has the following simple syntax:
break;

The break statement can also be used in a labeled form to jump out of an outernested loop or switch statement. In this case, it has the syntax
break label;

where label is a Java identifier that is used to label a loop or switch statement. Such a label can only appear at the beginning of the declaration of a loop. There are no other kinds of "go to" statements in Java.

We illustrate the use of break statement in the following simple example:
public class Break
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;    // terminate loop if i is 5
}
System.out.print(i + " ");
}
System.out.println("stop the loop here");
}
}

Output:
1 2 3 4 stop the loop here

Continue Statement:
The other statement to explicitly change the flow of control in a Java program is the continue statement, which has the following syntax:
 
continue label;

where label is an optional Java identifier that is used to label a loop. As mentioned above, there are no explicit "go to" statements in Java. Likewise, the continue statement can only be used inside loops (for, while, and do-while). The continue statement causes the execution to skip over the remaining steps of the loop body in the current iteration (but then continue the loop if its condition is satisfied).

Example:

public class ContinueTest
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue;    // skip next statement if i is even
}
System.out.println(i + " ");
}
}
}
Output:
1 3 5 7 9

Wednesday, February 14, 2018

Java new operator with example

In this post you will learn how to use new operator in java with example.In Java, a new object is created from a defined class by using the new operator. The new operator creates a new object from a specified class and returns a reference to that object. In order to create a new object of a certain type, we must immediately follow our use of the new operator by a call to a constructor for that type of object.

Let us understand this topic with the following example:

public class Demo
{
public static void main(String args[])
{
Counter c;//declares the variable c to be of type Counter that means c can refer to any Counter object
Counter d=new Counter();//creates a new Counter object and returns a reference to it
c=new Counter();//creates a new Counter object and returns a reference to it
d=c;
}
}

Calling the new operator on a class type causes three events to occur:

  • A new object is dynamically allocated in memory, and all instance variables are initialized to standard default values. The default values are null for object variables and 0 for all base types except boolean variables (which are false by default).
  • The constructor for the new object is called with the parameters specified. The constructor fills in meaningful values for the instance variables and performs any additional computations that must be done to create this object.
  • After the constructor returns, the new operator returns a reference (that is, a memory address) to the newly created object. If the expression is in the form of an assignment statement, then this address is stored in the object variable, so the object variable refers to this newly created object.

Monday, February 12, 2018

How to declare class in Java

In this post you will learn how class is declared in java which is basic knowledge for beginners.an object is a specific combination of data and the methods that can process and communicate that data. Classes define the types for objects; hence, objects are sometimes referred to as instances of their defining class, because they take on the name of that class as their type.

Let's understand how to define a class with example. In this example a counter class for a simple counter,which can be accessed,incremented and decremented.

Example:

public class Counter{
protected int count;//a simple integer instance variable
Counter(){ //the default constructor for a counter object
count=0;
}
/** An accessor method to get the current count*/
public int getCount(){
return count;
}
/** A modifier method for incrementing the count */
public void incrementCount()
{
count++;
}
/**A modifier method for decrementing the count */
public void decrementCount()
{
return count--;
}

In the above example,notice that the class definition is delimited by braces, that is, it begins with a "{" and ends with a "} ". In Java, any set of statements between the braces "{" and "}" define a program block.

The Counter class is public, which means that any other class can create and use a Counter object. The Counter has one instance variable—an integer called count. This variable is initialized to 0 in the constructor method, Counter, which is called when we wish to create a new Counter object (this method always has the same name as the class it belongs to). This class also has one accessor method, getCount, which returns the current value of the counter. Finally, this class has two update methods—a method, incrementCount, which increments the counter, and a method, decrementCount, which decrements the counter.

Class modifiers are optional keywords that precede the class keyword. We have already seen examples that use the public keyword. 

In general,the different class modifiers and their meaning is as follows:

abstract: It is a class modifier describes a class that has abstract methods.Abstract methods are declared with the abstract keyword and are empty that means without defining a body of code for this method.

final: final class modifier describes a class that can have no subclasses.

public: public class modifier describes a class that can be instantiated or extended by anything in the same package or by anything that imports the class.

Public classes are declared in their own separate file called classname. java, where "classname" is the name of the class.

If the public class modifier is not used, the class is considered friendly. This means that it can be used and instantiated by all classes in the same package. This is the default class modifier

Wednesday, February 7, 2018

How to establish a database connection using JSP

In this post you will learn how to establish a database connection using JSP.The first thing you need to add is a page directive to import the java.sql package for the database code as follows:
<%@ page import="java.sql.*" %>
You'll use a single ResultSet object to hold your database results. Because you'd like this to be
available to the entire page, the next thing you do is declare it in a JSP declaration tag:
<%! ResultSet rs = null; %>
Finally, you establish a connection to the database and retrieve the required data.
Now i will show you a complete code for simple application to connect database.

<!-- JSP Directives -->
<%@ page import="java.sql.*" %>
<html>
<head>
<title>Employee Details</title>
</head>
<body>
<basefont face="Arial">
<!-- JSP Declarations -->
<%! ResultSet rs = null; %>

<!-- JSP Scriptlet -->
<%
try {
Class.forName("org.gjt.mm.mysql.Driver");
Connection db = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/quoting");
Statement s = db.createStatement();
rs = s.executeQuery("select * from employee");
}
catch (Exception e) {
// For now, just report the error to the system log
System.out.println(e.toString());
}
%>
<!-- Template text -->
<table width="550" border="0" align="center">
<tr>
<td bgcolor="#006633">
<div align="center">
<font size="6" color="#FFFFFF">
<b>Employee Details</b>
</font>
</div>
</td>
</tr>
<tr>
<td>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p align="center"><b>Employees</b></p>
<table width="290" border="0" align="center">
<%
try {
while (rs.next()) {
%>
<!-- JSP Expressions used within template text -->
<tr>
<td width="20"><%= rs.getInt(1) %></td>
<td width="70"><%= rs.getString(2) %></td>
<td width="70"><%= rs.getString(3) %></td>
<td width="40">
<a href="emp.jsp?id=<%= rs.getString(1) %>&action=edit">
edit
</a>
</td>
<td width="40">
<a href="emp.jsp?id=<%= rs.getString(1) %>&action=delete">
delete
</a>
</td>
</tr>
<%
}
}
catch (SQLException e) {
// For now, just report the error to the system log
System.out.println(e.toString());
}
%>
</table>
</td>
</tr>
<tr>
<td>
<p>&nbsp;</p>
<p align="center"><a href="emp.jsp?action=add">New Employee</a></p>
</td>
</tr>
</table>
</body>
</html>

Output:

Login form using JSP and MySQL

In this session you will learn how to develop a login form using jsp and MySQL database connection.MySQL has always been my favorite database because it’s very easy to use.You can use any IDE like Netbeans or Eclipse to build a JSP application. I prefer Netbeans over Eclipse.e building the application, make sure you have the MySQL Java Connector added to the libraries. Without it, the server (for e.g. Glass Fish Server) will throw an error.

Step 1: Create Login page

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Demo with JSP</title>
    </head>
    <body>
        <form method="post" action="validate.jsp">
            <center>
            <table border="1" cellpadding="5" cellspacing="2">
                <thead>
                    <tr>
                        <th colspan="2">Login</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Username</td>
                        <td><input type="text" name="username" required/></td>
                    </tr>
                    <tr>
                        <td>Password</td>
                        <td><input type="password" name="password" required/></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center"><input type="submit" value="Login" />
                            &nbsp;&nbsp;
                            <input type="reset" value="Reset" />
                        </td>                       
                    </tr>                   
                </tbody>
            </table>
            </center>
        </form>
    </body>
</html>

Step 2: Now create the validation page

After creating login page,this page will validate the username and password against the MySQL database.

<%@ page import ="java.sql.*" %>
<%
    try{
        String username = request.getParameter("username");  
        String password = request.getParameter("password");
        Class.forName("com.mysql.jdbc.Driver");  // MySQL database connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo?" + "user=root&password=");   
        PreparedStatement pst = conn.prepareStatement("Select user,pass from login where user=? and pass=?");
        pst.setString(1, username);
        pst.setString(2, password);
        ResultSet rs = pst.executeQuery();                       
        if(rs.next())          
           out.println("Valid login credentials");       
        else
           out.println("Invalid login credentials");           
   }
   catch(Exception e){      
       out.println("Something went wrong !! Please try again");      
   }     
%>

Once you have finished both your login and validate page, you can run the application in the browser. 

Output:
 

Note:
You must add JAR files when you use MySql database. In this case make sure you have added the MySQL Java Connector JAR file.

Saturday, February 3, 2018

javascript Alert box example

In this post you will understand how to create alert dialogue box using java script. This type of questions used to ask in technical round to check your programming skills. Let us see how to create alert dialogue box.

program:

<html>
<head>
<title>javascript program for an alert</title>
</head>
<body>
<script language="javascript">
   alert("welcome to example of alert using javascript");
var a=confirm("GOOD BYE");
if(true)
document.write("press ok");
else
document.write("pressed cancel");
document.close();
</script>
</body>
</html>
 

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...