INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Starting out with Java

JDBC, Servlet, JavaMail, and MSAccess hook up by gaboware
Posted: 12 Jul 01

PREREQUESITE
You should have tomcat or some other servlet/jsp working on your maching.  you should know how to create a database with msaccess and use the data sources administrative tool. you should run this source on a local machine.  

INTRODUCTION
Just thought i'll pass my example and show how easy servlets, databases and email can be incorporated. Why?
Because beginners like myself need help sometimes.

DESCRIPTION
This class represents a simple movie database that gets updated through an HTML Form, Servlet, and JDBC.  Also it sends email to an specified email using JavaMail.

CAUTIONS
Caution1:  This servlet's email method needs to be uncommented and provided with appropiate email server and email adddress information.  Otherwise, it will simply just update the database.  
Caution2: This servlet is not efficient, is not recommended for use only for educational purposes.

TOOLS
Tools I used to create this Class:
Operating System: Windows 2000 Professional
Database:  MSAccess 2000
Editor:  JCreator
JSP/Servlet: Tomcat 3.2.2
Language: Java 2
Java 2 extensions:  JavaMail

DATABASE INFORMATION
This class was run under a LOCAL machine. I provide the class only, you must create the Database with three tables using MSAccess and add its appropiate Data Source name through Windows 2000 administrative tools.  

The Default data source name this class connects to is:
Movies
The Default Tables this class updtates are:
ActionMovies
ComedyMovies
DramaMovies
The Default Fields for each Table are:
Title, Year, Type, Length

Of course you can change the format of the database but these changes must be reflected on the class.

CONCLUSION
So, copy class and html form code below and have fun with it. Hopefully, if you do everything right, it should work.  

CODE

 //Creator Gustavo Delgado
//The class MovieOnline was inspired through the readings of Marty Hall's Core Servlets
//and JavaServerPages, Michael Meloan's DukeBakery example at
//http://developer.java.sun.com/developer/technicalArticles/Database/dukesbakery/,
//and Oreilly's Java Network Programming 2nd Edition
//This class is not efficient, it just gives an idea of how to easily incorporate
//JDBC, Servlets and JavaMail


import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MovieOnline extends HttpServlet {
    String type, title, year, length, format, message;
    Connection connect;
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        
        
//Establishing connection to Database
        try{
        String url = "jdbc:odbc:Movies";
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        connect = DriverManager.getConnection(url, "gabo", "hi");
        message = "Connection Succesful";
    }
    catch(ClassNotFoundException cnfex){
        cnfex.printStackTrace();
    }
    catch(SQLException sqlex){
        sqlex.printStackTrace();
    }
    catch(Exception excp){
        excp.printStackTrace();
    }
        
//Gathering parameters from HTML form        
        
        type = request.getParameter("category");
        title = request.getParameter("title");
        year = request.getParameter("year");
        format = request.getParameter("format");
        length = request.getParameter("length");

//Outputing a freindly message to user    
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML><HEAD><TITLE>" + message + "</TITLE></HEAD>" +
                    "<BODY BGCOLOR = WHITE>\n" +
                    "<H1>" + message + "</H1>\n");
                    
                    
        
