<br style="font-size: 18px;" /><pre name="code" class="html" style="font-size: 18px;">闲暇时查了下关于md5加密的东西,现在一般都会在前台进行加密然后传到后台,这也是出于安全性的考虑吧,所以写了个小例子,作为笔记记录一下哈。<!DOCTYPE html>
login.html,注意要导入相关的js
</pre><pre name="code" class="html"><html>
<head>
<meta charset="UTF-8">
<title>md5</title>
<!-- 导入jquery和 md5的js -->
<script type="text/javascript">
$(function(){
$("#submit").bind("onclick",function(){
//检验是否继续保存cookie
if($("#checkbox")[0].checked) {
$("#SAVE_PWD").val("_YES");
}
else {
$("#SAVE_PWD").val("_NO");
}
//加密
md5PWD();
//提交
$("#loginForm").submit();
});
//获取cookie
function checkCookie() {
var name = "userNbr=";
var pwd = "userPwd=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
if (c.indexOf(name) != -1){
$("#name").val(c.substring(name.length, c.length));
$("#checkbox")[0].checked = "checked";
}
else if(c.indexOf(pwd) != -1) {
$("#PWD").val(c.substring(pwd.length+1, c.length));
$("#password").val("默认密码");
}
}
}
checkCookie();
//对密码进行md5加密,赋给hidden
function md5PWD(){
if($("#password").val()=="默认密码"){
return;
}
var md5PWD = $("#password").val();
$("#PWD").val(hex_md5(md5PWD)) ;//不同的md5.js调用的方法可能不同
}
});
</script>
</head>
<body>
<form action="/LoginController" method="post">
姓名:<input type="text" name="name" id="name" placeholder="姓名">
密码:<input type="password" name="password" id="password" placeholder="密码">
<input type="hidden" id="PWD">
<input type="submit" id="submit" value="提交">
记住密码:<input type="checkbox" id="checkbox">
<input type="hidden" id="SAVE_PWD">
</form>
</body>
</html>
loginController 代码片段:
String setCookie = request.getParameter("SAVE_PWD");
if ("_YES".equals(setCookie)) {
// 设置cookie
Cookie cookieName = new Cookie("userNbr", userNbr);
cookieName.setMaxAge(7 * 24 * 60 * 60 * 1000);
response.addCookie(cookieName);
Cookie cookiePwd = new Cookie("userPwd", pwd);
cookiePwd.setMaxAge(7 * 24 * 60 * 60 * 1000);
response.addCookie(cookiePwd);
}
else {
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
if ("userNbr".equals(cookies[i].getName()) || "userPwd".equals(cookies[i].getName())) {
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);
}
}
}