簡體   English   中英

從 javascript 到 java servlet 的 HTTP POST

[英]HTTP POST from javascript to java servlet

如何通過 JavaScript 將參數發布到 Java Servlet?

這是我的html代碼,它有效:

<div id="loginPanel">
<form action="/login" method="POST" class="form">
    <label>Login:</label>
    <input type="text" name="login" id="login">
    <label>Password:</label>
    <input type="text" name="password" id="password">
    <div id="loginLower">
        <input type="checkbox"><label memory="memory">Remember me</label>
        <input type="submit" value="Login">
    </div>
</form>
</div>

現在,我想對密碼進行哈希處理並 POST 到 /login hashPassword,如下所示:

<form onsubmit="post()">
    <label>Login:</label>
    <input type="text" name="login" id="login">
    <label>Password:</label>
    <input type="text" name="password" id="password">
    <div id="loginLower">
        <input type="checkbox"><label memory="memory">Remember me</label>
        <input type="submit" value="Login">
    </div>
</form>

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>

<script>
function post(){
 var passhash = CryptoJS.MD5(document.getElementById("password").value);
//post to /login login and passhash
}
</script>

我曾嘗試使用 AJAX、JQuery 但這些解決方案在 /login 方面存在問題,因為它們在瀏覽器中調用 localhost:8080/?login 而我想調用 Java Servlet: web.xml

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>pl./*...*/.LogoutServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login/*</url-pattern>
</servlet-mapping>

我承認我的回答部分是一種預感(因為它是很久以前我寫的)但是對於 JSP,您通常應該將表單操作命名為web.xml中配置的 servlet 的名稱

我認為你的web.xml應該是這樣的:

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>pl./*...*/.LogoutServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

並將您的HTML更改為:

<form action="LoginServlet" method="POST" class="form" id="loginForm">

對於 JavaScript 部分,如果您使用 jQuery 提交表單,您可以修改要發布的參數並省略密碼的發布(因為如果您想將其發布為散列形式,則不需要它),請參見下面的使用代碼:

JavaScript(使用 jQuery):

// Attach a submit handler to the form
$("#loginForm").submit(function( event ) {

    // Stop form from submitting normally
    event.preventDefault();

    // Get some values from elements on the page:
    var $form = $( this );

    // We want to customize what we post, therefore we format our data
    var data = "login="+ $('#login').val() +"&passwordHash=" + CryptoJS.MD5($('#password').val());

    // For debugging purposes... see your console:
    // Prints out for example: login=myLoginName&passwordHash=a011a78a0c8d9e4f0038a5032d7668ab
    console.log(data);

    // The actual from POST method
    $.ajax({
        type: $form.attr('method'),
        url:  $form.attr('action'),
        data: data,
        success: function (data) {
            console.log("Hey, we got reply form java side, with following data: ");
            console.log(data);

            // redirecting example..
            if(data === "SUCCESS") {

               window.location.replace("http://stackoverflow.com");

            }

        }
    });

});    

最后,在 Java 端,您將需要捕獲loginpasswordHash值等的doPost()方法。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String login = request.getParameter("login");
    String password = request.getParameter("passwordHash");

   //
   // Do what ever you want with login and passwordHash here...
   //

   // Because we are using ajax we need to respond to it stating whether we can redirect or not to new location, see lines below

   // Content type of the response - You could also return application/json for example (which would be better in this case)
   response.setContentType("text/plain"); // Using text/plain for example
   response.setCharacterEncoding("UTF-8");

   // Change this as you like - it can also be url or anything else you want...
   response.getWriter().write("SUCCESS");

}

閱讀有關使用 json 響應的更多信息: json response with jsp

您是否嘗試過將您的 web.xml 指定為 url 的 jQuery POST 方法? 您還需要阻止默認提交事件。

https://api.jquery.com/jQuery.post/

function post(e){
    e.preventDefault();

    $.post( "/web.xml" , you_data, function(data, textStatus, jqXHR){

    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM