HTTP POST从javascript到java servlet

时间:2014-04-01 12:08:43

标签: java javascript jsp servlets

如何通过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 /?登录,而我想调用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>

2 个答案:

答案 0 :(得分:1)

我承认我的答案部分是预感(因为很久以前我写过)但是使用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端,您需要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响应的更多信息:json response with jsp

答案 1 :(得分:0)

您是否尝试过将jQuery POST方法指定为url? 您还需要阻止默认的提交事件。

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

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

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

    });
}