简体   繁体   English

从 javascript 到 java servlet 的 HTTP POST

[英]HTTP POST from javascript to java servlet

How can I POST paramters via JavaScript to Java Servlet?如何通过 JavaScript 将参数发布到 Java Servlet?

Here is my html code, which works:这是我的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>

And now, I want to hash password and POST to /login hashPassword with something like this:现在,我想对密码进行哈希处理并 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>

I'd tried to use AJAX, JQuery but those solutions has problems with /login, because they call localhost:8080/?login in browser while I want to call Java Servlet: web.xml我曾尝试使用 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>

I admit that my answer this is partly a hunch (because it was long time ago I wrote it) but with JSP you should typically name form action to be name of the servlet configured in web.xml我承认我的回答部分是一种预感(因为它是很久以前我写的)但是对于 JSP,您通常应该将表单操作命名为web.xml中配置的 servlet 的名称

I think your web.xml should be this:我认为你的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>

And change your HTML to this:并将您的HTML更改为:

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

For the JavaScript part if you submit form with jQuery you can modify your parameters which to post and omit posting of password (because it should not be needed if you want to post it as hashed) see below code for usage:对于 JavaScript 部分,如果您使用 jQuery 提交表单,您可以修改要发布的参数并省略密码的发布(因为如果您想将其发布为散列形式,则不需要它),请参见下面的使用代码:

JavaScript (using 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");

            }

        }
    });

});    

Finally, at Java side you will need doPost() method which captures login and passwordHash value etc.最后,在 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");

}

Read more about using json response: json response with jsp阅读有关使用 json 响应的更多信息: json response with jsp

Have you tried jQuery POST method specifying your web.xml as url?您是否尝试过将您的 web.xml 指定为 url 的 jQuery POST 方法? You need also prevent the default submit event.您还需要阻止默认提交事件。

https://api.jquery.com/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