从javascript到Java servlet的HTTP POST [英] HTTP POST from javascript to java servlet

查看:72
本文介绍了从javascript到Java servlet的HTTP POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过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>

现在,我想使用以下方式对密码进行哈希处理并发布到/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,通常应将form action命名为name在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端,您将需要doPost()方法来捕获loginpasswordHash值等.

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响应的更多信息:使用jsp的json响应

How can I POST paramters via JavaScript to Java Servlet?

Here is my html code, which works:

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

<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

<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

I think your web.xml should be this:

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

<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 (using 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.

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

这篇关于从javascript到Java servlet的HTTP POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