JSP Example to Connect to MS SQL Database and Retrieve Records

16
JSP Example to connect to MS SQL database and retrieve records This is a simple JSP program to connect to MSSQL database. This example JSP program shows how to connect to a MSSQL database from your JSP program. 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;

Transcript of JSP Example to Connect to MS SQL Database and Retrieve Records

JSP Example to connect to MS SQL database and retrieve recordsThis is a simple JSP program to connect to MSSQL database. This example JSP program shows how to connect to a MSSQL database from your JSP program. 

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;

// Remember to change the next line with your own environment String url= "jdbc:jtds:sqlserver://nameofyourdatabaseserver.or.ipaddress/yourdatabasename";String id= "username";String pass = "password";try{

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>

Sending Email using JSPThis is a sample program to send email using JSP. Of course you should have a HTML page that shows a form to enter and get details of the email, just as you will see in any email client. The form should accept details such as 'to' email, 'from' email, 'subject' and 'body'. The form action should point to the JSP page shown below.

<html><head><title>JSP JavaMail Example </title></head><body><%@ page import="java.util.*" %><%@ page import="javax.mail.*" %><%@ page import="javax.mail.internet.*" %><%@ page import="javax.activation.*" %><%String host = "yourmailhost";String to = request.getParameter("to");String from = request.getParameter("from");String subject = request.getParameter("subject");String messageText = request.getParameter("body");boolean sessionDebug = false;// Create some properties and get the default Session.Properties props = System.getProperties();props.put("mail.host", host);props.put("mail.transport.protocol", "smtp");Session mailSession = Session.getDefaultInstance(props, null); // Set debug on the Session// Passing false will not echo debug info, and passing True will. mailSession.setDebug(sessionDebug); // Instantiate a new MimeMessage and fill it with the // required information. Message msg = new MimeMessage(mailSession);msg.setFrom(new InternetAddress(from));InternetAddress[] address = {new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO, address);msg.setSubject(subject);msg.setSentDate(new Date());msg.setText(messageText); // Hand the message to the default transport service// for delivery. 

Transport.send(msg);out.println("Mail was sent to " + to);out.println(" from " + from);out.println(" using host " + host + ".");%></table></body></html>

JSP Example to connect to MS SQL database using Tomcat Connection PoolThis is a simple JSP program to connect to MSSQL database using the connection pool in Tomcat by creating JNDI name for the DataSource. 

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

A sample context setting in Tomcat 4.1.29 is given below: 

<Context path="/Payment" docBase="C:\Applications\Payment"><Logger className="org.apache.catalina.logger.FileLogger" prefix="payment_log." suffix=".txt" timestamp="true"/><Resource auth="Container" name="jdbc/paymentDB" scope="Shareable" type="javax.sql.DataSource"/><ResourceParams name="jdbc/paymentDB"><parameter><name>factory</name><value>org.apache.commons.dbcp.BasicDataSourceFactory</value></parameter><parameter><name>url</name><value></value></parameter><parameter><name>password</name><value>yourdbpassword</value></parameter><parameter>

<name>maxWait</name><value>10000</value></parameter><parameter><name>maxActive</name><value>100</value></parameter><parameter><name>driverClassName</name><value>net.sourceforge.jtds.jdbc.Driver</value></parameter><parameter><name>username</name><value>yourdbusername</value></parameter><parameter><name>maxIdle</name><value>30</value></parameter></ResourceParams></Context>

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;

javax.naming.Context initCtx = new javax.naming.InitialContext();javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");paymentDB = (DataSource) envCtx.lookup("jdbc/paymentDB");

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 TomcatThe 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.htmldefault.jsp anotherJsp.jspimages/logo.jpegWEB-INF/classes/jspservletcookbook/myservlet.classWEB-INF/lib/helperclasses.jarWEB-INF/lib/utilities.jarWEB-INF/web.xmlWEB-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 web.xmldeployment descriptor The classes directory, which contains package-related directories and servlet or support

classes like JavaBeans The lib directory, which stores any Java Archive (JAR) files containing utility or helper

classes that your web application uses Optionally, any Tag Library Descriptor files (files with .tld suffixes) Any optional directories for images, video files, XML files, or other web resources

What are the different scopes in JSP?

One of the most powerful features of JSP is that a JSP page can access, create, and modify data objects on the server. You can then make these objects visible to JSP pages. When an object is created, it defines or defaults to a given scope. The container creates some of these objects, and the JSP designer creates others.

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 JSPSessions 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.

First we have a form, let us call it GetName.html

<HTML>

<BODY>

<FORM METHOD=POST ACTION="SaveName.jsp">

What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>

<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.)

<%

   String name = request.getParameter( "username" );

   session.setAttribute( "theName", name );

%>

<HTML>

<BODY>

<A HREF="NextPage.jsp">Continue</A>

</BODY>

</HTML>

 

The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.  

<HTML>

<BODY>

Hello, <%= session.getAttribute( "theName" ) %>

</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

Encrypting Passwords in Tomcat using ServletsIn Tomcat, it’s easy to encrypt passwords by adding the digest attribute to a realm definition. The value must be one of the digest algorithms supported by the java.security.MessageDigest class (SHA, MD2, or MD5). To expand on the earlier example, the XML snippet shown next adds SHA encrypting to a file-based realm:

<Realm className="org.apache.catalina.realm.UserDatabaseRealm" debug="0" resourceName="UserDatabase" digest="SHA" />

To log into the application, you now need to encrypt the password stored in tomcat-users.xml to its encrypted form. You can do this by executing the following command: 

java org.apache.catalina.realm.RealmBase -a SHA {cleartext-password}

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.