toink
toink

Reputation: 255

passing Date parameter to create date range query

Using the codes below I would like to ask how can I pass a "Date" parameter coming from a text field. I am planning to create a simple date range query using DAO and servlet. I can display all columns using this codes however I want to filter in using Date...

here's my code:

My Servlet




package source;

import java.io.*;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 *
 * @author jaypee.martinez
 */
public class parseServlet extends HttpServlet {

    private parseDAO parseDAO;


    @Override
    public void init() throws ServletException {
        String driver = "org.postgresql.Driver";
        String url = "jdbc:postgresql://localhost5432/mydb";
        String username = "postgres";
        String password = "secret";


        Database database = new Database(driver, url, username, password);
        this.parseDAO = new parseDAO(database);
    }


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


            try {

            List<parseBean> parse_array = parseDAO.results();

            request.setAttribute("parse_array", parse_array);
            request.getRequestDispatcher("results.jsp").forward(request, response);
        }
            catch (SQLException e) {
            throw new ServletException("Cannot retrieve areas", e);
        }
    }

}

and My DAO

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package source;

import java.sql.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class parseDAO {

    private Database database;

    public parseDAO(Database database) {
        this.database = database;
    }

    public List<parseBean> results() throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<parseBean> parse_array = new ArrayList<parseBean>();
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");

        try {
            connection = database.getConnection();
            statement = connection.prepareStatement("select * from dateparse");


            resultSet = statement.executeQuery();


            while (resultSet.next()) {
                parseBean parsearray = new parseBean();
                parsearray.setDate(resultSet.getDate("date"));
                parsearray.setName(resultSet.getString("name"));
                parsearray.setAddress(resultSet.getString("address"));
                parse_array.add(parsearray);
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
            if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
        }

        return parse_array;
    }
}

Upvotes: 1

Views: 29392

Answers (2)

mprabhat
mprabhat

Reputation: 20323

In your doGet you will get the value from request

String dateFromTxt = request.getParameter("DateFromTxtField");

Pass this to your dao's results method

then your results method may look like this :

public List<parseBean> results(String filterDate) throws SQLException {

   String query = "select * from dateparse where date = ? ";

   // get connection and prepare statement, also format the incoming date as per your database requirement then say you store this in variable myFormattedDate

   statement.setDate(1, myFormattedDate);

   // Execute query and fetch result.            

}

Upvotes: 0

BalusC
BalusC

Reputation: 1108722

Use HttpServletRequest#getParameter() to collect request parameters. Assuming that the input field has the name date.

String dateString = request.getParameter("date");

Use SimpleDateFormat#parse() to convert it to java.util.Date using a specific pattern, depending on how the enduser was asked to enter the date.

Date date = null;

try {
    date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
}
catch (ParseException e) {
    // Show error message to enduser about the wrong format and forward back to the JSP with the form.
    request.setAttribute("error", "Invalid format, please enter yyyy-MM-dd");
    request.getRequestDispatcher("search.jsp").forward(request, response);
    return;
}

Pass this as a method argument to your DAO method:

List<ParseBean> results = parseDAO.search(date);

You need to convert it to java.sql.Date, so that you can use PreparedStatement#setDate() to set it on the SQL query:

String query = "SELECT * FROM dateparse WHERE date = ?";
// ...
statement.setDate(1, new java.sql.Date(date.getTime()));

You can use WHERE date > ? to search for records newer than the given date, or WHERE date < ? to search for records older than the given date, or WHERE date BETWEEN ? and ? to search for records between the specified dates.

Upvotes: 3

Related Questions