5

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>
DivinaProportio
  • 220
  • 1
  • 3
  • 13
  • The problem with this question is that you modified it after edit to be totally different question, actually, it is now 2 different questions. At first part you are requiring usage of passwordHash before form submit and at second part you are now using plain input values. First one would require tweaking with javascript and other doesnt. Make separate questions, this is madness – Mauno Vähä Apr 01 '14 at 14:51
  • Ok, you have right! ;-) – DivinaProportio Apr 01 '14 at 14:56

2 Answers2

3

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

Community
  • 1
  • 1
Mauno Vähä
  • 9,340
  • 3
  • 26
  • 52
  • After executing this code, I recive: GET http://localhost:8080/login?login=admin&passwordHash=21232f297a57a5a743894a0e4a801fc3 405 (HTTP method GET is not supported by this URL) jquery-1.10.2.js:8706 – DivinaProportio Apr 01 '14 at 13:40
  • Can you show your java code which is most likely the doPost() method, it might be the problem – Mauno Vähä Apr 01 '14 at 13:42
  • At first glance, you are using not using login and passwordHash to get attributes and that error is at least mentioned in http://stackoverflow.com/questions/5879529/http-method-get-is-not-supported-by-this-url and http://stackoverflow.com/questions/5370633/405-http-method-get-is-not-supported-by-this-url try to remove any code under capturing those parameters and just use System.out.println(); for them so you can narrow down the problem – Mauno Vähä Apr 01 '14 at 13:50
  • I somewhat understand what the problem is @DivinaProportio , your initial code did not state what kind of behavior you are looking for after processing request at Java. Therefore, if you want to redirect after using ajax post you need to respond with url from Java and let javascript to redirect to certain location. – Mauno Vähä Apr 01 '14 at 14:12
  • Update my answer to contain doPost() example with response to javascript – Mauno Vähä Apr 01 '14 at 14:41
  • Thanks a lot!! It works!! My mistake was caused by response.sendRedirect() instead of response.write(); Thanks for help! – DivinaProportio Apr 01 '14 at 16:19
  • @DivinaProportio no problem, glad that could help :) – Mauno Vähä Apr 01 '14 at 16:21
0

Have you tried jQuery POST method specifying your web.xml as url? You need also prevent the default submit event.

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

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

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

    });
}
Stefano Ortisi
  • 5,094
  • 2
  • 26
  • 39
  • Never seen anything like this with JSP, although I used to program it like six years ago.. have you ever tested that this works? – Mauno Vähä Apr 01 '14 at 12:28