我承认我的回答在一定程度上是一种预感(因为我很久以前就写了它),但是对于 JSP,您通常应该将表单操作命名为配置的 servlet 的名称web.xml
我认为你的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()
捕获的方法login
and passwordHash
值等
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 响应