Skip to content
Advertisement

Passing Date from an HTML form to a servlet to an SQL database

I have a problem getting an inputed date (yyyyMMdd) from an HTML form to a sql database via a servlet. The date from the form passes to the servlet as a string but then somehow I need to convert it to date for storing in the database.

I have tried a number of methods, date formatter etc.. A possible way of doing it is to convert it to a long and then format it however this seems like a slight bodge.

Any thoughts would be appreciated.

Okay this includes the code of the form and the servlet. I have left the buisness object out.

The form:

<html>
<head>
<title>Inputing Episode Into Sons Of Anarchy Database</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<h1>Add Sons Of Anarchy Episode to Database</h1>
<form name="sonsOfAnarchyForm" method="get" action="EnterpriseCWEverythingsrccourseworkServlet2.java">
  <p>Season Number: 
    <input name="seasonNumber" type="text" id="seasonNumber">
  </p>
  <p>Season Episode Number: 
    <input name="seasonEpisodeNumber" type="text" id="seasonEpisodeNumber">
  </p>
  <p>Series Episode Number: 
    <input name="seriesEpisodeNumber" type="text" id="seriesEpisodeNumber">
  </p>
    <p>Episode Title: 
    <input name="title" type="text" id="title">
  </p>
    <p>Written By: 
    <input name="writtenBy" type="text" id="writtenBy">
  </p>
    <p>DirectedBy: 
    <input name="directedBy" type="text" id="directedBy">
  </p>
    <p>Original Air Date (YYYY-MM-DD): 
    <input name="origionalAirDate" type="text" id="origionalAirDate">
  </p>
    <p>Viewing Figures US (Millions): 
    <input name="viewingFigures" type="text" id="viewingFigures">
  </p>  
  <p>
    <input name="addEpisode" type="submit" value="Add Episode">
  </p>
</form>
</body>
</html>

The Servlet: (Sorry tried using the code samle facility but for whatever reason it was not loving it.)

    package coursework;

import javax.servlet.*;
import java.util.Date;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class Servlet2 extends HttpServlet
{

    public void doGet (HttpServletRequest rq, HttpServletResponse rp) throws ServletException, IOException
    {
        rp.setContentType("text/html");
        PrintWriter out = rp.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE> Insert - Test </TITLE></HEAD>");
        out.println("<BODY>");
        try 
        {
            ArrayList<Episode> episodes;
            episodes = new ArrayList<Episode>();
            String url = "jdbc:mysql://localhost:3306/sons_of_anarchy";
            String driver = "com.mysql.jdbc.Driver";
            Class.forName(driver);          
            Connection connection = DriverManager.getConnection(url,"root","password");
            
            // Convert string to date
            //String temp1;
            //long temp;
            //temp = Long.parseLong(rq.getParameter("origionalAirDate"));
            //temp1 = rq.getParameter("origionalAirDate");
            
            //Problem Code................................................
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = formatter.parse(rq.getParameter("origionalAirDate"));
            
            //SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); 
            //Date date = formatter.format(rq.getParameter("origionalAirDate"));

            

            // Set the new instance of the episode row
            Episode temp;
            episodes.add(temp = new Episode(Integer.parseInt(rq.getParameter("seasonNumber")), Integer.parseInt(rq.getParameter("seasonEpisodeNumber")), Integer.parseInt(rq.getParameter("seriesEpisodeNumber")), rq.getParameter("title"), rq.getParameter("directedBy"), rq.getParameter("writtenBy"), date , Float.parseFloat(rq.getParameter("viewingFigures"))));
            PreparedStatement editStatement = connection.prepareStatement("INSERT into episode_guide");
            // Put in database
            editStatement.setInt(1, temp.getSeasonNumber());
            editStatement.setInt(2, temp.getSeasonEpisodeNumber());
            editStatement.setInt(3, temp.getSeriesEpisodeNumber());
            editStatement.setString(4, temp.getTitle());            
            editStatement.setString(5, temp.getDirectedBy());
            editStatement.setString(6, temp.getWrittenBy());
            editStatement.setDate(7, (java.sql.Date) temp.getOrigionalAirDate());
            editStatement.setFloat(8, temp.getViewingFigures());
            
            editStatement.executeUpdate();
            editStatement.close();
            connection.close();
            
            // Print out new entry
            int i = 0;
            while(i < episodes.size()){
            out.print(episodes.get(i).getSeasonNumber()+
                    "t"+ episodes.get(i).getSeasonEpisodeNumber()+
                    "t"+ episodes.get(i).getSeriesEpisodeNumber() +
                    "t"+ episodes.get(i).getTitle()+
                    "t"+ episodes.get(i).getDirectedBy()+
                    "t"+ episodes.get(i).getWrittenBy()+
                    "t"+ episodes.get(i).getOrigionalAirDate()+
                    "t"+ episodes.get(i).getViewingFigures());
            
            out.print("<br>");
            i++;
            }
        } 
        catch (Exception e) 
        {
            out.println("Error" + e);
        }
        out.println("<H3> Basic Insert Servlet </H3>");
        out.println("Result...");
        out.println("</BODY></HTML>");
    }
}

Sorry for the extended dribble but in context maybee it makes more sense.

Advertisement

Answer

            ArrayList<BuisnessObject> episodes;
        episodes = new ArrayList<BuisnessObject>();
        String url = "jdbc:mysql://localhost:3306/sons_of_anarchy";
        String driver = "com.mysql.jdbc.Driver";
        Class.forName(driver);          
        Connection connection = DriverManager.getConnection(url,"root","password");


        BuisnessObject newEpisode;

        // Takes the date from the form in String and converts it java.util.date which is how the buisness object is written
        java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(rq.getParameter("origionalAirDate")); 

        // Creates an instance of the buisness object
        episodes.add(newEpisode = new BuisnessObject(Integer.parseInt(rq.getParameter("seasonNumber")), Integer.parseInt(rq.getParameter("seasonEpisodeNumber")), Integer.parseInt(rq.getParameter("seriesEpisodeNumber")), rq.getParameter("title"), rq.getParameter("directedBy"), rq.getParameter("writtenBy"), date, Float.parseFloat(rq.getParameter("viewingFigures"))));
        PreparedStatement editStatement = connection.prepareStatement("INSERT into episode_guide VALUES (null,?,?,?,?,?,?,?,?)");

        // Takes date from java.util.date and converts it to java.sql.date
        java.sql.Date mySqlDate = new java.sql.Date(newEpisode.origionalAirDate.getTime());


        editStatement.setInt(1, newEpisode.getSeasonNumber());
        editStatement.setInt(2, newEpisode.getSeasonEpisodeNumber());
        editStatement.setInt(3, newEpisode.getSeriesEpisodeNumber());
        editStatement.setString(4, newEpisode.getTitle());          
        editStatement.setString(5, newEpisode.getDirectedBy());
        editStatement.setString(6, newEpisode.getWrittenBy());
        editStatement.setDate(7, mySqlDate);
        editStatement.setFloat(8, (float) newEpisode.getViewingFigures());

        editStatement.executeUpdate();
        editStatement.close();
        connection.close();

Several hours later and it works… Thanks

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement