The content in this blog just for educational purposes only.We are not responsible for anything.

Recent Post

Recent Posts

Showing posts with label servlets. Show all posts
Showing posts with label servlets. Show all posts

Wednesday, July 3, 2013

Accessing database from JSP

Accessing database from JSP

In This article I am going to discuss the connectivity from MYSQL database with JSP.we take a example of Books database. This database contains a table named books_details.


In This article I am going to discuss the connectivity from MYSQL database with JSP.we take a example of Books database. This database contains a table named books_details. This table contains three fields- id, book_name& author. we starts from very beginning. First we learn how to create tables in MySQl database after that we write a html page for inserting the values in 'books_details' table in database. After submitting values a table will be showed that contains the book name and author name.
Database

The database in example consists of a single table of three columns or fields. The database name is "books" and it contains information about books names & authors.

Table:books_details

ID   Book Name   Author
   1.  Java I/O  Tim Ritchey
   2.
 Java & XML,2 Edition   
 Brett McLaughlin
   3.  Java Swing, 2nd Edition
 Dave Wood, Marc Loy,
Start MYSQL prompt and type this SQL statement & press Enter-
    MYSQL>CREATE DATABASE `books` ;
This will create "books" database.
Now we create table a table "books
_details" in database "books".
  
  
   MYSQL>CREATE TABLE `books_details` (
    `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
    `book_name` VARCHAR( 100 ) NOT NULL ,
   `author` VARCHAR( 100 ) NOT NULL ,
    PRIMARY KEY ( `id` )
    ) TYPE = MYISAM ;

This will create a table "books_details" in database "books"
JSP Code
The following code contains  html for user interface & the JSP backend-
<%@ page language="java" import="java.sql.*" %>
<%
 String driver = "org.gjt.mm.mysql.Driver";
 Class.forName(driver).newInstance();
 
 Connection con=null;
 ResultSet rst=null;
 Statement stmt=null;
 
 try{
  String url="jdbc:mysql://localhost/books?user=
&password=";
  con=DriverManager.getConnection(url);
  stmt=con.createStatement();
 }
 catch(Exception e){
  System.out.println(e.getMessage());
 }
 if(request.getParameter("action") != null){ 
  String bookname=request.getParameter("bookname");
  String author=request.getParameter("author");
  stmt.executeUpdate("insert into books_details(book_name,
author) values('"+bookname+"','"+author+"')");
  rst=stmt.executeQuery("select * from books_details");
  %>
  
  
  

Books List

<% int no=1; while(rst.next()){ %> <% no++; } rst.close(); stmt.close(); con.close(); %>
S.No Book Name Author</.b>
<%=no%> <%=rst.getString(" book_name")%> <%=rst.getString("author") %>
<%}else{%> Book Entry FormDocument
  
   

Book Entry Form

 
Book Name:
Author:
<%}%>
Now we explain the above  codes.
Declaring Variables: Java is a strongly typed language which means, that variables must be explicitly declared before use and must be declared with the correct data types. In the above example code we declare some variables for making connection. Theses variables are- 
Connection con=null;
ResultSet rst=null;
Statement stmt=null;


The objects of type Connection, ResultSet and Statement are associated with the Java sql. "con" is a Connection type object variable that will hold Connection type object. "rst" is a ResultSet type object variable that will hold a result set returned by a database query. "stmt" is a object variable of Statement .Statement Class methods allow to execute any query.  
Connection to database: The first task of this programmer is to load database driver. This is achieved using the single line of code :-
String driver = "org.gjt.mm.mysql.Driver";
Class.forName(driver).newInstance();
The next task is to make a connection. This is done using the single line of code :-
String url="jdbc:mysql://localhost/books?user=&password=";
con=DriverManager.getConnection(url);
When url is passed into getConnection() method of DriverManager class it  returns connection object. 
Executing Query or Accessing data from database:
This is done using following code :-

stmt=con.createStatement(); //create a Statement object 
rst=stmt.executeQuery("select * from books_details");
stmt is the Statement type variable name and rst is the RecordSet type variable. A query is always executed on a Statement object.
A Statement object is created by calling createStatement() method on connection object con. 
The two most important methods of this Statement interface are executeQuery() and executeUpdate(). The executeQuery() method executes an SQL statement that returns a single ResultSet object. The executeUpdate() method executes an insert, update, and delete SQL statement. The method returns the number of records affected by the SQL statement execution.
After creating a Statement ,a method executeQuery() or  executeUpdate() is called on Statement object stmt and a SQL query string is passed in method executeQuery() or  executeUpdate().
This will return a ResultSet rst related to the query string.
Reading values from a ResultSet:
while(rst.next()){

   %>

   <%=no%><%=rst.getString("book_name")%><%=rst.getString("author")%>

  <%

}
The ResultSet  represents a table-like database result set. A ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row. Therefore, to access the first row in the ResultSet, you use the next() method. This method moves the cursor to the next record and returns true if the next row is valid, and false if there are no more records in the ResultSet object.
Other important methods are getXXX() methods, where XXX is the data type returned by the method at the specified index, including String, long, and int. The indexing used is 1-based. For example, to obtain the second column of type String, you use the following code:
resultSet.getString(2);
You can also use the getXXX() methods that accept a column name instead of a column index. For instance, the following code retrieves the value of the column LastName of type String.
resultSet.getString("book_name");
The above example shows how you can use the next() method as well as the getString() method. Here you retrieve the 'book_name' and 'author' columns from a table called 'books_details'. You then iterate through the returned ResultSet and print all the book name and author name in the format " book name | author " to the web page.
Summary:
This article presents JDBC and shows how you can manipulate data in a relational database from your  JSP page. To do this, you need to use  the java.sql package: DriverManager, Connection, Statement, and ResultSet. Keep in mind, however, that this is only an introduction. To create a Web application, you need  JDBC to use more features such as prepared statements and connection pooling.
To Download Example click here

When you click on the above link a Book Entry Form will open

Fill the book name and author fields and press Submit button. A page will open and show  a table of book name and authors like...

 


Monday, July 1, 2013

Upload and Retrieve image using JSP.

Upload and Retrieve image using JSP.
          
  Hello friends,  I am write this blog for those programmer are required a code for “how to upload and retrieve images (photos) from server using JSP.”
There is two jsp files are used in this project, and this project following libraries are required.   
     commons-fileupload.jar
        commons-fileupload-1.2.1.jar
        commons-io-1.4

this project done using NetBeans IDE 6.9.1 IDE. and jdk1.6.0_23
Code:
upload_file_multipale.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" errorPage="" %> 
<%@ page import="java.util.List"%> 
<%@ page import="java.util.Iterator"%> 
<%@ page import="java.io.File"%> 
<%@ page import="org.apache.commons.fileupload.*"%> 
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> 
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.lang.Exception"%>



           
           

Your files are uploading.....

            <%
       
                 String itemName="";
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                       
                 if (!isMultipart){
                         out.println("The Form is not Multipart!!!!!");
                 }
                else
                {
                         FileItemFactory  factory = new DiskFileItemFactory();
                         ServletFileUpload upload = new ServletFileUpload(factory);
                         List items = null;
                         try {
                                        items = upload.parseRequest(request);
                         } catch (FileUploadException  e) {
                                        out.println(e.toString());
                         }
                                                Iterator itr = items.iterator();
                                   
                                                while (itr.hasNext()) {
                                                            FileItem item = (FileItem) itr.next();
                                                            if (item.isFormField()){
                                                                         String name = item.getFieldName();
                                                                         String value = item.getString();
                                                            }
                                                            else {
                                                                        try {
                                                                                     itemName = item.getName();
                                                                                    itemName = FilenameUtils.getName(itemName);
                                                                                    //out.println(itemName);

    File savedFile = new File(config.getServletContext().getRealPath("/")+"uploadedFiles/"+itemName);
                       item.write(savedFile);
                       session.setAttribute("FileName",itemName);
                                                                                   
                                                                       } catch (Exception e) {
                                                                                                out.println(e.toString());
                                                                        }
                                                            }
                                                }
                                    }
                        
            response.sendRedirect("/FileUpload/upload_file_multipale_html.jsp");
   %>
   
  




upload_file_multipale_html.jsp

<%@page import="java.io.File"%>

     Multipale file upload by using apache.commons.fileupload

  
  
      
                   
Upload and Retrieve Image (Photo)by using apache.commons.fileupload in JSP  
      
      
          

      
      
          
                               Specify file: 
           
       
        
                

        
         
               
               
           
             
        
            

        
         
            
By RAVICHANDRA
Email: kotharavichandra555@gmail.com
My blog: kotharavichandra.blogspot.com
         
   
      
   
          
               <%
                   
                     String FileName = (String)session.getAttribute("FileName");
                     File savedFile = new File(config.getServletContext().getContextPath() +"/uploadedFiles/"+FileName  );
                   
                %>
               

          
      
  

Upload and Retrieve image using JSP.
          
  Hello friends,  I am write this blog for those programmer are required a code for “how to upload and retrieve images (photos) from server using JSP.”

There is two jsp files are used in this project, and this project following libraries are required.   
     commons-fileupload.jar
        commons-fileupload-1.2.1.jar
        commons-io-1.4

this project done using NetBeans IDE 6.9.1 IDE. and jdk1.6.0_23
Code:
upload_file_multipale.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" errorPage="" %> 
<%@ page import="java.util.List"%> 
<%@ page import="java.util.Iterator"%> 
<%@ page import="java.io.File"%> 
<%@ page import="org.apache.commons.fileupload.*"%> 
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> 
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.lang.Exception"%>



           
           

Your files are uploading.....

            <%
       
                 String itemName="";
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                       
                 if (!isMultipart){
                         out.println("The Form is not Multipart!!!!!");
                 }
                else
                {
                         FileItemFactory  factory = new DiskFileItemFactory();
                         ServletFileUpload upload = new ServletFileUpload(factory);
                         List items = null;
                         try {
                                        items = upload.parseRequest(request);
                         } catch (FileUploadException  e) {
                                        out.println(e.toString());
                         }
                                                Iterator itr = items.iterator();
                                   
                                                while (itr.hasNext()) {
                                                            FileItem item = (FileItem) itr.next();
                                                            if (item.isFormField()){
                                                                         String name = item.getFieldName();
                                                                         String value = item.getString();
                                                            }
                                                            else {
                                                                        try {
                                                                                     itemName = item.getName();
                                                                                    itemName = FilenameUtils.getName(itemName);
                                                                                    //out.println(itemName);

    File savedFile = new File(config.getServletContext().getRealPath("/")+"uploadedFiles/"+itemName);
                       item.write(savedFile);
                       session.setAttribute("FileName",itemName);
                                                                                   
                                                                       } catch (Exception e) {
                                                                                                out.println(e.toString());
                                                                        }
                                                            }
                                                }
                                    }
                        
            response.sendRedirect("/FileUpload/upload_file_multipale_html.jsp");
   %>
   
  




upload_file_multipale_html.jsp

<%@page import="java.io.File"%>

     Multipale file upload by using apache.commons.fileupload

  
  
      
                   
Upload and Retrieve Image (Photo)by using apache.commons.fileupload in JSP  
      
      
          

      
      
          
                               Specify file: 
           
       
        
                

        
         
               
               
           
             
        
            

        
         
            
By RAVICHANDRA
Email: kotharavichandra555@gmail.com
My blog: kotharavichandra.blogspot.com
         
   
      
   
          
               <%
                   
                     String FileName = (String)session.getAttribute("FileName");
                     File savedFile = new File(config.getServletContext().getContextPath() +"/uploadedFiles/"+FileName  );
                   
                %>
               

          
      
  
 


All the best Guys...
Hope you find the answer for your question...!!!