//Checking what database table should the html form information go        

      if (type.equals("comedy")){
               try{
                Statement stmt = connect.createStatement();
                    String query = "INSERT INTO ComedyMovies (" +
                    "Title, Year, Type, Length" +
                    ") VALUES ('" +
                    title + "', '" +
                    year  + "', '"+
                    format + "', '"+
                    length + "')";
                    int result = stmt.executeUpdate(query);
                    stmt.close();
                }
                
                catch(SQLException ex){
                    while (ex != null){
                   System.out.println("\nError:\n");
                   System.out.println("Message: " + ex.getMessage());
                   System.out.println("SQLState: " + ex.getSQLState());
                   System.out.println("Error Code: " + ex.getErrorCode());
                   ex = ex.getNextException();
                    System.out.println("ERROR WITH SQL");
                }
                }  
            }
                
                else if (type.equals("action")){
                    try{
                    Statement stmt = connect.createStatement();
                    String query = "INSERT INTO ActionMovies (" +
                    "Title, Year, Type, Length" +
                    ") VALUES ('" +
                    title + "', '" +
                    year + "', '"+
                    format + "', '"+
                    length + "')";
                    int result = stmt.executeUpdate(query);
                    stmt.close();
                
                }
                 catch(SQLException ex){
                    while (ex != null){
                   System.out.println("\nError:\n");
                   System.out.println("Message: " + ex.getMessage());
                   System.out.println("SQLState: " + ex.getSQLState());
                   System.out.println("Error Code: " + ex.getErrorCode());
                   ex = ex.getNextException();
                    System.out.println("ERROR WITH SQL");
                    
                }
                 }
                }
                
                
                else if (type.equals("drama")){
                    try{
                    Statement stmt = connect.createStatement();
                    
                    String query = "INSERT INTO DramaMovies (" +
                    "Title, Year, Type, Length" +
                    ") VALUES ('" +
                    title + "', '" +
                    year + "', '"+
                    format + "', '"+
                    length + "')";
                    int result = stmt.executeUpdate(query);
                    stmt.close();
                }
                 catch(SQLException ex){
                    while (ex != null){
                   System.out.println("\nError:\n");
                   System.out.println("Message: " + ex.getMessage());
                   System.out.println("SQLState: " + ex.getSQLState());
                   System.out.println("Error Code: " + ex.getErrorCode());
                   ex = ex.getNextException();
                    System.out.println("ERROR WITH SQL");
                }
                 }
                }
                
                else {System.out.println("something really went wrong");}
//End of Checking                

//Sending friendly message continued..
      out.println("<H1>Movie Database Updated</H1>\n" +
                    "<H1>An email has been sent to you for your records</H1>\n"+
                    "<H1>Thanks!</H1>\n" +
                    "</BODY></HTML>");             
//End of friendly message
      
//Sending Email describing how the database got updated
      
      //sendEmail(); UNCOMMENT THIS FIELD FOR EMAIL FUNCTIONALITY
            
      }
      
//End of doGet Method      
      
     
    
    //The following method was inspired by O'reilly's Java Networking
    //Programming 2nd Edition (Chapter 19, pg. 640)
    //Use of a working STMP email server is required for this method
    //to work properly
    
    /*public void sendEmail(){
        String message = "The following movie was added to the database\n" +
                         "Type: " + type + "\n" +
                         "Title: " + title + "\n" +
                         "Year: " + year + "\n" +
                         "Length: " + length + "\n" +
                         "Format: " + format + "\n";
        
        try {
            Properties prop  = new Properties();
            prop.put("mail.host", "your_stmp_goes_here"); //SMTP goes here
            
            Session mailConnection = Session.getInstance(prop, null);
            Message msg = new MimeMessage(mailConnection);
            
            Address myaddress = new InternetAddress("YOURNAME@YourMail.com", "YourName");
            Address sendingTo = new InternetAddress("SENDERSNAME@YourMail.com", "OtherPersonsName");
            
            msg.setContent(message, "text/plain");
            msg.setFrom(myaddress);
            msg.setRecipient(Message.RecipientType.TO, sendingTo);
            msg.setSubject("Movie Database Update");
            
            Transport.send(msg);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        
        
    }*/
}

//End of class MovieOnline

HTML FORM

<html>
<head><title>Database Test</title></head>
<body>

Choose a Movie Category<br>
<form action = "http://localhost:8080/MyServlets/servlet/MovieOnline";>
<dl>
<dd><input type = "radio" name = "category" value = "comedy">
Comedy
<dd><input type = "radio" name = "category" value = "action">
Action
<dd><input type = "radio" name = "category" value = "drama">
Drama
</dl>

Title: <input type = "text" name = "title"><br>
Year:  <input type = "text" name = "year"><br>
Format: <input type = "text" name = "format"><br>
Length: <input type = "text" name = "length"><br>
<br>
<input type = "submit"><br><br>
**Format means what type of movie DVD or VHS
**Length in minutes
</form>
 

Back to Java FAQ Index
Back to Java Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close