所以,我目前有一個問題,我有一個表單,其中包含兩個用戶名和密碼輸入,一個驗證碼(<div>
)和 submit
類型的行爲作爲一個按鈕。當這個提交按鈕被擊中時,我希望它檢查驗證碼以查看它是否爲空。如果它不是空的,我希望它調用驗證用戶的其他Java代碼。如何調用與jsp相同形式的java代碼和javascript代碼
我的JSP形式如下:
<html>
<head>
<!-- more scripts/google api js are here -->
<script type="text/javascript">
function get_action(form) {
var v = grecaptcha.getResponse();
if(v.length === 0) {
document.getElementById('captcha').innerHTML="Login failed: Empty captcha";
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<form action="login" method="post" onsubmit="return get_action(this);">
<input type="text" id="email" value="${fn:escapeXml(param.email)}" required>
<input type="text" id="password" value="${fn:escapeXml(param.password)}" required>
<div class="g-recaptcha" data-sitekey="xxx"></div>
<input class="submit_button" type="submit" name="submit" value="Submit" />
<span class="error"${error.invalid}</span>
<div id="captcha" class="captchaError"></div>
</form>
</body>
</html>
,這是應該做用戶的驗證如下:我登錄的servlet:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private LoginDAO loginDAO;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("login.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> error = new HashMap<String,String>();
request.setAttribute("error",error);
String email = request.getParameter("email");
String password = request.getParameter("password");
// Verify re-captcha
String gRecaptchaResponse = request.getParameter("captcha");
boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);
if(!verify) {
error.put("captcha","You seem to be a robot. Try to use the captcha again");
}
if(error.isEmpty()) {
loginDAO = new LoginDAO();
try {
List<Customer> customer = new ArrayList<Customer>();
customer = loginDAO.validate(email,password);
if(customer.isEmpty()) {
error.put("invalid","Invalid email or password");
}
if(error.isEmpty()) { // no errors, proceed
HttpSession session = request.getSession(true);
Customer user = customer.get(0);
session.setAttribute("user",user);
response.sendRedirect("main");
return;
}
request.getRequestDispatcher("login").forward(request,response);
} catch(SQLException e) {
throw new ServletException("Could not check login",e);
}
loginDAO.closeLoginDAO();
}
}
}
凡loginDAO只檢查用戶名和針對數據庫的密碼。
什麼是奇怪的是,昨晚一切工作正常。我做的唯一的事情就是將java文件移動到子目錄中。但我更新了web.xml
文件以確保沒有錯誤。
現在我有一種感覺form
的onsubmit=
部分正在搞java類。有誰知道用JavaScript和java進行表單驗證是正確的嗎?我不幸的是需要一些JavaScript的reCaptcha,否則用戶可以提交一個空的驗證碼。
在'doGet()'中,您轉發到'login.jsp'。在'doPost()'你轉發到'登錄'。不知道這是否是問題中的錯字,但可能會導致問題。附註:在進行轉發或重定向之前請注意關閉您的loginDAO資源。 – Tap