如何发送客户端's时间戳到Servlet

How to send Client's Timestamp to Servlet?

本文关键字:时间戳 Servlet 何发送 客户端      更新时间:2023-09-26

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

<<p> JSP/strong>
<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)

为表单元素添加submit回调

<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>

我认为在您的time()功能中需要一个return

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

我认为你还需要一个value=[time value]属性在你的hiddenTxt字段。这可能是POST参数当前为空字符串的原因。

您的"request.getParameter("hiddenTxt")"返回一个空字符串("),您正在将其解析为长值。所以你会得到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之前,检查是否为空:

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。