登录模块(前端bookstrapValidator校验+加密+后台加密+后台验证)
2017-05-13 09:00 甘雨路 阅读(1660) 评论(0) 编辑 收藏 举报package sysone.zr.com.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; import com.alibaba.fastjson.JSON; import com.google.gson.Gson; /** * * @author lf * */ public class BasicalController { /** * 获取IP * @return */ public static String getIP(HttpServletRequest request){ String ip = request.getHeader("X-Forwarded-For"); if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { //多次反向代理后会有多个ip值,第一个ip才是真实ip int index = ip.indexOf(","); if (index != -1) { return ip.substring(0,index); }else { return ip; } } ip = request.getHeader("X-Real-IP"); if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { return ip; } return request.getRemoteAddr(); } /** * 输出json数据(基于gson) * @param object * @param response */ public static void printOutByGson(Object object ,HttpServletResponse response){ response.setCharacterEncoding("UTF-8"); // 创建gson对象 Gson gson = new Gson(); String jsonstr = gson.toJson(object); try { response.getWriter().print(jsonstr); } catch (IOException e) { e.printStackTrace(); } } /** * 输出json数据(基于阿里巴巴的jar实现的) * @param object * @param response */ public static void printOutByFast(Object object,HttpServletResponse response){ response.setCharacterEncoding("UTF-8"); String jsonStr = JSON.toJSONString(object); System.out.println(jsonStr); try { response.getWriter().print(jsonStr); } catch (IOException e) { e.printStackTrace(); } } }
package sysone.zr.com.controller; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import javax.enterprise.inject.New; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import sysone.zr.com.mapper.model.MessageTip; import sysone.zr.com.utils.Encrypt; import sysone.zr.com.utils.VerifyString; /** * * @author lf * */ @Controller public class LoginController extends BasicalController{ /** * 利用map取代去数据库查询 */ private static Map<String, String> info = new HashMap<String, String>(); private String regStr = "[a-zA-Z]{2,12}"; static{ info.put("username", "lf"); // info.put("password", "123456"); info.put("password", "750e65ebba95ab9493cda01e3eq*&@,.,`~S6@#>e388f02f"); } /** * 进入登录页面 * @return */ @RequestMapping("index.htm") public String comeToLoginPage(HttpServletRequest request){ System.out.println(super.getIP(request)); return "login"; } /** * 验证登录的合法性֤ * @param username * @param password * @param response */ @RequestMapping(value="login",method=RequestMethod.POST) public void login(@RequestParam(value="username",required=true,defaultValue="") String username, @RequestParam(value="password",required=true,defaultValue="") String password, HttpServletResponse response){ System.out.println("username:"+username+"\npassword:"+password); //判断用户名合法性 boolean isLegal = false; isLegal = VerifyString.validString(username, regStr); System.out.println(isLegal); if (!isLegal) { super.printOutByGson(new MessageTip("username is not valid"), response); return ; } // 加密 String newPwd = Encrypt.encrypt(password); System.out.println(newPwd); // 通过map去查询(在此忽略了去数据查找的步骤) boolean isExisted = false; String usernameStr = info.get("username"); String pwd = info.get("password"); if (username.equals(usernameStr) && newPwd.equals(pwd)) { isExisted = true; } // 根据查找的结果返回相应的提示 String msg = isExisted == true ? "success" : "非法用户名"; MessageTip tip = new MessageTip(msg); super.printOutByFast(tip, response); } /** * 进入欢迎页面 * @return */ @RequestMapping("welcome.htm") public String comeToWelcomePage(){ return "welcome"; } /** * ע�� */ // @RequestMapping(value="regedit",method=RequestMethod.POST) // public void regedit(){ // // ��̨У����� // } /** * 进入注册页面 * @return */ @RequestMapping("regedit.htm") public String comeToRegeditPage(){ return "regedit"; } }
package sysone.zr.com.mapper.model; /** * * @author lf * */ public class MessageTip { private String tips; public String getTips() { return tips; } public void setTips(String tips) { this.tips = tips; } public MessageTip() { super(); } public MessageTip(String tips) { super(); this.tips = tips; } }
package sysone.zr.com.utils; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * 加密工具类 * @author lf * */ public class Encrypt { public static void main(String[] args) { System.out.println(encrypt("123456789")); } /** * 将字符串从中间一分为二,然后分开的字符串进行倒序排序后,在拼接在一起 * 如果字符串出现基数,中间的值保持不变,将剩下的字符串一分为二 * */ public static String encrypt(String str){ str = appendString(str); int num = str.length() % 2; String str1 = reverseString(str.substring(0, str.length()/2)); if (num==0) { String str2 = reverseString(str.substring(str.length()/2, str.length())); return str1+str2; }else { String str2 = reverseString(str.substring(str.length()/2+1, str.length())); return str1+str.substring(str.length()/2, str.length()/2+1)+str2; } } /** * 拼接字符串 * @param str * @return */ private static String appendString(String str){ String newStr = str+">#@6S~`,.,@&*qe3"; return newStr; } /** * ͨ递归将字符串倒序排序 * @param str * @return */ private static String reverseString(String str){ if (str.length()==1) { return str; }else{ // 截取最后一个字符 String lastStr = str.substring(str.length()-1, str.length()); String string =lastStr+ reverseString(str.substring(0, str.length()-1)); return string; } } }
package sysone.zr.com.utils; import java.util.regex.Pattern; /** * * @author apple * */ public class VerifyString { /** * 判断是否匹配 * @param str * @param regStr * @return */ public static boolean validString(String str, String regStr){ Pattern pattern = Pattern.compile(regStr); return pattern.matcher(str).matches(); } }
package sysone.zr.com.utils; /** * * @author lf * */ public class VerifyUtil { //手机号 public static String mobile = "^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$"; //空白 public static String blank = ".*[^ ].*"; //邮箱 public static String email = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([0-9a-z_\\-]*)(\\.(com|cn|inc|org|cc|edu|de)*){1,2}([a-z]{2})?$"; //QQ号 public static String tencentQQ = "[1-9][0-9]{4,11}"; //网址ַ public static String url = "(http|https)+://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"; //微信号 public static String weixin = "^[A-Za-z0-9]\\w{3,60}+$"; }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" > <!-- 包扫描 --> <context:component-scan base-package="sysone.zr" /> <aop:aspectj-autoproxy proxy-target-class="true" /> <!-- 开启Springmvc注解驱动 --> <mvc:annotation-driven /> <!-- SpringMVC视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 拦截器 --> <!-- <bean id="urlhandler" class="sysone.zr.com.interception.URLHandler"></bean> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/lf/online/**"/> <ref bean="urlhandler"/> </mvc:interceptor> </mvc:interceptors> --> </beans>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录页面</title> <script src="/resource/vendor/jquery/jquery-1.10.2.min.js"></script> <script src="/resource/vendor/bootstrap/js/bootstrap.min.js"></script> <link href="/resource/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" /> <script src="/resource/dist/js/bootstrapValidator.min.js"></script> <script src="/resource/md5/md5.js"></script> <link href="/resource/dist/css/bootstrapValidator.min.css" rel="stylesheet" /> </head> <body> <p> <br/> <center><h1 id="tip"></h1></center> <form id="logForm" class="form-horizontal" method="post" action="login.htm"> <div class="form-group"> <label class="col-lg-3 control-label">用户名</label> <div class="col-lg-5"> <input id="username" type="text" class="form-control" name="username" /> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">密码</label> <div class="col-lg-5"> <input id="password" type="password" class="form-control" name="password" placeholder="密码是由6到12字符和数字组成(包括下划线和小圆点)"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label"></label> <button type="submit" class="btn btn-info">提交</button> <a class="btn btn-info" href="regedit.htm">注册</a> </div> </form> <script type="text/javascript"> $('#logForm').submit(function(){ //验证 if(!$('#logForm').data('bootstrapValidator').isValid()){ return false; } var pwdInput = document.getElementsByName("password")[0]; var password = pwdInput.value; // 对密码加密 var hash = hex_md5(password); pwdInput.value = hash; $.ajax({ url : 'login.htm', data : { "username" : $('#username').val(), "password" : $('#password').val(), }, type : 'post', dataType : 'text', success : function(data) { alert(data); var obj = eval('(' + data + ')'); var value = obj.tips; if(value != 'success'){ $('#tip').html(value); }else{ window.location.href='welcome.htm'; } }, error : function() { alert("提交出了点故障,您可以重新提交试试~"); } }); return false; }); $('#logForm').bootstrapValidator({ fields: { username: { message: 'The username is not valid', validators: { notEmpty: { message: '用户名不能为空' }, stringLength: { min: 2, max: 12, message: '密码长度必须在2到12个字母' }, regexp: { regexp: /^[a-zA-Z]{2,12}$/, message: '密码是由2到12字符和数字组成(包括下划线和小圆点)' } } }, password: { message:'密码无效', validators: { notEmpty: { message: '密码不能为空' }, stringLength: { min: 6, max: 12, message: '密码长度必须在6到12之间' }, regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: '密码是由6到12字符和数字组成(包括下划线和小圆点)' } } } } }); </script> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>注册页面</title> <script src="/resource/vendor/jquery/jquery-1.10.2.min.js"></script> <script src="/resource/vendor/bootstrap/js/bootstrap.min.js"></script> <link href="/resource/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" /> <script src="/resource/dist/js/bootstrapValidator.min.js"></script> <script src="/resource/md5/md5.js"></script> <link href="/resource/dist/css/bootstrapValidator.min.css" rel="stylesheet" /> </head> <body> <form id="logForm" class="form-horizontal" method="post" action="login.htm"> <div class="form-group"> <label class="col-lg-3 control-label">用户名</label> <div class="col-lg-5"> <input type="text" class="form-control" name="username" /> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">密码</label> <div class="col-lg-5"> <input type="password" class="form-control" name="password" placeholder="密码是由6到12字符和数字组成(包括下划线和小圆点)"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">手机</label> <div class="col-lg-5"> <input type="text" class="form-control" name="cellphone" placeholder="请输入手机号"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">邮箱</label> <div class="col-lg-5"> <input type="text" class="form-control" name="email" placeholder="请输入邮箱"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">身份证号码</label> <div class="col-lg-5"> <input type="text" class="form-control" name="identifier" placeholder="请输入身份证号码"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">日期</label> <div class="col-lg-5"> <input type="text" class="form-control" name="date" placeholder="日期"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">IP地址</label> <div class="col-lg-5"> <input type="text" class="form-control" name="IP" placeholder="IP地址"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">小写字母</label> <div class="col-lg-5"> <input type="text" class="form-control" name="little" placeholder="请输入小写字母"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">大写字母</label> <div class="col-lg-5"> <input type="text" class="form-control" name="big" placeholder="请输入大写字母"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">数字</label> <div class="col-lg-5"> <input type="text" class="form-control" name="digital" placeholder="自然数"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">QQ号</label> <div class="col-lg-5"> <input type="text" class="form-control" name="QQ" placeholder="请输入QQ号"/> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label"></label> <button type="submit" class="btn btn-info">注册</button> </div> </form> <script type="text/javascript"> $('#logForm').submit(function(){ //验证 if(!$('#logForm').data('bootstrapValidator').isValid()){ return false; } var pwdInput = document.getElementsByName("password")[0]; var password = pwdInput.value; // 对密码加密 var hash = hex_md5(password); pwdInput.value = hash; $.ajax({ url : 'login.htm', data : { "username" : $('#username').val(), "password" : $('#password').val(), }, type : 'post', dataType : 'text', success : function(data) { alert(data); var obj = eval('(' + data + ')'); var value = obj.tips; if(value != 'success'){ $('#tip').html(value); }else{ window.location.href='welcome.htm'; } }, error : function() { alert("提交出了点故障,您可以重新提交试试~"); } }); return false; }); $('#logForm').bootstrapValidator({ fields: { username: { message: 'The username is not valid', validators: { notEmpty: { message: '用户名不能为空' } } }, password: { message:'密码无效', validators: { notEmpty: { message: '密码不能为空' }, stringLength: { min: 6, max: 12, message: '密码长度必须在6到12之间' }, regexp: { /*以小写字母、大写字母、数字、下划线和小圆点的自由组合(其中^代表以什么开头,\.代表小圆点,+代表子表达式一次或多次,&代表结束)*/ regexp: /^[a-zA-Z0-9_\.]+$/, message: '11位数字' } } }, cellphone: { message:'手机号无效', validators: { notEmpty: { message: '手机号不能为空' }, regexp: { regexp: /^1[3|4|5|7|8][0-9]{9}$/, message: '密码是由6到12字符和数字组成(包括下划线和小圆点)' } } }, email: { message:'手机号无效', validators: { notEmpty: { message: '邮箱不能为空' }, regexp: { regexp: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/, message: '请输入正确的邮箱地址' } } }, identifier: { message:'无效身份证号', validators: { notEmpty: { message: '身份证号不能为空' }, regexp: {/* *代表匹配前面的字符零次和多次 */ regexp: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/, message: '请输入正确的邮箱地址' } } } , date: { message:'日期格式不正确', validators: { notEmpty: { message: '日期不能为空' }, regexp: {/* ?代表匹配前面的字符一次或零次,\d代表任意一个十进制数字*/ regexp: /^[1-9]\d{3}([-|\/|\.])?((0\d)|([1-9])|(1[0-2]))\1(([0|1|2]\d)|([1-9])|3[0-1])$/, message: '请输入正确的邮箱地址' } } } , IP: { message:'IP格式不正确', validators: { notEmpty: { message: 'IP不能为空' }, regexp: { regexp: /^((([1-9]\d?)|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}(([1-9]\d?)|(1\d{2})|(2[0-4]\d)|(25[0-5]))$/, message: '请输入正确的邮箱地址' } } } , little: { message:'格式不正确', validators: { notEmpty: { message: '小写字母框不能为空' }, regexp: { regexp: /^[a-z]+$/, message: '请输入正确的邮箱地址' } } } , big: { message:'格式不正确', validators: { notEmpty: { message: '大写字母框不能为空' }, regexp: { regexp: /^[A-Z]+$/, message: '请输入正确的邮箱地址' } } } , digital: { message:'格式不正确', validators: { notEmpty: { message: '自然数不能为空' }, regexp: {/*0~9数字范围内,至少一次(可多次)*/ regexp: /^[0-9]+$/, message: '请输入正确的自然数' } } } , QQ: { message:'格式不正确', validators: { notEmpty: { message: 'QQ号不能为空' }, regexp: { /*第一位数字在1~9之间,第二个数起在0~9之间,且要求在4到14位数(加上第一位数字,数字格式在5~15位)*/ regexp: /^[1-9][0-9]{4,14}$/, message: '请输入正确的QQ号码' } } } } }); </script> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>首页</title> </head> <body> <h1>欢迎进入本网站</h1> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- 配置springmvc核心 Servlet--> <servlet> <servlet-name>pringmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置文件加载的路径 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>pringmvc</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <!-- END 配置springmvc核心 Servlet--> <!-- spring 路径的配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/spring.xml</param-value> </context-param> <!--END spring 路径的配置 --> <!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--END 配置spring监听器 --> </web-app>
注意:要导入bookstrap相关的文件