我在 jsp 文件中有一个登录页面,该文件也使用 jSTL,以及一个简单的 javascript 验证来检查其字段是否为空。
单击“登录”按钮时,它应该检查字段是否已满,如果为真,则将表单详细信息传递给 Dispatcher Servelet 并执行其余过程。
但是单击提交按钮时,JavaScript 会被完全忽略,因此如果存在空白字段,则会发生异常。 为什么会发生这种情况?
这是我使用过的代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>iLitmus Portal</title>
<link href="<c:url value="resources/css/login.css" />" rel="stylesheet" type="text/css" />
<link href="<c:url value="resources/css/common.css" />" rel="stylesheet" type="text/css" />
<link href="<c:url value="http://fonts.googleapis.com/css?family=Amaranth" />" rel="stylesheet" type="text/css" />
<link href="<c:url value="http://fonts.googleapis.com/css?family=Convergence" />" rel="stylesheet" type="text/css" />
<%@ include file="header.jsp" %>
</head>
<body >
<div id="portal_banner" align="center">
<img src="resources/images/logo-main.png" id="logo">
<p>Litmus iPortal</p>
</div>
<div id="loginbox">
<div align="center">
<h3 id="chngpass_title">Login</h3>
<form:form name="frm" method="post" action="login" onsubmit="return validateForm()" commandName="login">
<form:input type="text" path="emp_id" name="username" placeholder="Employee-ID"/><br>
<form:input type="password" path="password" name="pwd" placeholder="Password"/>
<br>
<input type="submit" value="Login">
<br>
<b> ${error} </b>
<p id="firstuser">If you are a first time user, please login with the predefined password. You will be directed to change your password and set up
a security question and answer.</p>
</form:form>
</div>
</div>
<script>
function validateForm()
{
if(document.frm.username.value==""&&document.frm.pwd.value!="")
{
alert("User Name should not be left blank");
return false;
}
else if(document.frm.pwd.value==""&&document.frm.username.value!="")
{
alert("Password should not be left blank");
return false;
}
else if(document.frm.pwd.value==""&&document.frm.username.value==""){
alert("Username and Password cannot be empty!");
return false;
}
return true;
}
</script>
</body>
</html>
我最初尝试将 javascript 代码放入外部 .js 文件中,但这不起作用,因此我尝试将其放入 jsp 页面中以检查是否有效。 我还尝试了类似于此逻辑的基于 jquery 的验证,但这也不起作用。
我正在使用 Tomcat 服务器在 Eclipse Juno 中执行此操作。
任何帮助将不胜感激!
最佳答案
我在不使用jsp的情况下尝试了你的代码<form>
标签,它在这个 FIDDLE 中工作正常.
此外,为了将表单绑定(bind)到表单 bean,您必须对这样的输入字段使用相同的 name 和 id 属性,
<input type="text" name="username" id="username" placeholder="Employee-ID"/>
<input type="password" name="pwd" id="pwd" placeholder="Password"/>
此外,在使用 jsp 标记时同时使用路径和名称属性并不是一个好的做法。将 javascript 代码放入 <head>
中的 fiddle 中标签。
更新
请使用与 path
相同的名称属性和 Servlet 类中的字段名称。例如,如果您给出 path
属性为emp_id
然后在您的 Servlet 中使用相同的名称。其他领域也是如此。
关于在 spring mvc 中实现的 jsp 文件中,Javascript 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26016918/