Skip to main content

Java JDBC Connection and JSP


Today we will create JSP page which will show records in table fetched from MySQL database using JDBC Connection.
It is not best practice to do coding in scriptlet.Major disadvantages of coding in scriptlet are
    Reusability: you can't reuse scriptlets.
    Replaceability: you can't make scriptlets abstract.
    OO-ability: you can't make use of inheritance/composition.
    Debuggability: if scriptlet throws an exception halfway, all you get is a blank page.
    Testability: scriptlets are not unit-testable.
    Maintainability: more time is needed to maintain mingled/cluttered/duplicated code logic.

     TRY TO AVOID CODING IN SCRIPTLET. USE JSTL OR EXPRESSION LANGUAGE.

But we will do it here just for demo purpose and to built up coding confidence.
We will not waste time and let's start coding part.

Step 1 : create Dynamic Web Project in Eclipse
                                New --->  Dynamic Web Project
Create web.xml file and add it  in WEB-INF folder of project.
                                WebContent ---> WEB-INF  ---> web.xml
It will act as entry point to your application.Every URL will mapped from this file.
web.xml

 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>DemoWebProject</display-name>  
  <welcome-file-list>  
   <welcome-file>/WEB-INF/index.jsp</welcome-file>  
  </welcome-file-list>  
 </web-app>  

Step 2 :  Create JSP file
JSP is just a servlet.
Create this file in Project at location  
                   WebContent ---> WEB-INF  ---> index.jsp
index.jsp


 <%@page import="java.util.ArrayList"%>  
 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
 <!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.lang.*"%>  
 <%@ page import="java.util.*"%>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
 <title>Insert title here</title>  
 </head>  
 <body>  
      <h4>Welcome : JDBC Connection and JSP</h4>  
      <%  
           Connection connect = null;  
           Statement statement = null;  
           ResultSet resultSet = null;  
           List<String> names = null;  
           try {  
                //install JDBC driver  
                Class.forName("com.mysql.jdbc.Driver");  
                // setup the connection with the DB.  
                connect = DriverManager.getConnection("jdbc:mysql://localhost/DB?user=scott&password=tiger");  
                // statements allow to issue SQL queries to the database  
                statement = connect.createStatement();  
                // resultSet gets the result of the SQL query  
                resultSet = statement.executeQuery("select * from STUDENT ");  
                names = new ArrayList<String>();  
                while (resultSet.next()) {  
                     names.add(resultSet.getString("NAME"));  
                }  
           } catch (Exception e) {  
                //handle exception here  
           } finally {  
                //always close resulset  
                if (resultSet != null) {  
                     resultSet.close();  
                }  
                //always close statement  
                if (statement != null) {  
                     statement.close();  
                }  
                //always remember to close the connection as it is very resource intensive  
                //it may couse connection leak in hude application  
                //it will slow down application  
                if (connect != null) {  
                     connect.close();  
                }  
           }  
      %>  
      <h5>Student Information</h5>  
      <table>  
           <tr>  
                <th>NAME</th>  
           </tr>  
           <tr>  
                <%  
                     if (names != null && !names.isEmpty()) {  
                          for (String name : names) {  
                               out.println("<td>" + name + "</td>");  
                          }  
                     }  
                %>  
           </tr>  
      </table>  
 </body>  
 </html>  


Step 3: Assuming you have created Table name STUDENT in database.It will have two columns ID and NAME.
SQL query may look like :

 CREATE TABLE STUDENT(ID int,NAMEvarchar(255));  

Step 4 :Install Apache TOMCAT server in eclipse and RUN the project.

Step 5:I think you will get error no driver found error in console.

 java.lang.ClassNotFoundException: com.mysql.jdbc.Driver   

we need an implementation of JDBC driver for mysql database which is implemented as "com.mysql.jdbc.Driver" and comes with mysql-connector.jar.
It will found in download.
Point to note : As it is web Project, you have to add jar in servers library.In this case it will be our tomcat.
Q : How can we add jar in Server library?
A : No need to panic.Just copy mysql-connector*.jar from disk and paste in folder in your project at location :
         WebContent ---> WEB-INF ---> lib

That's it.


Popular posts from this blog

Share data between Iframe and its Parent using JQuery

There could be requirement that you have to pass variables values to Iframe from parent or in other scenario you have to pass values from Iframe to its parent.I am going to show simple example of above situation with the help of JQuery.
           Support we have parent HTML page having iframe included like below

<html> <body> <input id="parentValue" type="text" value="I am from Parent !" /> <iframe src="domainurl/relativepath" id="iframe"></iframe> <script> $(document).ready(function() { //code to take value from child iframe var childValue = $("#iframe").contents().find("#childValue").val(); alert(childValue); }); </script> </body> </html> 
        and we have frame code like below
<html> <body> <input id="childValue" type="text" value="I …

Spring Default Limit for Collection and Array is 256

If you are working in Web Application Development then you may stuck or already had ,then you will get mad of getting this error


java.lang.ArrayIndexOutOfBoundsException:Arrayindexoutofrange256
How this error emanates in Spring?

i will explain you with example.Suppose you are adding Values in List in JSP using JSTL tag or other.
This list is in Form(HTML).When you POST this form,In behind Stage,Spring does binding of Object and List if present.

But wait...
In Spring,Default limit for array and collection growing is 256.

Why this limit is Set?

seldom you have to send List size greater than this limit.
Spring has set this limit to avoid notable OutOfMemoryErrors in case of large indexes.

So,than What if i want to set Collection greater than this size?

I had told earlier,spring does binding behind.If we tell spring to increase it's size or set collection size behalf of spring.
You you can do it.

We have initBinder,  in Spring  it is called when spring does the binding mechanism
e.g @Mod…

Apache FOP Tutorial for PDF Generation

What is meant by Apache FOP?

Apache is providing open source JAVA application for PDF(or any other format) file generation from XML data.Simply to can give data in XML,it gives output in PDF or any format.But it is primary for PDF output.

Official explanation,
OP (Formatting Objects Processor) is the world's first print formatter driven by XSL formatting objects (XSL-FO) and the world's first output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output. Output formats currently supported include PDF, PCL, PS, SVG, XML (area tree representation), Print, AWT, MIF and TXT

How wcan configure apache fop with our project?

I am going to explain how to generate PDF using Apache FOP.
I will explain it in steps

Step 1:
You will require 3 jar for configurations.Here fop jar depend on both avalon api and avalon impl.
              1.    apache fop 1.1
              2.    avalon-framework-api 4.3.1
    …