This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Saturday, December 8, 2012

Hibernate Architecture


Hibernate Architecture


Hibernate architecture has three main components:
  • Connection Management
  • Transaction management
  • Object relational mapping:

How Hibernate came into existence?


How Hibernate came into existence?


=> Entity Beans of EJB technology were addressing almost all the limitations of direct usage of JDBC in data access layer.
=> Entity beans had two major limitations:
(1) Very bad performance
(2) Very complex to develope
=> Gavinn King developed Hibernate in 2001.
=> In 2003 Hibernate 2.x released.
=> In 2004 industry starts using Hibernate extensively.
=> Most of the Hibernate projects are using Hibernate 3.x.
=> Latest edition of Hibernate is 4.1.2.

What is Hibernate ?


What is Hibernate ?
=> Hibernate is a java persistent framework.
=> Hibernate is a software product to be installed into a computer system in order to use it to build data access layer of Java enterprise application.
=> Hibernate follows ORM approach to build data access layer & performs CRUD operations.
=> Hibernate is one of the ORM implements.
=> Hibernate consist of the followings:
(1) Hibernate API
(2) Hibernate Engine
(3) HQL
(4) DTD (& Schema) for generating mapping files and Annotations to specify mapping.

Friday, December 7, 2012

Apache Ant – Building Simple Java Projects


Ant Tutorial

By using this tutorial you can easily and quickly learn how to use Ant to build  java projects.

Ant Definition

Apache Ant is an open source, cross-platform based build tool that is use XML scripting to build  Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks.

Apache Ant Overview

Ant is developed by Apache Foundation specifically to build projects based on java platform. Ant is an abbreviation forAnother Neat Tool.

A Java build process typically includes:
  • the compilation of the Java source code into Java Bytecode
  • creation of the .jar file for the distribution
  • creation of the Documentation
Ant uses anXMLfile for its configuration. You can’t give any name to this file, this file is usually calledbuild.xmlIt builds are based on three blocks: taskstargets and extension points .
A task is a individual work like compile source code or creating Javadoc. More than one task can be combine to form a group called targets.
A target can be directly invoked via Ant. Targets can specify their dependencies  using “depends” attribute. Ant tool will automatically execute dependent targets.
For example if target Run depends on Compile, than Ant will first perform Compile and then Run.
<target name="compile">
 ...................
   </target>
<target name="run" depends="compile">
 ...................
   </target>
In yourbuild.xmlfile you can specify the default target. Ant will execute this target, if no explicit target is specified.

History of Ant

The development of Ant technology originated as an integral component of Tomcat application server based on Java Servlet and Java Server Faces. Ant, as a part of Apache Jakarta Project is an open source solution based on java platform.  Ant used as a major tool in building java projects and now it has become a top-level Apache project for server-side solutions. The latest release of Ant is version 1.8.4.
Introduction to Apache Ant (Another Neat Tool)
Ant is an open source build technology developed by Apache intended to build processes in Java environment. Ant is based on XML and uses java classes in automatic generation of build processes that makes it platform independent. It is applicable to any integrated development environment (IDE) that uses java. A build file is generally named asbuild.xml (can’t be other than build.xml).
The best features of the Ant technology can be summarized as below -
  • · Easy to Use: As it is an XML based scripting tool, therefore easy to understand and implement.
  • · Portable and Cross-platform based:  it can be run on any operating system.
  • · Extended Functionality:  It is easier to implement than any specific IDE because it is automated and ubiquitous.
  • · Build Automation: Ant provides automated build processes that is faster and more efficient than manual procedures and other build tools can also be integrated with it.
  • · Compilation of Source Code: Ant can use and compile source code from a variety of version controls and packaging of the compiled code and resources can also be done.
  • · Handling Dependencies between Targets: An Ant Project describes the target and tasks associated with it and also handles dependencies between various targets and tasks.

Saturday, July 28, 2012

JSP Tag Libraries in Breif



You have many options when it comes to generating dynamic content inside the JSP page.

These options are as follows :
  • Scripting elements calling servlet code directly
  • Scripting elements calling servlet code indirectly (by means of utility     classes)
  • Beans
  • Servlet/JSP combo (MVC)
  • MVC with JSP expression language
  • Custom tags

