Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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="EnterpriseCWEverything\src\coursework\Servlet2.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.

like image 646
London Student Avatar asked Mar 22 '11 15:03

London Student


People also ask

How does servlet read HTML form data?

Reading Form Data using Servlet getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames() − Call this method if you want a complete list of all parameters in the current request.


1 Answers

To convert String to java.util.Date, use SimpleDateFormat as answered by Gursel.

String string = "2011-03-22";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(string);

To convert java.util.Date to java.sql.Date, just use its constructor.

preparedStatement.setDate(index, new java.sql.Date(date.getTime()));

Casting ain't going to work since SimpleDateFormat doesn't return an instance of java.sql.Date.

like image 117
BalusC Avatar answered Sep 28 '22 20:09

BalusC