【问题标题】:How can i access the parameter which are sent using the get method? [duplicate]如何访问使用 get 方法发送的参数? [复制]
【发布时间】:2020-04-27 23:38:50
【问题描述】:

我正在尝试将位置数据从 javascript 发送到我的 servlet 并及时将其存储在数据库中。我一直在获取 null 如何访问我的参数?

NewFile.html

<script>
    $(document).on("click", "#somebutton", function() {
        if (navigator.geolocation) {

            navigator.geolocation.watchPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }

        function showPosition(position) {
            console.log(position)

            var params = {
                lat : position.coords.latitude,
                lng : position.coords.longittude
            };

            $.get("someservlet", $.param(params), function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
            });

        }

    });
</script>

servlet.java

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



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String text = "some text";
       String params= request.getParameter("params");
        System.out.println(params);
    }

}

【问题讨论】:

  • 您可能想使用 Post 而不是 Get,但不确定这是为什么您获得 Null 值的主要原因,但从那开始。然后从浏览器网络工具中检查哪些数据以及实际发送到后端的方式。我对 java servlet 不熟悉,所以无法仅给出这些小技巧的答案。
  • 感谢@maximelian1986,但我也在 servlet 中使用 get 方法,所以这方面没有问题!我只需要在获取信息后访问它

标签: javascript java jquery servlets


【解决方案1】:

您的 Servlet:

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


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String text = "some text";
        System.out.println(String.format("Lat: %s Long: %s", request.getParameter("lat"), request.getParameter("lng")));
    }

}

建议你关注naming conventions

类名应该是名词,大小写混合,每个内部单词的首字母大写。尽量保持你的类名简单和描述性。使用完整的单词,避免使用首字母缩写词和缩写词(除非缩写词比长格式更广泛地使用,例如 URL 或 HTML)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    相关资源
    最近更新 更多