The options at the top of the list are much simpler to use and are just as legitimate as the options at the bottom of the list. However, industry has adopted a best practice to avoid placing Java code inside the JSP page. This best practice stems from it being much harder to debug and maintain Java code inside the JSP page. In addition, JSP pages should concentrate only on the presentation logic. Introducing Java code into the JSP page tends to divert its purpose and, inevitably, business logic starts to creep in. To enforce this best practice, version 2.4 of the servlet specification went so far as to provide a way to disable any type of JSP scripting for a group of JSP pages. We discuss how to disable scripting in Section 2.14 (Configuring JSP Pages).

That said, there are cases where the presentation logic itself is quite complex and using the non-Java code options in the JSP page to express that logic becomes either too clunky and unreadable or, sometimes, just impossible to achieve. This is where logic through the familiar HTML-like structures.

Although the SimpleTag API completely replaces the classic tag API, you should keep in mind that it works only in containers compliant with servlet specification 2.4 and above. Because there are still a lot of applications running on servlet 2.3-compliant containers, you should consider avoiding the SimpleTag API if you are not sure what type of container your code will end up on.

Tag Library Components :

To use custom JSP tags, you need to define three separate components :

- The tag handler class that defines the tag's behavior
- The TLD file that maps the XML element names to the tag implementations
- The JSP file that uses the tag library

Most people find that the first tag they write is the hardest—the difficulty being in knowing where each component should go, not in writing the components. So, we suggest that you start by just downloading the simplest of the examples of this chapter from http://volume2.coreservlets.com/ and getting those examples to work on your machine. After that, you can move on and try creating some of your own tags.

The Tag Handler Class :

When defining a new tag, your first task is to define a Java class that tells the system what to do when it sees the tag. This class must implement the SimpleTag interface. In practice, you extend SimpleTagSupport, which implements the SimpleTag interface and supplies standard implementations for some of its methods. Both the SimpleTag interface and the SimpleTagSupport class reside in the javax.servlet.jsp.tagext package.

The very first action the container takes after loading the tag handler class is instantiating it with its no-arg constructor. This means that every tag handler must have a no-arg constructor or its instantiation will fail. Remember that the Java compiler provides one for you automatically unless you define a constructor with arguments. In that case, be sure to define a no-arg constructor yourself.

The code that does the actual work of the tag goes inside the doTag method. Usually, this code outputs content to the JSP page by invoking the print method of the JspWriter class. To obtain an instance of the JstWriter class you call getJspContext().getOut() inside the doTag method. The doTag method is called at request time. It's important to note that, unlike the classic tag model, the SimpleTag model never reuses tag handler instances. In fact, a new instance of the tag handler class is created for every tag occurrence on the page. This alleviates worries about race conditions and cached values even if you use instance variables in the tag handler class.

You place the compiled tag handler in the same location you would place a regular servlet, inside the WEB-INF/classes directory, keeping the package structure intact. For example, if your tag handler class belongs to the mytags package and its class name is MyTag, you would place the MyTag.class file inside the WEB-INF/classes/mytags/ directory.

Example Tag Handler Class :

Code:
package javabynataraj;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

public class ExampleTag extends SimpleTagSupport {
  public void doTag() throws JspException, IOException {
    JspWriter out = getJspContext().getOut();
    out.print("<b>Hello World!</b>");
  }
}

The Tag Library Descriptor File :

Once you have defined a tag handler, your next task is to identify this class to the server and to associate it with a particular XML tag name. This task is accomplished by means of a TLD file in XML format. This file contains some fixed information (e.g., XML Schema instance declaration), an arbitrary short name for your library, a short description, and a series of tag descriptions.

Example Tag Library Descriptor File :

Code:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
  <tlib-version>1.0</tlib-version>
  <short-name>csajsp-taglib</short-name>
  <tag>
    <description>Example tag</description>
    <name>example</name>
    <tag-class>package.TagHandlerClass</tag-class>
    <body-content>empty</body-content>
    </tag>
</taglib>

We describe the details of the contents of the TLD file in later sections. For now, just note that the tag element through the following subelements in their required order defines the custom tag.

description : This optional element allows the tag developer to document the purpose of the custom tag.

name : This required element defines the name of the tag as it will be referred to by the JSP page (really tag suffix, as will be seen shortly).

tag-class : This required element identifies the fully qualified name of the implementing tag handler class.

