JSP Example To Connect To MS SQL Database and Retrieve Records
JSP Example To Connect To MS SQL Database and Retrieve Records
You also need to download the appropriate driver to connect to MSSQL server from your JSP
page. In this tutorial we are using the JTDS driver which can be downloaded from
http://jtds.sourceforge.net/ Once you have downloaded the jar file you will have to copy it to
your common lib folder in your tomcat (or any other servlet container you are using).
The database server can be residing anywhere in the network. You just need to get the IP address
or the domain name of the server together with the database name, username and password. Just
remember to construct the right url. This sample JSP page assumes that there is a table named
tbl_sys_user in your database and it has fields with names, cust_id, rdate and email. In your case,
you will have to change the names according to your requirement.
<html>
<head><title>Enter to database</title></head>
<body>
<table>
<%@ page import="java.util.*" %>
<%@ page import="javax.sql.*;" %>
<%
java.sql.Connection con;
java.sql.Statement s;
java.sql.ResultSet rs;
java.sql.PreparedStatement pst;
con=null;
s=null;
pst=null;
rs=null;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = java.sql.DriverManager.getConnection(url, id, pass);
}catch(ClassNotFoundException cnfex){
cnfex.printStackTrace();
}
String sql = "select top 10 * from tbl_sys_user";
try{
s = con.createStatement();
rs = s.executeQuery(sql);
%>
<%
while( rs.next() ){
%><tr>
<td><%= rs.getString("cust_id") %></td>
<td><%= rs.getString("rdate") %></td>
<td><%= rs.getString("email") %></td>
</tr>
<%
}
%>
<%
}
catch(Exception e){e.printStackTrace();}
finally{
if(rs!=null) rs.close();
if(s!=null) s.close();
if(con!=null) con.close();
}
%>
</body>
</html>
You also need to download the appropriate driver to connect to MSSQL server from your JSP
page. In this tutorial we are using the JTDS driver which can be downloaded from
http://jtds.sourceforge.net/ Once you have downloaded the jar file you will have to copy it to
your common lib folder in your tomcat (or any other servlet container you are using).
For using the JNDI in Tomcat, you will have to edit your context setting in server.xml
As you can see in the context example for connection pooling above, you are creating a JNDI
named jdbc/paymentDB with the url that connects to your database server and the username and
password. Once you have done that you can use the sample JSP page given below to get the
context of this JNDI and use this to connect to the database. This sample program assumes that
there is a table named tbl_sys_user in your database and it has fields with names, cust_id, rdate
and email. In your case, you will have to change the names according to your requirement.
<html>
<head><title>Enter to database</title></head>
<body>
<table>
<%@ page import="java.util.*" %>
<%@ page import="javax.sql.*;" %>
<%
java.sql.Connection c1;
java.sql.Statement s1;
java.sql.ResultSet rs1;
java.sql.PreparedStatement pst1;
DataSource paymentDB;
c1=null;
s1=null;
pst1=null;
rs1=null;
try{
if(paymentDB == null) {
javax.naming.Context initCtx1 = new javax.naming.InitialContext();
javax.naming.Context envCtx1 = (javax.naming.Context) initCtx1.lookup("java:comp/env");
paymentDB = (DataSource) envCtx1.lookup("jdbc/paymentDB");
}
}
catch(Exception e){
System.out.println("inside the context exception");
e.printStackTrace();
}
c1 = paymentDB.getConnection();
String sq1= "select top 10 * from tbl_sys_user";
pst1 = c1.prepareStatement(sq1);
rs1 = pst1.executeQuery();
while( rs1.next() ){
%>
<tr>
<td><%= rs1.getString("cust_id") %></td>
<td><%= rs1.getString("rdate") %></td>
<td><%= rs1.getString("email") %></td>
</tr>
<%
}
if(pst1!=null) pst1.close();
if(rs1!=null) rs1.close();
if(c1!=null) c1.close();
%>
</body>
</html>
Deploying an Individual JSP on Tomcat
The easiest way to test a new JSP file is to place it at the top level of Tomcat's default web
application. This application is located in the <Tomcat-installation-directory>/webapps/ROOT/
directory. Tomcat 4.1.x compiles (or recompiles, if you are pasting a new JSP file over an old
one) the JSP and display its response in a web page. You do not have to stop and start Tomcat
using the Tomcat manager application for the new JSP file to be available to your web
application.
Placing a JSP file in a deployed web application will not work if the JSP
depends on application-specific resources such as servlets, custom tags, or
other Java classes, because there is no guarantee that the temporary host
web application you are using for the JSP has access to those resources.
If you have to deploy a JSP separately from its web application, you can also place a JSP file in a
deployed web application other than the Tomcat default application. This makes the JSP page
available to application users without having to stop and restart Tomcat. Remember that the JSP
files belong in the top level of the web application, which has the following directory structure:
index.html
default.jsp
anotherJsp.jsp
images/logo.jpeg
WEB-INF/classes/jspservletcookbook/myservlet.class
WEB-INF/lib/helperclasses.jar
WEB-INF/lib/utilities.jar
WEB-INF/web.xml
WEB-INF/mytags.tld
In other words, the top level of the directory contains the HTML and JSP files, as well as the
WEB-INF directory. The WEB-INF directory contains:
The scope of an object describes how widely it's available and who has access to it. For example,
if an object is defined to have page scope, then it's available only for the duration of the current
request on that page before being destroyed by the container. In this case, only the current page
has access to this data, and no one else can read it. At the other end of the scale, if an object has
application scope, then any page may use the data because it lasts for the duration of the
application, which means until the container is switched off.
Page Scope
Objects with page scope are accessible only within the page in which they're created. The data is
valid only during the processing of the current response; once the response is sent back to the
browser, the data is no longer valid. If the request is forwarded to another page or the browser
makes another request as a result of a redirect, the data is also lost.
Request Scope
Objects with request scope are accessible from pages processing the same request in which they
were created. Once the container has processed the request, the data is released. Even if the
request is forwarded to another page, the data is still available though not if a redirect is required.
Session Scope
Objects with session scope are accessible from pages processing requests that are in the same
session as the one in which they were created. A session is the time users spend using the
application, which ends when they close their browser, when they go to another Web site, or
when the application designer wants (after a logout, for instance). So, for example, when users
log in, their username could be stored in the session and displayed on every page they access.
This data lasts until they leave the Web site or log out.
Application Scope
Objects with application scope are accessible from JSP pages that reside in the same application.
This creates a global object that's available to all pages.
Application scope uses a single namespace, which means all your pages should be careful not to
duplicate the names of application scope objects or change the values when they're likely to be
read by another page (this is called thread safety). Application scope variables are typically
created and populated when an application starts and then used as read-only for the rest of the
application.
Sessions in JSP
Sessions in JSP
In this article we will see about sessions in JSP. On a typical web site, a visitor might
visit several pages and perform several interactions.
If you are programming the site, it is very helpful to be able to associate some data with
each visitor. For this purpose, "session"s can be used in JSP.
A session is an object associated with a visitor. Data can be put in the session and
retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the
site.
Here is a set of pages that put a user's name in the session, and display it elsewhere. Try
out installing and using these.
<HTML>
<BODY>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
The target of the form is "SaveName.jsp", which saves the user's name in the session.
Note the variable "session". This is another variable that is normally made available in JSPs, just
like out and request variables. (In the @page directive, you can indicate that you do not need
sessions, in which case the "session" variable will not be made available.)
<%
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
<HTML>
<BODY>
</BODY>
</HTML>
If you bring up two different browsers (not different windows of the same browser), or
run two browsers from two different machines, you can put one name in one browser and
another name in another browser, and both names will be kept track of.
The session is kept around until a timeout period. Then it is assumed the user is no longer
visiting the site, and the session is discarded
where catalina.jar is in the CLASSPATH. Now, copy and paste this new password into the
%TOMCAT_HOME%\conf\tomcat-users.xml file. The problem with this method of password
encryption is that it might not be portable. Let’s take a look at programmatic encryption. You’ll
need to add encrypt.password=true to the build.properties file, pass it in from the command line
with ant –Dencrypt.password=true, or edit the default setting in app-settings.xml. If you’re using
the binary version (.war file) of this application, simply edit the following <init-param> of the
LoginServlet (in the web.xml file):
<init-param>
<param-name>encrypt-password</param-name>
<param-value>true</param-value>
</init-param>
Next, you need to actually encrypt the password within your servlet. To do this, create an
encodePassword(String password, String algorithm) method in a StringUtil.java class. This
method uses the MessageDigest class from JSSE to encrypt a string:
import java.security.MessageDigest;
public static String encodePassword(String password, String algorithm) {
byte[] unencodedPassword = password.getBytes();
MessageDigest md = null;
try {
// first create an instance, given the provider
md = MessageDigest.getInstance(algorithm);
} catch (Exception e) {
log.error("Exception: " + e);
return password;
}
md.reset();
// call the update method one or more times
// (useful when you don't know the size of your data, e.g. stream)
md.update(unencodedPassword);
// now calculate the hash
byte[] encodedPassword = md.digest();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < encodedPassword.length; i++) {
if (((int) encodedPassword[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) encodedPassword[i] & 0xff, 16));
}
return buf.toString();
}
This method encrypts a string based on the algorithm you pass in. This algorithm is defined in
LoginServlet and configurable when building via the ${encrypt-algorithm} variable. The default
setting is SHA.
If you’re using password encryption and also have a retrieve password feature, you’ll probably
want to add a password_hint column in your user store. It’s hard enough to remember all the
passwords you keep, and it’s annoying when you have to create a new password, so the “send me
a hint” tactic is useful.