1

使用下面的代码,我想问一下如何传递来自文本字段的“日期”参数。我打算使用 DAO 和 servlet 创建一个简单的日期范围查询。我可以使用此代码显示所有列,但是我想使用 Date 过滤...

这是我的代码:

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);
        }
    }

}

和我的 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;
    }
}
4

2 回答 2

3

用于HttpServletRequest#getParameter()收集请求参数。假设输入字段的名称为date

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

用于SimpleDateFormat#parse()将其转换为java.util.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;
}

将此作为方法参数传递给您的 DAO 方法:

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

您需要将其转换为java.sql.Date,以便您可以PreparedStatement#setDate()在 SQL 查询中使用它来设置它:

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

您可以使用WHERE date > ?搜索比给定日期新的记录,或WHERE date < ?搜索比给定日期更旧的记录,或WHERE date BETWEEN ? and ?搜索指定日期之间的记录。

于 2012-05-21T19:03:40.117 回答
0

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.            

}
于 2012-05-21T18:35:15.747 回答