First program of adding two numbers in JSP
< %@ page language="java"% >
< html >
< head >
< title > Add number program in JSP< /title >
< /head >
< body >
< %
int a=5;
int b=2;
int result=a+b;
out.print("Additon of a and b :"+result);
% >
< /body >
< /html >
Second program of subtraction two numbers in JSP
< %@ page language="java"% >
< html >
< head >
< title > Subtraction numbers program in JSP< /title >
< /head >
< body >
< %
int a=5;
int b=2;
int result=a-b;
out.print("Subtraction of a and b :"+result);
% >
< /body >
< /html >
Third program of print even numbers in JSP
< %@ page language="java"% >
< html >
< head >
< title > Even number program in JSP< /title >
< /head >
< body >
< %
for(int i=0;i< =10;i++)
{
if((i%2)==0)
{
out.print("Even number :"+i);
out.print("< br >");
}
}
% >
< /body >
< /html >
Forth program of print odd numbers in JSP
< %@ page language="java"% >
< html >
< head >
< title > Odd number program in JSP< /title >
< /head >
< body >
< %
for(int i=0;i< =10;i++)
{
if((i%2)!=0)
{
out.print("Odd number :"+i);
out.print("< br >");
}
}
% >
< /body >
< /html >
Wednesday, February 10, 2010
servlet
What is Java Servlets?
Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others.
Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language.
HTTP Servlet typically used to:
* Priovide dynamic content like getting the results of a database query and returning to the client.
* Process and/or store the data submitted by the HTML.
* Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.
Methods of Servlets
A Generic servlet contains the following five methods:
init()
public void init(ServletConfig config) throws ServletException
The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service.
The servlet cannot be put into the service if
* The init() method does not return within a fix time set by the web server.
* It throws a ServletException
Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred.
service()
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and javax.servlet.ServletResponse are passed by the servlet container.
The status code of the response always should be set for a servlet that throws or sends an error.
Parameters - The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception.
getServletConfig()
public ServletConfig getServletConfig()
This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.
Returns - the ServletConfig object
getServletInfo()
public String getServletInfo()
The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup.
Returns - a string that contains the information about the servlet
destroy()
public void destroy()
This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held.
Life cycle of Servlet
The life cycle of a servlet can be categorized into four parts:
1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute of web.xml file. If the attribute has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.
The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.
Life Cycle of a Servlet
Inserting Data In Database table using Statement
In this program we are going to insert the data in the database from our java program in the table stored in the database.
To accomplish our goal we first have to make a class named as ServletInsertingData, which must extends the abstract HttpServlet class, the name of the class should be such that other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method that takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We can insert the data in the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we first need to call the method forName(), which is static in nature of the class Class. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method createStatement() of the Connection object which will return the Statement object. This object is used for executing a static SQL statement and obtaining the results produced by it. We have to insert a values into the table so we need to write a query for inserting the values into the table. This query we will write inside the executeUpdate() method of the Statement object. This method returns int value.
If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure".
The code of the program is given below:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DataInsertion extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost/zulfiqar?user=root&password=admin";
Connection conn;
ResultSet rs;
try{
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection(url);
Statement statement = conn.createStatement();
String query = "insert into emp_sal values('zulfiqar', 15000)";
int i = statement.executeUpdate(query);
if(i!=0){
out.println("The record has been inserted");
}
else{
out.println("Sorry! Failure");
}
rs = statement.executeQuery("select * from emp_sal");
while(rs.next()){
out.println("
" + rs.getString(1) + " " + rs.getInt(2) + "
");
}
rs.close();
statement.close();
}
catch (Exception e){
System.out.println(e);
}
}
}
XML File for this program
"1.0" encoding="ISO-8859-1"?>
Hello
class>DataInsertionclass>
Hello
/DataInsertion
Table in the database before Insertion:
mysql> select * from emp_sal;
Empty set (0.02 sec)
The output of the program is given below:
Table in the database after Insertion:
mmysql> select * from emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
+ysql> select * from emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
+----------+--------+
1 row in set (0.02 sec)
Retrieving Data from the table using PreparedStatement
n this program we are going to fetch the data from the database in the table from our java program using PreparedStatement.
To accomplish our goal we first have to make a class named as ServletFetchingDataFromDatabase which must extends the abstract HttpServlet class, the name of the class should be such that the other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class ClassLoader. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object and takes a query as its parameter. In this query we will write the task we want to perform. The Resultset object will be retrieved by using the executeQuery() method of the PreparedStatement object. Now the data will be retrieved by using the getString() method of the ResultSet object.
The code of the program is given below:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletFetchingDataFromDatabase extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin");
PreparedStatement pst = connection.prepareStatement("Select * from emp_sal");
ResultSet rs = pst.executeQuery();
while(rs.next()){
pw.println(rs.getString(1) +" " + rs.getString(2)+"
");
}
}
catch (Exception e){
pw.println(e);
}
pw.println("hello");
}
}
The output of the program is given below:
Table in the database:
mysql> select * from emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others.
Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language.
HTTP Servlet typically used to:
* Priovide dynamic content like getting the results of a database query and returning to the client.
* Process and/or store the data submitted by the HTML.
* Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.
Methods of Servlets
A Generic servlet contains the following five methods:
init()
public void init(ServletConfig config) throws ServletException
The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service.
The servlet cannot be put into the service if
* The init() method does not return within a fix time set by the web server.
* It throws a ServletException
Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred.
service()
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and javax.servlet.ServletResponse are passed by the servlet container.
The status code of the response always should be set for a servlet that throws or sends an error.
Parameters - The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception.
getServletConfig()
public ServletConfig getServletConfig()
This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.
Returns - the ServletConfig object
getServletInfo()
public String getServletInfo()
The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup.
Returns - a string that contains the information about the servlet
destroy()
public void destroy()
This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held.
Life cycle of Servlet
The life cycle of a servlet can be categorized into four parts:
1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute of web.xml file. If the attribute has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.
The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.
Life Cycle of a Servlet
Inserting Data In Database table using Statement
In this program we are going to insert the data in the database from our java program in the table stored in the database.
To accomplish our goal we first have to make a class named as ServletInsertingData, which must extends the abstract HttpServlet class, the name of the class should be such that other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method that takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We can insert the data in the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we first need to call the method forName(), which is static in nature of the class Class. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method createStatement() of the Connection object which will return the Statement object. This object is used for executing a static SQL statement and obtaining the results produced by it. We have to insert a values into the table so we need to write a query for inserting the values into the table. This query we will write inside the executeUpdate() method of the Statement object. This method returns int value.
If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure".
The code of the program is given below:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DataInsertion extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost/zulfiqar?user=root&password=admin";
Connection conn;
ResultSet rs;
try{
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection(url);
Statement statement = conn.createStatement();
String query = "insert into emp_sal values('zulfiqar', 15000)";
int i = statement.executeUpdate(query);
if(i!=0){
out.println("The record has been inserted");
}
else{
out.println("Sorry! Failure");
}
rs = statement.executeQuery("select * from emp_sal");
while(rs.next()){
out.println("
" + rs.getString(1) + " " + rs.getInt(2) + "
");
}
rs.close();
statement.close();
}
catch (Exception e){
System.out.println(e);
}
}
}
XML File for this program
"1.0" encoding="ISO-8859-1"?>
Hello
class>DataInsertionclass>
Hello
/DataInsertion
Table in the database before Insertion:
mysql> select * from emp_sal;
Empty set (0.02 sec)
The output of the program is given below:
Table in the database after Insertion:
mmysql> select * from emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
+ysql> select * from emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
+----------+--------+
1 row in set (0.02 sec)
Retrieving Data from the table using PreparedStatement
n this program we are going to fetch the data from the database in the table from our java program using PreparedStatement.
To accomplish our goal we first have to make a class named as ServletFetchingDataFromDatabase which must extends the abstract HttpServlet class, the name of the class should be such that the other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class ClassLoader. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object and takes a query as its parameter. In this query we will write the task we want to perform. The Resultset object will be retrieved by using the executeQuery() method of the PreparedStatement object. Now the data will be retrieved by using the getString() method of the ResultSet object.
The code of the program is given below:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletFetchingDataFromDatabase extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin");
PreparedStatement pst = connection.prepareStatement("Select * from emp_sal");
ResultSet rs = pst.executeQuery();
while(rs.next()){
pw.println(rs.getString(1) +" " + rs.getString(2)+"
");
}
}
catch (Exception e){
pw.println(e);
}
pw.println("hello");
}
}
The output of the program is given below:
Table in the database:
mysql> select * from emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
Sunday, February 7, 2010
Subscribe to:
Comments (Atom)
Bind Some Event to Element and trigger that function when click the element
Scenario: Suppose if we used same click event function in various web pages. if you want do some logic some page button for that need to re...
-
Find highcharts which are loaded in the page and then convert chart into png using jquery Charts are loaded through the ajax See the e...