【问题标题】:How to send Client's Timestamp to Servlet?如何将客户端的时间戳发送到 Servlet?
【发布时间】:2015-09-08 05:41:59
【问题描述】:

我正在尝试获取提交 HTML 表单时客户端计算机的时间。目前我在 servlet 中使用它,但它会产生时区问题。所以为了摆脱这种情况,我决定在客户端机器中找到Timestamp,并在提交表单时将其发送到服务器。下面是我的代码

JSP

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <script>
            function time()
            {
                 var elem = document.getElementById("hiddenTxt");
                 elem.value = Date.now();
            }
        </script>
    </head>
    <body>


        <form action="TimestampClass" method="post">
            Name: <input type="text" name="nameTxt">
            <input type="hidden" name="hiddenTxt" id="hiddenTxt" onsubmit="time()">
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

Servlet

package test;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

/**
 *
 * @author Yohan
 */
public class TimestampClass extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

//        long currentTimeMillis = System.currentTimeMillis();
//        Timestamp timestamp = new Timestamp(currentTimeMillis);
//        System.out.println(currentTimeMillis);
//        System.out.println(timestamp);

        String name = request.getParameter("nameTxt");
        long timeStamp = Long.parseLong(request.getParameter("hiddenTxt"));

        PrintWriter out = response.getWriter();
        out.println(name);
        out.println(timeStamp);


        }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

但是它不起作用,NumberFormatException 被抛出用于时间戳字段。那么,如何正确地将客户端的时间戳发送到 servlet 并在那里处理呢?

我不知道这个异常是否有帮助,因为我确信它正在发生,因为没有任何东西被传递给 servlet。不管怎样,它在下面

Sep 08, 2015 11:09:01 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [TimestampClass] in context with path [/ForTesting] threw exception
java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:601)
    at java.lang.Long.parseLong(Long.java:631)
    at test.TimestampClass.processRequest(TimestampClass.java:41)
    at test.TimestampClass.doPost(TimestampClass.java:76)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

  • "request.getParameter("hiddenTxt")" 的输出是什么..?在此处发布您的例外情况..
  • 好的,它清楚地表明您的“request.getParameter("hiddenTxt")”返回一个空字符串 (""),并且您正在将其解析为 Long 值。所以你会得到 NumberFormatException。

标签: javascript java jsp servlets timestamp


【解决方案1】:

在表单元素上添加提交回调

<form action="TimestampClass" method="post" onsubmit="time()">
                Name: <input type="text" name="nameTxt">
                <input type="hidden" name="hiddenTxt" id="hiddenTxt" >
                <input type="submit" value="Submit">
            </form>

【讨论】:

  • 不幸的是 Javascript 时间也显示了服务器时间
  • 可能是您在同一台机器或同一时区运行客户端和服务器
  • 不,不是。服务器在亚马逊,我的时区不同
【解决方案2】:

我认为您的time() 函数中需要一个return

function time() {
    return (new Date()).getTime()
}

我认为您还需要在 hiddenTxt 字段中添加 value=[time value] 属性。可能是为什么 POST 参数当前是一个空字符串。

【讨论】:

    【解决方案3】:

    您的 "request.getParameter("hiddenTxt")" 返回一个空字符串 (""),您将其解析为 Long 值。所以你会得到 NumberFormatException。

    让我们从您的 JSP 开始..尝试以下操作:

    <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
    
            <script>
                function time()
                {
                   document.getElementById("hiddenTxt").value = Date.now();
                   document.getElementById('theForm').submit(); 
                }
            </script>
        </head>
        <body>
    
    
            <form action="TimestampClass" method="post" name="theForm">
                Name: <input type="text" name="nameTxt">
                <input type="hidden" name="hiddenTxt" id="hiddenTxt" onsubmit="time()">
                <input type="button" value="Submit" onclick="time();">
            </form>
        </body>
    

    这将设置客户端时间并在提交按钮单击时提交表单。

    在将其转换为 long 之前,请检查 null:

    PrintWriter out = response.getWriter();
    long timeStamp = 0;
    String timeVal = request.getParameter("hiddenTxt");
    try{
         if(("").equals(timeVal) && timeVal != null){
           timeStamp = Long.parseLong(timeVal);
         }
          out.println(name);
          out.println(timeStamp);
        }catch(NumberFormatException e){
           e.printStackTrace();
        }
    

    这样你就可以摆脱 NFException.

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2011-07-22
      • 2014-04-12
      • 2018-10-27
      • 2018-01-02
      • 1970-01-01
      • 2019-01-17
      • 2012-01-27
      • 1970-01-01
      相关资源
      最近更新 更多