body-content : This required element tells the container how to treat the content between the beginning and ending occurrence of the tag, if any. The value that appears here can be either empty, scriptless, tagdependent, or JSP.

The value of empty means that no content is allowed to appear in the body of the tag.

This would mean that the declared tag can only appear in the form :

Code:
<prefix:tag/>
      or
<prefix:tag></prefix:tag>


(without any spaces between the opening and closing tags). Placing any content inside the tag body would generate a page translation error.

The value of scriptless means that the tag body is allowed to have JSP content as long as it doesn't contain any scripting elements like <% ... %> or <%= ... %>. If present, the body of the tag would be processed just like any other JSP content.

The value of tagdependent means that the tag is allowed to have any type of content as its body. However, this content is not processed at all and completely ignored. It is up to the developer of the tag handler to get access to that content and do something with it. For example, if you wanted to develop a tag that would allow the JSP page developer to execute an SQL statement, providing the SQL in the body of the tag, you would use tagdependent as the value of the body-content element.

Finally, the value of JSP is provided for backward compatibility with the classic custom tag model. It is not a legal value when used with the SimpleTag API.

Note that there is no legal way of allowing any scripting elements to appear as the tag body under the new SimpleTag API model.

Core Warning :

When using the SimpleTag API, it is illegal to include scripting elements in the body of the tag.

The TLD file must be placed inside the WEB-INF directory or any subdirectory thereof.

Example JSP File :

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Example JSP page</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<%@ taglib uri="/WEB-INF/tlds/example.tld"
             prefix="test" %>
<test:example/>
<test:example></test:example>
</BODY></HTML>

Static ContextPath to Dynamic ContextPaths in Jsp and JS pages



Changing Static ContextPath to Dynamic ContextPath references in JSP and JS pages in our project. If you are working with any project on java and jsp technologies, if the requirement may come to change the static context paths to dynamic context path.

What is the need to change context path from static to dynamic context path?

While developing our application we use to develop to put our contextPath directly in some areas like for links and mostly for images we give absolute paths with context. We put this in developing the project. After developing the project , it goes to Testing after then to production.
Let us assume our project contextPath is "/myproj"


Now this project is going for testing, then the testers change the contextPath as theirs purpose like "/myprojTest" then the images and links all will broken. For this purpose the dynamic context references will be use full.

1. Change to Dynamic ContextPaths in Pager Tags of JSP pages.

The Old Code having Static ContextPath:

<pg:pager maxPageItems="10"

            prevNextUrl="/myproj/auto/sheetAuditResults.do"

            url="/myproj/auto/sheetAuditResults.do" 

            name="caseResponseForm">
               -------
              ------------
</pg:pager>

Here the ContextPath is /myproj need to change to Dynamic path as given below:

use jsp:useBean tags to define the variable name and get the contextPath then assign the link to the variables pnUrlName and urlName in the scriptlets.

<jsp:useBean id="pnUrlName" class="java.lang.String" scope="page" />

<jsp:useBean id="urlName" class="java.lang.String" scope="page" />

      <%pnUrlName = request.getContextPath()+"/auto/sheetAuditResults.do"; %>

      <%urlName = request.getContextPath()+"/auto/sheetAuditResults.do"; %>

      <pg:pager maxPageItems="10"

            prevNextUrl="<%=pnUrlName %>"

            url="<%=urlName %>" 

            name="auditInformationResultsResponseForm">


2. Change ContextPath for images in Jsp page

<img src="/myproj/images/calbtn.gif" border="0" alt="popup selection calendar ">
We have to change the static contextPath /myproj to dynamically.

for that we have to declare in jsp page below to the taglib tags. as given below:
<%@ taglib uri="/WEB-INF/tlds/struts-core.tld" prefix="c" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>

Convert the image with static contextPath to dynamically as given below

<img src="<c:out value="${path}"/>/images/calbtn.gif" border="0" alt="popup selection calendar">

3. Change ContextPath in javascript file to open a new window.

