如何处理作为参数发送到Servlet的空白日期

时间:2016-01-12 14:55:11

标签: java servlets

我正在编写一个webapp,其中有日期要发送到Servlet,我想发送一些空白日期,并根据这些日期我想构建一个查询。但是我的问题是当我传递参数,即日期工作正常时,当我发送空白参数时,它会向我发出以下错误。

Start date got is  and end date is //Here I'm checking the output
Unparseable date: "" servlet Errotr

当我在控制台中显示日期时,将其显示为 Start date got is (TheStartDateValue) and end date is (TheEndDateValue)  并且没有例外(因为日期被解析)。以下是我的代码。

public class Controller extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            /* Date Start */
            String startDateStr = request.getParameter("startDate");
            String endDateStr = request.getParameter("endDate");
            System.out.println("Start date got is " + startDateStr + " and end date is " + endDateStr);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat print = new SimpleDateFormat("yyyy-MM-dd");
            Date startParsedDate = null, endParsedDate = null;
            String startDate = null, endDate = null;
            if (!startDateStr.equals(null) || !startDateStr.equals("")) {
                startParsedDate = sdf.parse(startDateStr);
                startDate = print.format(startParsedDate);
            }
            if (!endDateStr.equals(null) || !endDateStr.equals("")) {
                endParsedDate = sdf.parse(endDateStr);
                endDate = print.format(endParsedDate);
            }

            System.out.println(startDate + " value and " + endDate);
            /* Date End */
            DataDao dataDao = new DataDao();
            ArrayList<UserBean> list = dataDao.getFrameWork(startDate, endDate);
            String searchList = new Gson().toJson(list);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(searchList);
            System.out.println("servlet Done");
        } catch (Exception e) {
            System.err.println(e.getMessage() + " servlet Errotr");
        }
    }

如果输入值为startDateStr或使用上面代码中的下面的块有一些值,我正在尝试处理startDateStrnull chweck。

if (!startDateStr.equals(null) || !startDateStr.equals("")) {
        startParsedDate = sdf.parse(startDateStr);
        startDate = print.format(startParsedDate);
}
if (!endDateStr.equals(null) || !endDateStr.equals("")) {
        endParsedDate = sdf.parse(endDateStr);
        endDate = print.format(endParsedDate);
}

请让我知道我哪里出错了,我该怎么办呢。

由于

1 个答案:

答案 0 :(得分:1)

问题是条件!startDateStr.equals(null) || !startDateStr.equals(""),您应该将其更改为startDateStr != null && !startDateStr.equals(""),同样的问题是第二种情况。