<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>我的jsp项目</title>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
span{
color:red;
}
</style>
</head>
<body>
<c:choose>
<c:when test="${param.code == '10001'}">
<div style="color:red">用户名或密码错误</div>
</c:when>
<c:when test="${param.code == '10003' }">
<div style="color:red">验证码错误</div>
</c:when>
<c:otherwise>
xxxx
</c:otherwise>
</c:choose>
<form action="login.jspx" method="post" id="myform">
UserName: <input type="text" name="username"/><span id="name_error"></span> <br/>
Password: <input type="password" name="password"/><span id="pwd_error"></span> <br/>
验证码:<input type="text" name="captcha"/>
<a href="javascript:;" if="changeVailidata"> <img src="jcaptcha.jpg" id="jcaptcha"></a>
<input type="submit" value="Login" id="btn"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#changeVailidata").click(funcition()){
$("#jcaptchar").attr("src","jcaptcha.jpg");
})
$("#btn").click(function(){
var name = $("input[name='username']").val();
var pwd = $("input[name='password']").val();
if(name.trim() == "") {
$("#name_error").html("请输入用户名");
return;
}
if(pwd == "") {
$("#pwd_error").html("请输入密码");
return;
}
$("#myform").submit();
});
});
</script>
</body>
</html>
这里写的验证码用的是jcaptcha插件;到网上可以下载到他的jar包;
以上是验证码配合登陆时,在jsp中的写法;
下面是当在servlet中接受验证码:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String captcha = request.getParameter("captcha");//接受jsp中传过来的验证码;
//这里必须这么写才能生成验证码;jcaptcha的官网里面有详细的介绍;
if (SimpleImageCaptchaServlet.validateResponse(request, captcha)) {
String name = request.getParameter("username");
String pwd = request.getParameter("password");
//服务端的验证
if(name == null || pwd == null) {
response.sendRedirect("index.jsp");
return;
}
System.out.println("Name:" + name + "\tpwd:" + pwd);
//2.验证用户名和密码是否正确
UserDao dao = new UserDao();
User user = dao.findByNameAndPwd(name, pwd);
if(user != null) {
//Servlet中获取session
HttpSession session = request.getSession();
session.setAttribute(Const.USER_IN_SESSION, user);
response.sendRedirect("prod.jspx");// 登陆成功,重定向跳转到prod.jspx;
} else {
response.sendRedirect("index.jspx?code=10001");
}
}else {
response.sendRedirect("index.jspx?code=10003");
}
}
}