caseWindow = window.open('/myapp/cases/displayCase.do?previousPage=addDeposit'+jsessionId,'
DN_modalEms','width=800,height=600,resizable=yes,
scrollbars=yes,status=yes,menubar=no,toolbar=no,modal=yes');

Then change the contextPath /myproj to dynamic contextPath

As we did before for the jsp page we have to define the contextPath to a variable path using jsp core tag library tags.
<c:set var="path" value="${pageContext.request.contextPath}"/>
use the contextPath in the javascript function:
<script type="text/javascript">
      contextPath = '<c:out value="${path}"/>';
</script>
modalCaseWindow = window.open(contextPath+'/cases/displayCreateCase1.do?previousPage=addDeposit'+jsessionId,'DN_modalEms',
'width=800,height=600,resizable=yes,scrollbars=yes,
status=yes,menubar=no,toolbar=no,modal=yes');

4.Change contextPath for hyperlinks:

<a href="/myproj/updateMyDeviceId.do?device=' + ent.deviceId + '">';
Change the static context root reference to dynamic contextPath for the hyperlink in jsp file as given below.

Use the same defined contextPath variable to use here. Actually the contextPath is global accessible in an application any where. NO need to define in every page of jsp.
<a href="'+ contextPath +'/updateMyDeviceId.do?device=' + ent.deviceId + '">';

5.Change contextPath in javascript file for image.

if (data.status == 1) {

                  $('#status').text('Enabled');
                  $('#circle').attr('src', '/myproj/images/green-circle.png')
                  $('#statusButton').val('Disable');
            }
Change the context path in the if condition. For this define a variable as ctx to get contextPath using request.getContextPath() method.

<script>var ctx = "<%=request.getContextPath()%>"</script>
Declare the ctx variable below to the taglib uri tags then we can use any where in the program.

if (data.status == 1) {
                  $('#status').text('Enabled');
                  $('#circle').attr('src',ctx+'/images/green-circle.png')
                  $('#statusButton').val('Disable');
            }


You might also like:     

Friday, July 20, 2012

Web application introduction.

WebApplication is a collection of web resources like HTML files, JavaScriptfiles, image files Servletsjsps and etc.

In order to make resources of a application as globally accessible resources developed as web resources of web-application each web-resource develops one webpage and this webpage is globally accessible page.
The web-application that is moved to internet network after development is called Website.

A web application contains two types of web-resources. 

**    Server side Web-resource    
**    Client side Web-resource
    A web resource that comes to browser(client) from web application placed in web-server/application server for execution is called client side web resource.

    EX:  HTML,JavaScript programs.

    The web-resource program that executed in the server(web-server/application server)is called server-side web-resource program.

    EX : Servlet,JSP
    • Don't decide weather web-server program is server-side or client side based on the place where it resides and decide based on the place where it executes.

    What is the difference between doGet() and doPost() methods ?

    The difference has given below......


     
    doGet

    doPost
    In doGet Method the parameters are appended to the URL and sent along with header information
    In doPost parameters are sent in separate line in the body
    Maximum size of data that can be sent using doget is 240 bytes
    There is no maximum size for data
    Parameters are not encrypted
    Parameters are encrypted
    DoGet method generally is used to query or to get some information from the server
    DoPost is slower compared to doGet since doPost does not write the content length
    DoGet should be idempotent. i.e. doget should be able to be repeated safely many times
    This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable for example updating stored data or buying items online.
    DoGet should be safe without any side effects for which user is held responsible.
    This method does not need to be either safe.

    Upload CSV file into MySql Database based on columns using Servlets and Java



    The CSV file is having multiple values to insert in perticular columns and rows in mysql database.

    Here we have two files so we have to insert in two tables .

    *** one is Header part file

    *** another is Detail part file

    Basically these two are to upload the questions and answers into the examination portal to upload question papers and answer paper in (Merit Tracking System project).

    First we have to do the things are Uploaded file has to save in perticular folder and then they have to insert the values into the database table.This is our main task to do.


    The required files to this program are 

    #1. index.jsp
    #2. succ.jsp
    #3. web.xml
    #4. DBConnection.java
    #5. SaveFile.java
    #6. UploadFile2DB.java

    and Some other libraries to add 


    #1. mysql-connector-java-3.1.11.jar
    #2. servlet-api.jar

    These are enough to our requirement add this files to your "lib" folder.



    #1. index.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
    <form name="fileuploadform"
     action="http://localhost:8080/UploadCSV/uploadfile">Upload CSV
    File<br>
    Select the header file to upload <input type="file" name="filehdr" /><br>
    Select the detail file to upload <input type="file" name="filedtl" /><br>
    
    Please select a folder to which the file has to be uploaded. <input
     type="file" name="filefolder" /><br>
    <input type="submit" name="submit" value="submit"> </form>
    </html>

    #2. succ.jsp 

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <b>The Files has been Uploaded into particular tables.</b>
    </body>
    </html>

    #3. DBConnection.java


    package com;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBConnection {
    static Connection con;
        
        public static Connection getConnection(){
            con=null;
            try{
                System.out.println("----------I am in DBConnection----------");
                Class.forName("com.mysql.jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://192.168.1.101:3306/test?user=test&password=test" );
                System.out.println("---------end of DBConnection----------");
            }catch(Exception e){
                e.getMessage();
            }
            return con;
        }
    }
    


    #4. SaveFile.java


    package com;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class SaveFile extends HttpServlet {
        public void init(ServletConfig config)throws ServletException{
            super.init(config);
            System.out.println("The SaveFile iniated.^^^^^^^^^^^^^^^^^^^################");
        }
        
        public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
            try{
                String pathheader=request.getParameter("filehdr");
                System.out.println("The pathheader is : "+pathheader);
                String pathdetail=request.getParameter("filedtl");
                System.out.println("The pathdetail is : "+pathdetail);
                
                String folderpath=request.getParameter("filefolder");    
                
                String filenamehdr=folderpath+pathheader.substring(pathheader.lastIndexOf('\\'));
                System.out.println("The file output path is : "+filenamehdr);            
                String filenamedtl=folderpath+pathdetail.substring(pathdetail.lastIndexOf('\\'));
                System.out.println("The file output path is : "+filenamedtl);
                
                FileInputStream fis=new FileInputStream(pathheader);
                FileOutputStream fos=new FileOutputStream(filenamehdr);
                
                byte buf[]=new byte[11024];
                fis.read(buf);
                fos.write(buf,0,buf.length);
                
                fis=new FileInputStream(pathdetail);
                fos=new FileOutputStream(filenamedtl);
                fis.read(buf);
                fos.write(buf,0,buf.length);
                
                if(fis!=null)
                    fis.close();
                if(fos!=null)
                    fos.close();
                
                System.out.println("------------------ Files are Saved in Folder-------------------");
                request.getRequestDispatcher("/uploaddata").forward(request, response);
    
            }catch(FileNotFoundException e){
                System.out.println(e.getMessage());
            }catch(IOException e){
                System.out.println(e.getMessage());
            }
        }
    
    
    }
    
    


    #5. UploadFile2DB.java


    package com;
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.util.StringTokenizer;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class UploadFile2DB extends HttpServlet {
        public void init(ServletConfig config) throws ServletException{
            super.init(config);
            System.out.println("The UploadDataServlet2 iniated.");
        }
    
    
    
        public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
            
            
            String filepathhdr=request.getParameter("filehdr");
            String filepathdtl=request.getParameter("filedtl");
            Connection con=DBConnection.getConnection();
            System.out.println("connection=----------->"+con);
            PreparedStatement pstmthdr=null;
            PreparedStatement pstmtdtl=null;
    
            int rowshdr=0;
            BufferedReader brhdr=new BufferedReader(new FileReader(filepathhdr));
            BufferedReader brdtl=new BufferedReader(new FileReader(filepathdtl));
            System.out.println("reading the file");
            String strLineHdr="";
            String strLineDtl="";
            String hdrstr="";
            String dtlstr="";
            StringTokenizer sthdr=null;
            StringTokenizer stdtl=null;
            //        String firstColumnData[]=new String[10];
            int lineNumberHdr=0;
            int lineNumberDtl=0;
            //        int line=1;
            try{
                pstmthdr=con.prepareStatement("insert into omts_onlinehdr values (?,?,?,?,?,?,?)");
                System.out.println("statement executed");
    
                while((strLineHdr=brhdr.readLine())!=null){
                    System.out.println("HEADERLINE"+strLineHdr);
                    int i=1;
                    if(!(lineNumberHdr==0)){
                        sthdr=new StringTokenizer(strLineHdr,",");
                        while(sthdr.hasMoreTokens()){
                            hdrstr=sthdr.nextToken();
                            System.out.println("HeaderString: "+hdrstr);
                            pstmthdr.setString(i++,hdrstr);
                            System.out.println("below insertion");
                        }
                        rowshdr=pstmthdr.executeUpdate();
                        System.out.println(rowshdr+" rows updated.");
                    }
                    lineNumberHdr++;
                }
                System.out.println("not in detail");
                pstmtdtl=con.prepareStatement("insert into omts_onlinedtl values (?,?,?,?,?,?,?)");
                System.out.println("ps executed");
    
                while((strLineDtl=brdtl.readLine())!=null){
                    System.out.println("detailLINE"+strLineDtl);
                    int i=1;
                    if(!(lineNumberDtl==0)){
                        stdtl=new StringTokenizer(strLineDtl,",");
                        while(stdtl.hasMoreTokens()){
                            dtlstr=stdtl.nextToken();
                            System.out.println("detail: "+dtlstr);
                            pstmtdtl.setString(i++,dtlstr);
                            System.out.println("below insertion");
                        }
                        int rowsdtl=pstmtdtl.executeUpdate();
                        System.out.println(rowsdtl+" rows are updated.");
                    }
                    lineNumberDtl++;
                }
                //con.commit();
            }
            catch(Exception e){
                System.out.println(e.getMessage());
            }
            finally
            {
                try {
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            response.sendRedirect("http://localhost:8080/UploadCSV/succ.jsp");
        }
    }
    


    Run your application using Tomcat webserver and it will displays index.jsp as welcome-file-list.



    By selecting CSV file  using browse button  of header part and detail part and set the path of the folder where you want to save the uploaded files and click on submit button.

    After completion of accessing two files into folders and databases it will displays as succ.jsp file as "successfully uploaded the two files".


    The Console will displays as the all the information what is going inside.
    Note: Use the MySql database or Oracle and give the driver name and url of the driver to connect Database in the DBConncetion class.


    DOWNLOAD SOURCE

    For Reference on Files:

    Difference between ServletContext and ServletConfig ?

    What is the Difference between ServletConfig and ServletContext.?


    ServletConfig:

    public interface ServletConfig

    ServletConfig encapsulates servlet configuration and gives access to the application (servlet context) object. Servlet initialization parameters appear in the servlet configuration file. Each servlet class may have several different servlet instances, one for each servlet parameters:


    1. One ServletConfig per servlet
    2. It is used to pass deploy-time info to servlet and configured in the deployment descriptor file. 
    3. it is used to access ServletContext 
    4. It is within the Servlet element in Deployment descriptor.
    5. It is accessed by using getServletConfig().getInitParameter("myname"); 
    6. It is available only to the servlet in which init-param is configured.

    Example: 


    ServletContext:

    public interface ServletContext

    ServletContexts encapsulate applications. Applications are generalized virtual hosts; a URL prefix defines a distinct application. So /myapp and /yourapp could define different applications. As a degenerate case, each virtual host has its own ServletContext. 

    1. It returns the current context of a web application running in a particular JVM.. 
    2. If the web application is distributed,it is one per JVM. 
    3. It is used to access the elements configured in deployment descriptor.
    4. It is accessed by using getServletContext().getInitParameter("myname"); 
    5. It is available to any servlet or jsp that is part of web application.


    Example:

    Introduction to JDBC

    JDBC stands for Java Database Connectivity allows developers to connect, query and update a database using the Structured Query Language. JDBC API standard provides Java developers to interact with different RDBMS and access table data through Java application without learning RDBMS details and using Database Specific JDBC Drivers.

    2.  JDBC Architecture

    JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database:

    open connection to database,

    use JDBC driver to send SQL queries to database,

    process the results that are returned, and

    close the connection.

    JDBC uses two architectures to communicate with database:

    1) The driver connects to database and executes SQL statements. Results are sent back from driver to driver manager and finally to the application.
    2) The JDBC driver communicates with ODBC driver. ODBC driver executes SQL query and then results are sent back to JDBC driver to driver manager and then to application.



    1. Introduction to JDBC
    2. JDBC Architecture 
    3. Interaction of JDBC with Database 
    4. Introduction to Hibernate 
    5. Hibernate Architecture 
    6. Hibernate Communication with RDBMS 
    7. Hibernate vs. JDBC 
    7.1. Advantage of Hibernate over JDBC 
    7.2. Disadvantages of Hibernate