Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Sunday, January 23, 2011

JSP Tutorial 4 : Creating Spreadsheets with JSP


In this program, we are going to create a new  excel sheet using java .
You can create any number of  new excel sheets in a excel file.

To create a excel sheet we can use third party APIs .
The name of this API is  POI.
This API is  provided by the Apache Jakarta(Jakarta POI - Java API To Access Microsoft Format Files ) Tomcat.
You can download POI.jar form  Apache Jakarta Project.It is open source.
OLE 2 compound Document Format is based on files including most Microsoft office files as XLS and DOC.
The package we need to import is java.io.InputStream, org.apache.poi.hssf.usermodel.HSSFSheet and org.apache.poi.hssf.usermodel. HSSFWorkbook.
The java.io.InputStream class is used to create file.
We are creating an excel file named "newrajesh.xls". The org.apache.poi.hssf.usermodel.
HSSFWorkbook class is used to create an object of  HSSFWorkbook, by which we will write our new rajesh.xls  file.
This object allows us to modify the excel file. The org.apache.poi.hssf.usermodel.HSSFSheet is used to create an object of sheet .
The org.apache.poi.hssf.usermodel.HSSFSheet is used to create a new sheet.
This class extends java.lang.Object. It is used to create a high level worksheet.

To create new sheet, we use HSSFSheet constructor in which we pass the name of the sheet as an  string argument.
We can create any number of sheets. As we are creating here six sheet as named  new sheet, second sheet ,third sheet ,fourth sheet, and fifth sheet.

Read the step by step tutorial :

JSP Tutorial 3 : Custom Exceptions in JSP


Before going to understand what is Custom Exception, its important to know what is Exception.
An Exception occurs whenever an abnormal condition arises at the execution of the code at run time.
It is run time error.

Custom Exception inherits the properties from the Exception class.
 Whenever we have declare our own exceptions then we call it custom exceptions.
 In the example given below we have declared our own Custom Exception which will be thrown
 when there arises any exception in the method fetchException().

The code of the program is given below:

<HTML>
    <HEAD>
        <TITLE>Custom Exception in jsp</TITLE>
    </HEAD>
    <BODY>
        <H1>Custom Exception in jsp</H1>
        <%!
            class CustomException extends Exception
            {
                String value="This is a custom Exception";
                public String toString()
                {
                    return "Custom Exception: " + value;
                }
                CustomException(String v)
                {
                    value = v;
                }
            }
     void fetchException(String value) throws CustomException
            {
                if(value != ""){
                    throw new CustomException(value);
            }
        }
    %>
    <%
        try {
            fetchException("This is a custom Exception");
            fetchException("");
        } catch (CustomException e) {
            out.println("Exception: " + e);
        }
    %>
    </BODY>
</HTML>


JSP Tutorial -2 : Connect to MYSQL database and basic operations


This is detailed java code to connect a jsp page to mysql database
and create a table of given name in the specified database.

Steps to Follow:

1. create a database named 'usermaster' in mysql and create table "user_master".
2. Create an application directory named 'user' in the Tomcat.
3. Before running this java code you need mysql connector jar
   in the Tomcat-6.0.16/webapps/user/WEB-INF/lib directory.

Creating JSP pages:
In this example, we have created two JSP pages.
First page is to provide link to create table and the next page for processing the table creation.

1. Hello_database_query.jsp
2.create_table.jsp

1. Hello_database_query.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
    <head>
        <title>Create table in mysql database using jsp</title>
    </head>
    <body>
        <TABLE style="background-color: #ffffcc;">
            <TR>
                <TD align="center"><h2>To create
                    table click on the link given below</h2></TD>
            </TR>
            <TR>
                <TD align="center"><A HREF="create_table.jsp">
                <font size="+2" color="blue">create table</font>
            </TR>
        </TABLE>
    </body>
</html>
Save this code as a .jsp file named "Hello_database_query.jsp" in the directory Tomcat-6.0.16/webapps/user/.
You can run this jsp page typing http://localhost:8080/user/Hello_database_query.jsp url in address bar of the browser.



2.create_table.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
    <head>
        <title>display data from the table using jsp</title>
    </head>
    <body>
        <%
            /* Create string of connection url within specified
                 format with machine name, port number
            and database name. Here machine name id localhost
              and database name is usermaster. */
            String connectionURL = "jdbc:mysql://localhost:3306/usermaster";
            // declare a connection by using Connection interface
            Connection connection = null;
            // declare object of Statement interface that is used for
            // executing sql statements.
            Statement statement = null;
            try {
                // Load JBBC driver "com.mysql.jdbc.Driver".
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                /* Create a connection by using getConnection() method
                   that takes parameters of string type connection url, user
                   name and password to connect to database. */
                connection =
                   DriverManager.getConnection(connectionURL, "root", "root");
                /* createStatement() is used for create statement object
                  that is used for sending
                sql statements to the specified database. */
                statement = connection.createStatement();
                // sql query to retrieve values from the secified table.
                String QueryString =
                 "create table user_master(id int not null auto_increment,name " +
                        "varchar(25),city varchar(20), primary key(id));";
                // execyteUpdate() mothod execute specified sql query.
                statement.executeUpdate(QueryString);
        %> <TABLE border="0" style="background-color: #ffffcc;">
        <TR>
            <TD align="center" ><font size="+3" color="green">Congratulations !
                </font></TD>
            <tr><TD align="center" ><font size="+2">Table of specified name is
                created successfully.</font>
            </TD></tr>
        </TR>
        <% } catch (Exception ex) {%>
        <TABLE border="0" style="background-color: #ffffcc;">
            <TR>
                <TD align="center" ><font size="+3" color="red">Some problems
               to create table.</font></TD>
            </TR>
            <% } finally {
                // close all the connections.
                statement.close();
                connection.close();
            }
            %><tr><td align="center" >
                    <A HREF="Hello_database_query.jsp">
                <font size="5" color="blue">back to home page</font></A></td>
        </tr> </TABLE>
    </body>
</html>
Save this code with name "create_table.jsp" in the directory Tomcat-6.0.16/webapps/user/.
This jsp code creates table of specified name in the mysql database and shows a response page.
If table exists already or found any error to make connection with database then shows an error page.

JSP Tutorial -1 : Life Cycle of a JSP Page


Life of the the jsp page is  same as the servlet life cycle.
Once translated the jsp file is just like a servlet.

The life cycle of the jsp page is given below:

1. jspInit(): This method is the called form the init() method.
This method is of interface javax.servlet.jsp.JspPage.
We can override this method. This method will be called once when the container loads the servlet for the first time.
2. _jspService(): This method is called from the servlet's service method.
The container passes the Request and Response objects to this method.
We can't override this method. It is a method of javax.servlet.jsp.HttpJspPage interface.

3. jspDestroy: This method is called by the servlet's destroy() method.
We can override this method. It is a method of javax.servlet.jsp.JspPage interface.

<html>
<head>
<title>The lifecycle of jsp page</title>
</head>


<body>
<h1>Showing the life cycle of jsp using jspInit and jspDestroy</h1>
<%!
int num;
int counter;
public void jspInit()
{
counter++;
num = 10;
}


public void jspDestroy()
{
counter--;
num = 0;
}
%>


<%
out.println("The number is " + num + "<br>");
out.println("The counter is " + counter + "<br>");
%>
</body>
</html>

subversion video