struts2+json+jquery局部刷新实现注册验证
1、项目需要导入的jar包
在web项目的WebRoot/WEB-INF/lib目录下导入以下包
2、在src目录下建立包com.entity,里面建立java类:UserInfo.java 、 MailSenderInfo.java
UserInfo.java
package com.entity; import java.io.Serializable; /** * 说明:用户实体类 * @author wangcunhuazi * */ public class UserInfo implements Serializable { private static final long serialVersionUID = 3952189513312630860L; private int userId; private String userName; private String password; private String email; private String phone; private String realName; private String idCard; private String birthday; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
MailSenderInfo.java
package com.entity; /** * 发送邮件需要使用的基本信息 */ import java.util.Properties; public class MailSenderInfo { // 发送邮件的服务器的IP和端口 private String mailServerHost; private String mailServerPort = "25"; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String toAddress; // 登陆邮件发送服务器的用户名和密码 private String userName; private String password; // 是否需要身份验证 private boolean validate = false; // 邮件主题 private String subject; // 邮件的文本内容 private String content; // 邮件附件的文件名 private String[] attachFileNames; /** * 获得邮件会话属性 */ public Properties getProperties(){ Properties p = new Properties(); p.put("mail.smtp.host", this.mailServerHost); p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); return p; } public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } public String getMailServerPort() { return mailServerPort; } public void setMailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] fileNames) { this.attachFileNames = fileNames; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String textContent) { this.content = textContent; } }
3、在src目录下建立包com.action,里面分别建立这几个java类:RegisterJsonAction.java 、 SendMessageAction.java 、 UserInfoAction.java
RegisterJsonAction.java
package com.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.entity.UserInfo; import com.opensymphony.xwork2.ActionSupport; public class RegisterJsonAction extends ActionSupport { private static final long serialVersionUID = 3518833679938898354L; private String userName; private String registerUserNameMess; private String email; private String registerEmailMess; private String emailIdentifyCode; private String emailIdentifyCodeMess; private String phone; private String registerPhoneMess; private String idCard; private String registerIdCardMess; private String identifyCode; private String registerIdeCodeMess; private UserInfo userInfo; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getRegisterUserNameMess() { return registerUserNameMess; } public void setRegisterUserNameMess(String registerUserNameMess) { this.registerUserNameMess = registerUserNameMess; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getRegisterEmailMess() { return registerEmailMess; } public void setRegisterEmailMess(String registerEmailMess) { this.registerEmailMess = registerEmailMess; } public String getEmailIdentifyCode() { return emailIdentifyCode; } public void setEmailIdentifyCode(String emailIdentifyCode) { this.emailIdentifyCode = emailIdentifyCode; } public String getEmailIdentifyCodeMess() { return emailIdentifyCodeMess; } public void setEmailIdentifyCodeMess(String emailIdentifyCodeMess) { this.emailIdentifyCodeMess = emailIdentifyCodeMess; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getRegisterPhoneMess() { return registerPhoneMess; } public void setRegisterPhoneMess(String registerPhoneMess) { this.registerPhoneMess = registerPhoneMess; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getRegisterIdCardMess() { return registerIdCardMess; } public void setRegisterIdCardMess(String registerIdCardMess) { this.registerIdCardMess = registerIdCardMess; } public String getIdentifyCode() { return identifyCode; } public void setIdentifyCode(String identifyCode) { this.identifyCode = identifyCode; } public String getRegisterIdeCodeMess() { return registerIdeCodeMess; } public void setRegisterIdeCodeMess(String registerIdeCodeMess) { this.registerIdeCodeMess = registerIdeCodeMess; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public void initUserInfo() { UserInfo userInfo1 = new UserInfo(); userInfo1.setUserId(1); userInfo1.setUserName("zhangsan"); userInfo1.setPassword("12345"); userInfo1.setRealName("张三"); userInfo1.setIdCard("440923199403112222"); userInfo1.setEmail("[email protected]"); userInfo1.setBirthday("1994-04-11"); userInfo1.setPhone("13916022555"); setUserInfo(userInfo1); } /** * 返回用户名是否存在的提示信息 */ public String returnRegisterUserNameMess() { if(checkUserNameIsExist()){ this.registerUserNameMess = "该用户名已被注册"; }else{ this.registerUserNameMess = "恭喜,该用户名可用"; } return "registerUserNameMess"; } /** * 判断是否存在该用户名 */ public boolean checkUserNameIsExist(){ initUserInfo(); if(getUserInfo().getUserName().equals(getUserName())){ return true; } else { return false; } } /** * 返回邮箱是否存在的提示信息 */ public String returnRegisterEmailMess() { if(checkEmailIsExist()){ this.registerEmailMess = "该邮箱已被注册"; }else{ this.registerEmailMess = "恭喜,该邮箱可用"; } return "registerEmailMess"; } /** * 判断是否存在该邮箱 */ public boolean checkEmailIsExist(){ initUserInfo(); if(getUserInfo().getEmail().equals(getEmail())){ return true; } else { return false; } } /** * 返回发往邮箱的验证码是否正确的提示信息 */ public String returnEmailIdentifyCodeMess() { if(checkSendCodeIsTrue()){ this.emailIdentifyCodeMess = ""; } else{ this.emailIdentifyCodeMess = "邮箱验证码错误"; } return "emailIdentifyCodeMess"; } /** * 返回发往邮箱的验证码是否正确的提示信息 */ public boolean checkSendCodeIsTrue(){ //通过ServletActionContext类来访问JSP的内置对象 HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(false); //获取session中的发送邮件时的时间戳sendCodeStartTime String sendCodeStartTime = (String) session.getAttribute("sendCodeStartTime"); if(sendCodeStartTime != null){ long startTime = Long.parseLong(sendCodeStartTime); long endTime = System.currentTimeMillis(); //得到用户提交的邮箱验证码与发送邮件时的时间差,单位为秒 long validTime = (endTime - startTime)/1000; //如果邮箱验证码在有效时间内,则对用户提交的邮箱验证码进行验证;否则,将清除session中的sendCodeStartTime和sendCode if(validTime > 0 && validTime < 90){ //获取session中的邮箱验证码sendCode String sendCode = (String) session.getAttribute("sendCode"); if(sendCode.equals(getEmailIdentifyCode())){ return true; } else{ return false; } } else{ //清除session中的sendCodeStartTime和sendCode session.removeAttribute("sendCodeStartTime"); session.removeAttribute("sendCode"); return false; } }else{ return false; } } /** * 返回手机号码是否存在的提示信息 */ public String returnRegisterPhoneMess() { if(checkPhoneIsExist()){ this.registerPhoneMess = "该手机号码已被注册"; }else{ this.registerPhoneMess = "恭喜,该手机号码可用"; } return "registerPhoneMess"; } /** * 判断是否存在该手机号码 */ public boolean checkPhoneIsExist(){ initUserInfo(); if(getUserInfo().getPhone().equals(getPhone())){ return true; } else { return false; } } /** * 返回身份证是否存在的提示信息 */ public String returnRegisterIdCardMess() { if(checkIdCardIsExist()){ this.registerIdCardMess = "该身份证已被注册"; }else{ this.registerIdCardMess = "恭喜,该身份证可用"; } return "registerIdCardMess"; } /** * 判断是否存在该身份证 */ public boolean checkIdCardIsExist(){ initUserInfo(); if(getUserInfo().getIdCard().equals(getIdCard())){ return true; } else { return false; } } /** * 返回验证码是否正确的提示信息 */ public String returnRegisterIdeCodeMess() { if(checkIdentifyCodeIsExist()){ this.registerIdeCodeMess = "验证码正确"; }else{ this.registerIdeCodeMess = "验证码错误"; } return "registerIdeCodeMess"; } /** * 判断验证码是否正确 */ public boolean checkIdentifyCodeIsExist(){ //通过ServletActionContext类来访问JSP的内置对象 HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(false); //获取jsp页面中存放进session中的验证码的值 String identifyCode = (String) session.getAttribute("rand"); //测试是否获取到jsp页面中生成的验证码的值 System.out.println("验证码为:" + identifyCode); //获取jsp页面生成的验证码与获取用户输入的验证码之间,二者进行不区分大小写比较 if(identifyCode.equalsIgnoreCase(getIdentifyCode())){ return true; } else { return false; } } }
SendMessageAction.java
package com.action; import com.opensymphony.xwork2.ActionContext; import com.util.mail.MailSenderInfo; import com.util.mail.SimpleMailSender; public class SendMessageAction { private String sendCode; private String sendCodeStuts; private String toAddress; private String sendCodeStartTime; public String getSendCode() { return sendCode; } public void setSendCode(String sendCode) { this.sendCode = sendCode; } public String getSendCodeStuts() { return sendCodeStuts; } public void setSendCodeStuts(String sendCodeStuts) { this.sendCodeStuts = sendCodeStuts; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getSendCodeStartTime() { return sendCodeStartTime; } public void setSendCodeStartTime(String sendCodeStartTime) { this.sendCodeStartTime = sendCodeStartTime; } public void postSendCode(){ //这个类主要是设置邮件 MailSenderInfo mailInfo = new MailSenderInfo(); //服务器与端口的对应关系: smtp.qq.com -> 587 smtp.163.com -> 25 mailInfo.setMailServerHost("smtp.sina.com"); //发送方的邮件服务器地址 mailInfo.setMailServerPort("25"); //发送方SMTP服务器端口 mailInfo.setValidate(true); //设置SMTP服务器需要身份验证 mailInfo.setUserName("[email protected]"); //发送方邮箱账号 mailInfo.setPassword("abc13432916088"); //发送方邮箱密码 mailInfo.setFromAddress("[email protected]"); //发送方邮箱地址 mailInfo.setToAddress(this.toAddress); //接收方邮箱地址 mailInfo.setSubject("系统所发的注册验证码,请勿回复"); //邮件标题 mailInfo.setContent("您好,您正在验证的邮箱验证码为"+this.sendCode+",90秒内有效,请及时完成验证,谢谢!"); //邮件内容 boolean flag = false; //SimpleMailSender这个类主要来发送邮件, sendHtmlMail是它的静态方法 flag = SimpleMailSender.sendHtmlMail(mailInfo);//发送html格式 if(flag){ //通过ActionContext类来访问Servlet API ActionContext context =ActionContext.getContext(); //把sendCode放进session中,用于与用户提交的表单中的sendCode属性的值进行验证 context.getSession().put("sendCode", this.sendCode); //获取系统当前的时间戳,System.currentTimeMillis()返回long类型,精确到毫秒,表示1970年一月一日00:00:00:000到现在的毫秒数 String sendCodeStartTime = System.currentTimeMillis() + ""; SendMessageAction sendMessageAction = new SendMessageAction(); sendMessageAction.setSendCodeStartTime(sendCodeStartTime); //把当前时间戳sendCodeStartTime放进session中 context.getSession().put("sendCodeStartTime", sendMessageAction.getSendCodeStartTime()); //打印成功发送邮件信息 System.out.println("发送html格式mail 成功!"); //打印出该验证码 System.out.println("发往该邮箱的验证码为:"+this.sendCode); //打印出系统当前的时间戳 System.out.println("系统当前时间戳为:"+sendMessageAction.getSendCodeStartTime()); } else{ System.out.println("发送html格式mail 失败!"); } } }
UserInfoAction.java
package com.action; public class UserInfoAction { public String register(){ return "success"; } }
4、在src目录下建立xml配置文件RegisterJson-struts.xml 、struts.xml 、UserInfo-struts.xml
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 配置 Struts 2 应用中的常量 --> <constant name="struts.i18n.encoding" value="UTF-8"/> <!-- struts2缺省配置 --> <include file="struts-default.xml"></include> <package name="com.json" extends="struts-default,json-default"> <!-- 全局映射元素,当在action里找不到相匹配的result时,就到全局变量里找 --> <global-results> <result name="login">/login.jsp</result> <result name="fail">/login.jsp</result> </global-results> <!-- 全局异常元素 --> <global-exception-mappings> <exception-mapping result="exception" exception="java.lang.Exception"></exception-mapping> </global-exception-mappings> </package> <!-- 把相关的struts.xml文件加载进来 --> <include file="RegisterJson-struts.xml"></include> <include file="UserInfo-struts.xml"></include> </struts>
RegisterJson-struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 配置 Struts 2 应用中的常量 --> <constant name="struts.i18n.encoding" value="UTF-8"/> <!-- 配置本应用中的包,继承 json-default 包 --> <package name="RegisterJson" extends="com.json"> <action name="returnRegisterUserNameMess" class="com.action.RegisterJsonAction" method="returnRegisterUserNameMess"> <result name="registerUserNameMess" type="json" /> </action> <action name="returnRegisterEmailMess" class="com.action.RegisterJsonAction" method="returnRegisterEmailMess"> <result name="registerEmailMess" type="json" /> </action> <action name="postSendCode" class="com.action.SendMessageAction" method="postSendCode"> <result type="json" /> </action> <action name="returnEmailIdentifyCodeMess" class="com.action.RegisterJsonAction" method="returnEmailIdentifyCodeMess"> <result name="emailIdentifyCodeMess" type="json" /> </action> <action name="returnRegisterPhoneMess" class="com.action.RegisterJsonAction" method="returnRegisterPhoneMess"> <result name="registerPhoneMess" type="json" /> </action> <action name="returnRegisterIdCardMess" class="com.action.RegisterJsonAction" method="returnRegisterIdCardMess"> <result name="registerIdCardMess" type="json" /> </action> <action name="returnRegisterIdeCodeMess" class="com.action.RegisterJsonAction" method="returnRegisterIdeCodeMess"> <result name="registerIdeCodeMess" type="json" /> </action> </package> </struts>
UserInfo-struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 配置 Struts 2 应用中的常量 --> <constant name="struts.i18n.encoding" value="UTF-8"/> <!-- 配置本应用中的包,继承 json-default 包 --> <package name="UserInfo" extends="com.json"> <action name="register" class="com.action.UserInfoAction" method="register"> <result name="success">/registerSucceed.jsp</result> </action> </package> </struts>
5、在WebRoot目录下建立js文件夹,在该文件夹里面导入jquery的官方jar包:jquery-1.10.1.js ,然后再建立以下几个js文件: registerJson.js 、 sendMessage.js
registerJson.js
//初始加载页面时 $(document).ready(function(){ //设置每个选项的完成状态的标识 var flag_userName = false; var flag_password = false; var flag_rePassword = false; var flag_idCard = false; var flag_email = false; var flag_emailIdentifyCode = false; var flag_phone = false; var flag_identifyCode = false; //用户名的验证 $("#userName").blur(function(){ //设置用户名文本框完成状态为false flag_userName = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //向String类型添加了一个可以判断带中文的字符串的长度的函数length2(),一个汉字算两个字符 String.prototype.length2 = function() { var cArr = this.match(/[^\x00-\xff]/ig); return this.length + (cArr == null ? 0 : cArr.length); }; //获取id对应的元素的值,去掉其左右的空格 var userName = $.trim($('#userName').val()); //清空显示层中的数据 $("#userNameMess").html(""); if(userName == ""){ $("#userNameMess").html("<font color='red'>"+"用户名不能为空"+"</font>"); } else if(userName.length2() < 6 || userName.length2() > 25){ $("#userNameMess").html("<font color='red'>"+"请输入合法的用户名"+"</font>"); } else{ $.post( "returnRegisterUserNameMess.action", {userName:userName}, function(data){ //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 if(data.registerUserNameMess == "该用户名已被注册"){ $("#userNameMess").html("<font color='red'>"+data.registerUserNameMess+"</font>"); }else{ $("#userNameMess").html("<font color='green'>"+data.registerUserNameMess+"</font>"); //设置用户名文本框完成状态为true flag_userName = true; //调用启用注册按钮函数 abledBtnRegister(); } } ); } }); //密码的验证 $("#password").blur(function(){ //设置密码文本框完成状态为false flag_password = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //获取id对应的元素的值,去掉其左右的空格 var password = $.trim($('#password').val()); var rePassword = $.trim($('#rePassword').val()); //清空显示层中的数据 $("#passwordMess").html(""); $("#rePasswordMess").html(""); if(password == ""){ $("#passwordMess").html("<font color='red'>"+"密码不能为空"+"</font>"); } else if(password.length < 6 || password.length > 16){ $("#passwordMess").html("<font color='red'>"+"密码为6~16个字符"+"</font>"); } else if(password == rePassword ){ //如果两次密码一致,则设置密码文本框和确认密码文本框完成状态为true flag_password = true; flag_rePassword = true; //调用启用注册按钮函数 abledBtnRegister(); } else{ $("#rePasswordMess").html("<font color='red'>"+"两次密码不一致"+"</font>"); } }); //确认密码的验证 $("#rePassword").blur(function(){ //设置确认密码文本框完成状态为false flag_rePassword = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //获取id对应的元素的值,去掉其左右的空格 var password = $.trim($('#password').val()); var rePassword = $.trim($('#rePassword').val()); //清空显示层中的数据 $("#rePasswordMess").html(""); if(rePassword != password){ $("#rePasswordMess").html("<font color='red'>"+"两次密码不一致"+"</font>"); } else{ //如果两次密码一致,则设置密码文本框和确认密码文本框完成状态为true flag_password = true; flag_rePassword = true; //调用启用注册按钮函数 abledBtnRegister(); } }); //身份证的验证 $("#idCard").blur(function(){ //设置身份证文本框完成状态为false flag_idCard = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //身份证验证js正则表达式(15位) isIDCard1 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/; //身份证验证js正则表达式(18位) isIDCard2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/; //获取id对应的元素的值,去掉其左右的空格 var idCard = $.trim($('#idCard').val()); //清空显示层中的数据 $("#idCardMess").html(""); if(idCard == ""){ $("#idCardMess").html("<font color='red'>"+"身份证不能为空"+"</font>"); } else if(!(isIDCard1.test(idCard) || isIDCard2.test(idCard))){ $("#idCardMess").html("<font color='red'>"+"请输入有效的身份证"+"</font>"); } else{ $.post( "returnRegisterIdCardMess.action", {idCard:idCard}, function(data){ //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 if(data.registerIdCardMess == "该身份证已被注册"){ $("#idCardMess").html("<font color='red'>"+data.registerIdCardMess+"</font>"); } else{ $("#idCardMess").html("<font color='green'>"+data.registerIdCardMess+"</font>"); //设置身份证文本框完成状态为true flag_idCard = true; //调用启用注册按钮函数 abledBtnRegister(); } } ); } }); //邮箱的验证 $("#email").blur(function(){ //设置邮箱文本框完成状态为false flag_email = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //获取id对应的元素的值,去掉其左右的空格 var email = $.trim($('#email').val()); //验证邮箱格式的js正则表达式 var isEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; //清空显示层中的数据 $("#emailMess").html(""); if(email == ""){ $("#emailMess").html("<font color='red'>"+"邮箱不能为空"+"</font>"); //隐藏发送邮箱按钮及其验证码的div层 $("#div_hidden").hide(100); } else if(!(isEmail.test(email))){ $("#emailMess").html("<font color='red'>"+"邮箱格式不正确"+"</font>"); //隐藏发送邮箱按钮及其验证码的div层 $("#div_hidden").hide(100); } else{ $.post( "returnRegisterEmailMess.action", {email:email}, function(data){ //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 if(data.registerEmailMess == "该邮箱已被注册"){ $("#emailMess").html("<font color='red'>"+data.registerEmailMess+"</font>"); //隐藏发送邮箱按钮及其验证码的div层 $("#div_hidden").hide(50); }else{ $("#emailMess").html("<font color='green'>"+data.registerEmailMess+"</font>"); //设置邮箱文本框完成状态为true flag_email = true; //显示发送邮箱按钮及其验证码的div层 $("#div_hidden").show(50); //清空邮箱验证码文本框 $('#emailIdentifyCode').val(""); } } ); } }); //发送邮件按钮及其验证码的div层的设置,此处设置为加载js文件时就隐藏 $("#div_hidden").hide(); //邮箱验证码的验证 $("#emailIdentifyCode").blur(function(){ //设置邮箱验证码文本框完成状态为false flag_emailIdentifyCode = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //获取id对应的元素的值,去掉其左右的空格 var emailIdentifyCode = $.trim($('#emailIdentifyCode').val()); if(emailIdentifyCode == ""){ $("#emailIdentifyCodeMess").html("<font color='red'>"+"邮箱验证码不能为空"+"</font>"); } else if(emailIdentifyCode.length != 6){ $("#emailIdentifyCodeMess").html("<font color='red'>"+"邮箱验证码错误"+"</font>"); } else{ $.post( "returnEmailIdentifyCodeMess.action", {emailIdentifyCode:emailIdentifyCode}, function(data){ //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 if(data.emailIdentifyCodeMess == "邮箱验证码错误"){ $("#emailIdentifyCodeMess").html("<font color='red'>"+data.emailIdentifyCodeMess+"</font>"); } else{ $("#emailIdentifyCodeMess").html(""); //设置邮箱验证码文本框完成状态为true flag_emailIdentifyCode = true; //调用启用注册按钮函数 abledBtnRegister(); } } ); } }); //手机的验证 $("#phone").blur(function(){ //设置手机文本框完成状态为false flag_phone = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //验证手机格式的js正则表达式 var isPhone = /^0?(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/; //获取id对应的元素的值,去掉其左右的空格 var phone = $.trim($('#phone').val()); //清空显示层中的数据 $("#phoneMess").html(""); if(phone == ""){ $("#phoneMess").html("<font color='red'>"+"手机不能为空"+"</font>"); } else if(!(isPhone.test(phone))){ $("#phoneMess").html("<font color='red'>"+"手机号码格式不正确"+"</font>"); } else{ $.post( "returnRegisterPhoneMess.action", {phone:phone}, function(data){ //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 if(data.registerPhoneMess == "该手机号码已被注册"){ $("#phoneMess").html("<font color='red'>"+data.registerPhoneMess+"</font>"); } else{ $("#phoneMess").html("<font color='green'>"+data.registerPhoneMess+"</font>"); //设置手机文本框完成状态为true flag_phone = true; //调用启用注册按钮函数 abledBtnRegister(); } } ); } }); //验证码的验证 $("#identifyCode").blur(function(){ //设置验证码文本框完成状态为false flag_identifyCode = false; //初始化设置注册按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //获取id对应的元素的值,去掉其左右的空格 var identifyCode = $.trim($('#identifyCode').val()); //清空显示层中的数据 $("#identifyCodeMess").html(""); if(identifyCode == ""){ $("#identifyCodeMess").html("<font color='red'>"+"验证码不能为空"+"</font>"); } else if(identifyCode.length != 6){ $("#identifyCodeMess").html("<font color='red'>"+"验证码错误"+"</font>"); } else{ $.post( "returnRegisterIdeCodeMess.action", {identifyCode:identifyCode}, function(data){ //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 if(data.registerIdeCodeMess == "验证码错误"){ $("#identifyCodeMess").html("<font color='red'>"+data.registerIdeCodeMess+"</font>"); } else{ $("#identifyCodeMess").html(""); //设置验证码文本框完成状态为true flag_identifyCode = true; //调用启用注册按钮函数 abledBtnRegister(); } } ); } }); //注册按钮的设置,js加载进来时,默认该按钮为不可用 $("#btnRegister").attr({"disabled":"disabled"}); //启用注册按钮函数 function abledBtnRegister(){ //如果所有的要求填写选项都正确完成,则设置注册按钮为可用 if(flag_userName && flag_password && flag_rePassword && flag_idCard && flag_email && flag_emailIdentifyCode && flag_phone && flag_identifyCode){ //设置注册按钮为可用 $("#btnRegister").removeAttr("disabled"); } }; //点击注册按钮函数 $("#btnRegister").click(function(){ //如果注册按钮为启用状态,并点击了它,则提交表单,并设置按钮的值为“正在处理...” $("#btnRegister").val("正在处理..."); }); });
sendMessage.js
var InterValObj; //timer变量,控制时间 var count = 90; //间隔函数,1秒执行 var curCount;//当前剩余秒数 var sendCode = ""; //验证码 var codeLength = 6;//验证码长度 //发送信息(验证码)函数 function sendMessage() { curCount = count; //产生验证码 for (var i = 0; i < codeLength; i++) { sendCode += parseInt(Math.random() * 9).toString(); } //设置button效果,开始计时 $("#btnSendCode").attr("disabled", "true"); $("#btnSendCode").val("请在" + curCount + "秒内输入验证码"); InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次 //向后台发送处理数据 var toAddress = $.trim($('#email').val()); $.post( "postSendCode.action", { sendCode:sendCode, toAddress:toAddress, } ); //把js中生成的验证码清零, sendCode = ""; } //timer处理函数 function SetRemainTime() { if (curCount == 0) { window.clearInterval(InterValObj);//停止计时器 $("#btnSendCode").removeAttr("disabled");//启用按钮 $("#btnSendCode").val("重新发送验证码"); code = ""; //清除验证码。如果不清除,过时间后,输入收到的验证码依然有效 } else { curCount--; $("#btnSendCode").val("请在" + curCount + "秒内输入验证码"); } }
6、修改web.xml文件
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 设置struts 2过滤器 --> <filter> <filter-name>struts 2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts 2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 设置欢迎页面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- session超时定义,单位为分钟 --> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>
7、在WebRoot根目录下建立以下几个jsp文件:identifyCode.jsp 、index.jsp 、 login.jsp 、 register.jsp 、registerSucceed.jsp
identifyCode.jsp
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="utf-8" %> <%! Color getRandColor(int fc,int bc){//给定范围获得随机颜色 Random random = new Random(); if(fc>255) fc=255; if(bc>255) bc=255; int r=fc+random.nextInt(bc-fc); int g=fc+random.nextInt(bc-fc); int b=fc+random.nextInt(bc-fc); return new Color(r,g,b); } %> <% //设置页面不缓存 response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); // 在内存中创建图象,设置验证码图片的宽和高 int width=90, height=30; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 Random random = new Random(); // 设定背景色 g.setColor(getRandColor(200,250)); //填充一个矩形区域,x、y为起始坐标(即左上角坐标),后面两个参数分别为:w、h,是矩形区域的宽和高 g.fillRect(0, 0, width, height); //设定字体,其中的参数: 字体,风格(Font.PLAIN为常量之一),字号 g.setFont(new Font("Times New Roman",Font.PLAIN,20)); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(getRandColor(160,200)); for (int i=0;i<155;i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x,y,x+xl,y+yl); } // 取随机产生的认证码(6位字母或数字的组合码) String codeList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; String sRand=""; for (int i=0;i<6;i++){ int a=random.nextInt(codeList.length()-1); String rand=codeList.substring(a,a+1); sRand+=rand; // 将认证码显示到图象中 //调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); g.drawString(rand,13*i+6,16); } // 将认证码存入SESSION,在后台验证时再取出即可 session.setAttribute("rand",sRand); // 图象生效 g.dispose(); // 输出图象到页面 ImageIO.write(image, "JPEG", response.getOutputStream()); out.clear(); out = pageContext.pushBody(); %>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>首页</title> </head> <body> <a href="login.jsp">去登录</a> <a href="register.jsp">去注册</a> </body> </html>
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>登录</title> <style type="text/css"> .label{ float: left; width: 180px; text-align: right; } .label_mess{float: right; width: 200px; text-align: left; } .li{float: left; width: 700px; margin-bottom: 10px; margin-left: 300px;} </style> <script type="text/javascript" src="js/jquery-1.10.1.js"></script> <script type="text/javascript" src="js/loginJson.js"></script> </head> <body> <div class="li"></div> <div class="li"></div> <div class="li"><label>登录</label></div> <form action="" method="post"> <div class="li"><label for="userName" class="label">用户名:</label><input type="text" name="userInfo.userName" id="userName" size="30" maxlength="25"/><label id="userNameMess" class="label_mess"></label></div> <div class="li"><label for="password" class="label">密 码:</label><input type="password" name="userInfo.password" id="password" size="30" maxlength="25"/><br /><label id="passwordMess" class="label_mess"></label></div> <div class="li"><label for="login" class="label"><input type="submit" value="登录" id="login" /></label></div> </form> </body> </html>
register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>欢迎注册</title> <style type="text/css"> .main{float:left; width: 700px; margin-left: 320px; margin-top: 10px; border:30px solid #dddddd;; border-radius:14px; -moz-border-radius:25px; } .label_welcome{float:left;width:150px;height:70px;float:left; text-align:center; line-height:70px; font-size:30px;} .label{ float: left; width: 180px; text-align: right; margin-top: 5px;} .label_mess{float: right; width: 200px; text-align: left; margin-top: 5px; } .label_idenCod{ float: left; width: 180px; text-align: right; margin-top: 15px; } input{float: left; height: 30px;} .li{float: left; width: 700px; min-height:30px; margin-bottom: 15px;} .flag{ color: #CC0033;} </style> <script type="text/javascript" src="js/jquery-1.10.1.js"></script> <script type="text/javascript" src="js/registerJson.js"></script> <script type="text/javascript" src="js/sendMessage.js"></script> </head> <body> <div class="main"> <div class="li"><label class="label_welcome">欢迎注册</label></div> <form action="register" method="post" id="regi_form"> <div class="li"><label for="userName" class="label"><span class="flag">* </span>用户名:</label><input type="text" name="userInfo.userName" id="userName" placeholder="6~25个字符,一个汉字算两个字符" size="30" maxlength="25"/><label id="userNameMess" class="label_mess"></label></div> <div class="li"><label for="password" class="label"><span class="flag">* </span>密码:</label><input type="password" name="userInfo.password" id="password" placeholder="6~16个字符,区分大小写" size="30" maxlength="16"/><label id="passwordMess" class="label_mess"></label></div> <div class="li"><label for="rePassword" class="label"><span class="flag">* </span>确认密码:</label><input type="password" name="rePassword" id="rePassword" placeholder="再输一次密码" size="30" maxlength="16"/><label id="rePasswordMess" class="label_mess"></label></div> <div class="li"><label for="idCard" class="label"><span class="flag">* </span>身份证:</label><input type="text" name="userInfo.idCard" id="idCard" placeholder="请输入有效身份证号码" size="30" maxlength="18"/><label id="idCardMess" class="label_mess"></label></div> <div class="li"><label for="email" class="label"><span class="flag">* </span>邮箱:</label><input type="text" name="userInfo.email" id="email" placeholder="请输入有效的邮箱" size="30" maxlength="25"/><label id="emailMess" class="label_mess"></label></div> <div class="li" id="div_hidden"><label class="label"></label><input type="text" name="emailIdentifyCode" id="emailIdentifyCode" placeholder="发往邮箱的验证码" size="15" maxlength="6"/><input type="button" value="发送验证码" id="btnSendCode" onclick="sendMessage()"/><label id="emailIdentifyCodeMess" class="label_mess"></label></div> <div class="li"><label for="phone" class="label"><span class="flag">* </span>手机:</label><input type="text" name="userInfo.phone" id="phone" placeholder="请输入有效的11位手机号码" size="30" maxlength="11"/><label id="phoneMess" class="label_mess"></label></div> <div class="li"><label for="identifyCode" class="label"><span class="flag">* </span>验证码:</label><input type="text" name="identifyCode" id="identifyCode" placeholder="请输入验证码" size="12" maxlength="6"/> <img id="identifyCode_img" src="identifyCode.jsp" alt="验证码" onclick="this.src=this.src+'?'" /><label id="identifyCodeMess" class="label_mess"></label></div> <div class="li"><label for="btnRegister" class="label"></label><input type="submit" value="注册" id="btnRegister" /></div> </form> </div> </body> </html>
registerSucceed.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>注册成功</title> <style type="text/css"> .context{ float:left; width: 700px; height: 300px; margin-left:300px; margin-top: 200px; text-align:center; font-size: 26px; } </style> </head> <body> <script type="text/javascript"> var t=10;//设定跳转的时间 setInterval("refer()",1000); //启动1秒定时 function refer(){ if(t==0){ location="login.jsp"; //#设定跳转的链接地址 } document.getElementById('show').innerHTML="恭喜您注册成功,"+t+"秒后自动跳转到登录界面。"; // 显示倒计时 t--; // 计数器递减 } </script> <div class="context"> <span id="show"></span> 您也可以点击<a href="login.jsp">这里</a>,马上跳转 </div> </body> </html>
完成以上所有的步骤后,把项目发布到服务器,用浏览器访问register.jsp ,在里面就可以看到要实现的效果如下:
时间: 2024-11-03 21:56:37