Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for access MySQL database into Servlet
Previous Home Next

This Servlet application, fetches Data and inserts it into MySQL database through Servlet.

Application directory structure

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <servlet>
    <servlet-name>MySQLServlet</servlet-name>
    <servlet-class>r4r.Servlet.MySQLServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>MySQLServlet</servlet-name>
     <url-pattern>/MySQLServlet</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
            30
    </session-timeout>
</session-config>
</web-app>

index.jsp

<%-- 
 Document: index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>r4r.co.in-index</title>
 </head>
 <body>
  <h1>Fetch and Insert data from MYSQL Database!</h1>

  <form action="MySQLServlet" method="POST">
   Enter PetName: <input type="text" name="name"
         value="" size="30" maxlength="10" /><br/>
   Enter OwnerName: <input type="text" name="ownername" 
        value="" size="30" maxlength="10" /><br/>
   Enter Species: <input type="text" name="species"
        value="" size="30" maxlength="10"/><br/>
   Enter Gender: <input type="radio" name="gender" 
              value="m" />Male
   <input type="radio" name="gender" value="f" />Female <br/>
   Birth Date: <input type="text" name="birth"
             value="" size="30" maxlength="10" />(0000-00-00)<br/>
   Death Data: <input type="text" name="death" 
             value="" size="30" maxlength="10" />(0000-00-00)<br/>
   <input type="submit" value="Insert Data" name="insert" />
   <input type="submit" value="Fetch Data" name="fetch" />
  
  </form> 
 </body>
</html>

Servlet Program

/*
 * Save as a MySQLServlet.java
 */
package r4r.Servlet;
import java.io.*;
import java.sql.*;
import java.util.logging.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
/**
 *
 * @author R4R
 */
public class MySQLServlet extends HttpServlet {

 private static Connection conn;

 @Override
 protected void doGet(HttpServletRequest request,
	   HttpServletResponse response)throws ServletException,IOException
{
 }

 @Override
 protected void doPost(HttpServletRequest request,
	   HttpServletResponse response)throws ServletException,IOException
{
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();

  // get value form TextField form index.jsp page
  String name = request.getParameter("name");
  String ownername = request.getParameter("ownername");
  String species = request.getParameter("species");
  String gender = request.getParameter("gender");
  String birth = request.getParameter("birth");
  String death = request.getParameter("death");
  String sql="INSERT INTOR4R.PET(name,ownername,species,gender,birth,death)"
 + " VALUES ('?', '?', '?', '?', '?', '?')";

  try {
if (request.getParameter("insert") != null) {
 conn = null;
 Class.forName("com.mysql.jdbc.Driver").newInstance();
 conn = DriverManager.getConnection
	   ("jdbc:mysql://localhost", "root", "root");
 if (!conn.isClosed()) {
  PreparedStatement ps = conn.prepareStatement(sql);
  ps.setString(1, name);
  System.out.println(name);
  ps.setString(2, ownername);
  ps.setString(3, species);
  ps.setString(4, gender);
  ps.setString(5, birth);
  ps.setString(6, death);
  ps.executeQuery();
  out.println("Data Sucessfully insert into database");
  out.println("<BR><a href=\"index.jsp\">Return to index page</a>");

 } else {
  throw new ServletException("SQL connection won't be open");
 }
} else {
 out.println("<html>");
 out.println("<head>");
 out.println("<title>" + getServletInfo() + "</title>");
 out.println("</head>");
 out.println("<body>");
 out.println("<h1>Fetch Data from Database</h1>");
 out.println("<table border=\"1\"cellspacing=\
                  "2\" cellpadding=\"2\">");
 out.println("<thead><tr>");
 out.println("<td> Id </td>");
 out.println("<td> PetName </td>");
 out.println("<td> Ownername </td>");
 out.println("<td> species </td>");
 out.println("<td> gender </td>");
 out.println("<td> Birth </td>");
 out.println("<td> Death </td>");
 out.println("</thead></tr>");

 conn = null;
 Class.forName("com.mysql.jdbc.Driver").newInstance();
 conn = DriverManager.getConnection
	       ("jdbc:mysql://localhost", "root", "root");
 if (!conn.isClosed()) {
  java.sql.Statement s = conn.createStatement();
  //get the number of record from table
  ResultSet count = s.executeQuery("select count(*) from R4R.PET");
  count.next();
  out.printf("Total (%d) result found into table", count.getInt(1));
  //get records from table
  ResultSet rs = s.executeQuery("select *from R4R.PET");
  while (rs.next()) {
out.println("<tbody><tr>");
out.println("<td> " + "<I><b>" 
	                + rs.getInt(7) + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>" 
	                + rs.getString("name") + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>"
                    + rs.getString("ownername") + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>"
                    + rs.getString("species") + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>"
                    + rs.getString("gender") + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>"
                    + rs.getString("birth") + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>" 
	                + rs.getString("death") + "</I></b>" + "</td>");
out.println("</tr></tbody>");
  }
 } else {
  throw new ServletException("SQL connection won't be open");
 }
 out.println("</table>");
 out.println("</body>");
 out.println("</html>");
 out.println("<BR><a href=\"index.jsp\">Return to index page</a>");
}
  } catch (Exception ex) {
Logger.getLogger(MySQLServlet.class.getName()).log(Level.SEVERE, 
  "Exception Generate while processing SQL request", ex);
  } finally {
try {
 //Free all resource
 conn.close();
 out.flush();
 out.close();
} catch (SQLException ex) {
 Logger.getLogger(MySQLServlet.class.getName()).log(Level.SEVERE, 
"SQLException generate while close SQL connection", ex);
}
  }
 }

 @Override
 public String getServletInfo() {
  return "r4r.co.in-MySQLServlet";
 }
}

Test program

/*
 * Save as a MySQLDAOMain.java
 * 
 * This class is only for test purpose
     (fetch data from database and display over server console)
 */
package r4r.Servlet;

import java.sql.*;

/**
 *
 * @author R4R
 */
public class MySQLDAOMain {

 private static Connection conn;

 public static void main(String[] args) throws Exception {
  try {
// Creates a new instance of the Class object
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Load the driver classes and establish a connection to database
conn = DriverManager.getConnection
	  ("jdbc:mysql://localhost", "root", "root");
//Check connection is open
if (!conn.isClosed()) {
 System.out.println("Connect with SQL Server");
//Creates a Statement object for sending SQL statements to the database
 Statement s = conn.createStatement();
 /*
  * Get the number of record from table
  */
 ResultSet count = s.executeQuery("select count(*) from R4R.PET");
 count.next();
 System.out.printf("Total (%d) result found into table", 
	          count.getInt(1));
 /*
  * Get the record from table 
  */
 ResultSet rs = s.executeQuery("select *from R4R.PET");
 while (rs.next()) {
  System.out.println(rs.getInt(7) + "|" 
	   + rs.getString("name") + "|" + rs.getString("ownername")
 + "|" + rs.getString("species") + "|" 
	  + rs.getString("gender") + "|" + rs.getString("birth")
 + "|" + rs.getString("death"));
 }
} else {
 System.err.println("Can't connect with MySQL server");
}
  } finally {
conn.close(); //close connection
  }
 }
}
Output of Program
Previous Home Next