HTTP POST从javascript到java servlet

如何通过JavaScript将参数发布到Java Servlet?

这是我的html代码,它有效:

现在,我想用这样的东西哈希密码和POST到/ login hashPassword:

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

我曾尝试使用AJAX,JQuery,但这些解决方案与/ login有问题,因为他们在浏览器中调用localhost:8080 /?登录,而我想调用Java Servlet:web.xml

  LoginServlet pl./*...*/.LogoutServlet   LoginServlet /login/*  

我承认我的答案部分是预感(因为很久以前我写过它)但是使用JSP,你通常应该将表单操作命名为web.xml配置的servlet的名称

我认为你的web.xml应该是这样的:

  LoginServlet pl./*...*/.LogoutServlet   LoginServlet /login  

并将您的HTML更改为:

 

对于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响应

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

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

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