我承认,我是 JSP 的初学者,因为我有 JavaScript 背景。
但据我了解,
当您在 JSP 表单中点击提交时,请求对象将通过表单字段传递到操作路径。
<form name="loginForm" method="POST" autocomplete="off" action="<%=(request.getContextPath())%>/Login.do" onsubmit="return validateLoginForm()">
.......
.......
<tr id="userNameRow">
<th id="usernameLabel">Username</th>
<td align="left">
<input name="username" id="username" autocomplete="off" type="text" aria-describedby="loginError"></td>
</tr>
<tr id="userPwdRow">
<th id="passwordLabel">Password</th>
<td align="left">
<input name="password" id="password" onKeyPress="decodeKeyPress(event)" autocomplete="off" type="password"></td>
</tr>
我想要的是,我不想将其存储在变量中并替换 pwd 字段中的文本,而不是在 pwd 字段中键入内容。
我认为字段上有 keypress
事件,以便我可以查找 keyCode 并最终重置字段值。
var pwdString = "";
function decodeKeyPress(event) {
var xCode = event.which || event.keyCode;
pwdString += String.fromCharCode(xCode);
console.log("My Key Press Code ---"+xCode);
var input = document.querySelector("input#password");
input.select();
input.value="";
}
现在,我想在 onSubmit 中传递变量 pwdString
值作为请求对象的一部分,而不是 pwd 字段值(重置为空字符串)。
这样在其他页面我可以将其读作
String password = (String) request.getParameter("password");
如何在 JSP 中实现?
最佳答案
要获取密码字段的值,您可以使用以下命令:
var pwdField = document.getElementById("password");
var pwdString;
pwdField.onChange(function(){//You can use keypress or keyup here
pwdString = pwdField.value;
});
提交时,可以使用ajax代替表单。示例如下:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/Login.do", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&password="+pwdString);
然后在java中,您可以使用String password = (String) request.getParameter("password");
注意: 由于字符串容易受到攻击且不安全,因此发送密码是因为可以随时从 DevTool 访问 JavaScript。所以尽量不要使用它。
关于javascript - 将变量作为请求对象的一部分而不是 JSP 中的表单字段发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51374560/