javascript - 将变量作为请求对象的一部分而不是 JSP 中的表单字段发送

标签 javascript html jsp

我承认,我是 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/

相关文章:

javascript - 如何正确使用 <%= link_to %> 的转义 javascript?

javascript - 我如何知道我点击了 HTML 中的哪个链接

java - 未使用过滤器和 ByteArrayOutputStream 写入响应

java - JSP 仅打印为纯文本

java - Struts 2 "<s:if>"标签无法按预期工作

javascript - Codrops 多级推送菜单的重复 javascript

javascript - Service Worker 从缓存中获取然后更新缓存

javascript - echo 中的 PHP 提交按钮可以做一些 javascripting

css - 导航按钮下的下拉菜单 css/html

javascript - 客户端事件库 (asp.net)