注册功能前台页面
欢迎注册EasyMall
欢迎注册EasyMall
@charset "utf-8";
{
border: 1px solid #999;
}
body{
background-image: url("../img/regist/zc.jpg");
background-position:top;
font-family:"微软雅黑";
}
h1{
width:300px;
margin: 190px auto 0px;
text-align: center;
color:#990000;
}
form{
width:450px;
margin: 30px auto 0px;
}
table{
margin: 0px auto 0px;
}
.tds{
text-align: right;
font-size:18px;
}
td{
padding-top:10px;
}
input[type='text'],input[type='password']{
width:150px;
height:22px;
border: 1px solid #cccccc;
}
input[name='valistr']{
width:80px;
}
#yzm_img{
vertical-align: top;
margin-left:5px;
}
input[type='submit']{
background-image: url("../img/regist/zcan01.jpg");
width:127px;
height:44px;
border-style:none;
font-size:20px;
color:white;
font-weight:bold;
}
input[type='submit']:hover{
background-image: url("../img/regist/zcan02.jpg");
}
span{
color:red;
font-size:14px;
}
注册功能后台逻辑
代码
RegisteSer
package com.easymall.ser;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.easymall.exception.MsgException;
import com.easymall.utils.MySqlUtils;
@SuppressWarnings("serial")
public class RegisteSer extends HttpServlet {
private Connection conn = null;
private PreparedStatement stat = null;
private ResultSet rs = null;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 全局变量
try {
// 0.获取应用参数
ServletContext sc = this.getServletContext();
String encode = sc.getInitParameter("encode");
// 1.解决requestpost请求乱码 解决response输出数据乱码
request.setCharacterEncoding(encode);
response.setCharacterEncoding(encode);
response.setContentType("text/html;charset=" + encode);
// 2.获取请求参数
String username = request.getParameter("username");
String password = request.getParameter("password");
String password2 = request.getParameter("password2");
String nickname = request.getParameter("nickname");
String email = request.getParameter("email");
String valistr = request.getParameter("valistr");
// 3.检查数据有效性 如果有问题 向浏览器报错
if (username == null || "".equals(username)) {
throw new MsgException("用户名不能为空!");
}
if (password == null || "".equals(password)) {
throw new MsgException("密码不能为空!");
}
if (password2 == null || "".equals(password2)) {
throw new MsgException("确认密码不能为空!");
}
if (!password.equals(password2)) {
throw new MsgException("两次密码不一致!");
}
if (nickname == null || "".equals(nickname)) {
throw new MsgException("昵称不能为空!");
}
if (email == null || "".equals(email)) {
throw new MsgException("邮箱不能为空!");
}
if (!email.matches("^\\w+@\\w+(\\.\\w+)+$")) {
throw new MsgException("邮箱格式不正确!");
}
if (valistr == null || "".equals(valistr)) {
throw new MsgException("验证码不能为空!");
}
// 4.存入数据库
// 判断账号是否重复
conn = MySqlUtils.getConn();
stat = conn.prepareStatement("select * from user where username=?");
stat.setString(1, username);
rs = stat.executeQuery();
if (rs.next()) {// 账号重复
throw new MsgException("账号重复");
} else {// 账号不重复
stat = conn
.prepareStatement("insert into user values(?,?,?,?)");// 账号,密码,昵称,邮箱
stat.setString(1, username);
stat.setString(2, password);
stat.setString(3, nickname);
stat.setString(4, email);
stat.executeUpdate();
}
// 5.向浏览器报告成功 回到主页
response.getWriter().write("注册成功!正在前往主页------>>>");
response.setHeader("refresh", "1;url=/regist.html");
} catch (MsgException e) {
String msg = e.getMessage();
response.getWriter().write(msg);
response.setHeader("refresh", "1;url=/regist.html");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭数据库
MySqlUtils.close(conn, stat, rs);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
验证码【ajax+禁用缓存】
ajax:Asynchronous JavaScript and XML
原生方式:(例)
$.ajax({ url: "test.html", context: document.body, success: function(){
$(this).addClass("done");
}});
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
$.post(url, [data], [callback], [type])
前台的实时校验数据【先js吧--这个代码量有点大】
function checkForm() {
var flag = true;
flag = checkNull("username", "帐号不能为空!") && flag;
flag = checkNull("password", "密码不能为空!") && flag;
flag = checkNull("password2", "确认密码不能为空!") && flag;
flag = checkNull("nickname", "昵称不能为空!") && flag;
flag = checkNull("email", "邮箱不能为空!") && flag;
flag = checkNull("valistr", "验证不能为空!") && flag;
flag = checkEmail("email", "格式不正确,是个油箱吧!") && flag;
flag = checkPassword("password", "两次密码不一致!") && flag;
if (flag) {
document.getElementById("form1").submit();
} else {
return;
}
}
function checkPassword(name, msg) {
var password = document.getElementsByName(name)[0].value;
var password2 = document.getElementsByName(name + "2")[0].value;
setMsg(name + "2", "");
if ("" == password2) {
setMsg(name + "2", "确认密码不能为空!");
return false;
}
if (("" != password2) && (password != password2)) {
setMsg(name + "2", msg);
return false;
}
return true;
}
function checkEmail(name, msg) {
var value = document.getElementsByName(name)[0].value;
var reg = /^\w+@\w+(\.\w+)+$/;
setMsg(name, "");
if ("" == value) {
setMsg(name, "邮箱不能为空!");
return false;
}
if ((!reg.test(value)) && ("" != value)) {
setMsg(name, msg);
return false;
}
return true;
}
function checkNull(name, msg) {
var value = document.getElementsByName(name)[0].value;
setMsg(name, "");
if ("" == value) {
setMsg(name, msg);
return false;
}
return true;
}
function setMsg(name, msg) {
document.getElementById(name + "_msg").innerHTML = msg;
}
前台的实时校验数据【jQuery】
$(document).ready(
function() {
var canSubmit = true;//提交的标志
//用户名已存在检查(ajax)
$("input[name='username']").blur(
function() {
if ($("input[name='username']").val() != "") {
$.get("/UserNameHasServlet?"
+ $.param({
"username" : $(
"input[name='username']")
.val()
}), function(data) {
if ($.parseJSON(data).hasUser) {
//提示该账户已有
$("input[name='username']")
.next("span").text("用户名重复!");
canSubmit = false;
} else {
$("input[name='username']")
.next("span").text("");
canSubmit = true;
}
});
}
});
//两次密码的一致性检验(失去焦点)
$("input[name='password2']").blur(
function() {
if ($("input[name='password2']").val() != "") {
if ($("input[name='password']").val() != $(
"input[name='password2']").val()) {//密码不一致
$("input[name='password2']").next("span")
.text("密码不一致!");
canSubmit = false;
} else {
$("input[name='password2']").next("span")
.text("");
canSubmit = true;
}
}
});
//检查邮箱的格式是否正确
$("input[name='email']").blur(function() {
var email_Reg = /^\w+@\w+(\.\w+)+$/;
if ($(this).val() != "" && email_Reg.test($(this).val())) {
$(this).next("span").text("");
canSubmit = true;
} else {
$(this).next("span").text("邮箱格式不正确!");
canSubmit = false;
}
});
//验证码切换(点击事件)
$("#yzm_img").click(
function() {
$(this).attr(
"src",
"/ValiImageServlet?time="
+ new Date().getTime());
});
//表单提交事件
$("form").submit(function() {
//判断所有的输入框是否为空
$.each($("input[type!='submit']"), function() {
if ($(this).val() == "") {//密码不一致
$(this).nextAll("span").text("数据不能为空!");
canSubmit = false;
} else {
$(this).nextAll("span").text("");
canSubmit = true;
}
});
return canSubmit;
});
});
验证码的生成过程【没你想的那么难】
package com.easymall.ser;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class ValiImageServlet extends HttpServlet {
// 背景参数
private int base = 30;
private int height = base;
private int width = base * 4;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 禁止浏览器缓存图片
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Progma", "no-cache");
resp.setDateHeader("Expires", 0);
// 创建内存中的图片
BufferedImage di = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取画布画背景
Graphics2D g2 = (Graphics2D) di.getGraphics();
// 填充矩形
g2.setColor(Color.white);
g2.fillRect(0, 0, width, height);
// 绘制边框
g2.setColor(Color.red);
g2.drawRect(0, 0, width - 1, height - 1);
// 写字
g2.setFont(new Font("微软雅黑", Font.BOLD, 25));
for (int i = 0; i < 4; i++) {
g2.setColor(new Color(getRandom(0, 255),getRandom(0, 255),getRandom(0, 255)));
int temp = getRandom(-45, 45);
g2.rotate(temp / 180.0 * Math.PI, 10 + 30 * i, 20);
g2.drawString(Integer.toString(getRandom(0, 10)), 10 + 30 * i, 20);
g2.rotate(-temp / 180.0 * Math.PI, 10 + 30 * i, 20);
}
// 画干扰线
for (int i = 0; i < 3; i++) {
g2.setColor(new Color(getRandom(0, 255),getRandom(0, 255),getRandom(0, 255)));
g2.drawLine(getRandom(0, width), getRandom(0, height),
getRandom(0, width), getRandom(0, height));
}
// 画干扰点
for (int i = 0; i < 5; i++) {
g2.setColor(new Color(getRandom(0, 255),getRandom(0, 255),getRandom(0, 255)));
g2.drawOval(getRandom(0, width), getRandom(0, height), 5, 5);
}
// 画出图片
ImageIO.write(di, "JPG", resp.getOutputStream());
// 关闭画布
g2.dispose();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
// 获取随机数
private int getRandom(int start, int end) {
Random random = new Random();
return start + random.nextInt(end - start);
}
}
用户名校验【ajax所联系的servlet】
package com.easymall.ser;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.easymall.utils.MySqlUtils;
public class UserNameHasServlet extends HttpServlet {
private Connection conn = null;
private PreparedStatement stat = null;
private ResultSet rs = null;
boolean hasUser = true;// 默认数据库有--防止出错
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// 获取用户名并解决乱码
String username = new String(req.getParameter("username").getBytes(
"iso8859-1"), "utf-8");
System.out.println(username);
// 查询数据库中是否有此用户
conn = MySqlUtils.getConn();
stat = conn
.prepareStatement("select * from user where username=? ");
stat.setString(1, username);
rs = stat.executeQuery();
hasUser = rs.next();// 用户名重复为true
System.out.println(hasUser);
} catch (SQLException e) {
e.printStackTrace();
} finally {
MySqlUtils.close(conn, stat, rs);
}
// 返回json格式的数据
resp.getWriter().write("{\"hasUser\":" + hasUser + "}");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
自定义异常类
package com.easymall.exception;
@SuppressWarnings("serial")
public class MsgException extends RuntimeException {
public MsgException() {
}
public MsgException(String msg) {
super(msg);
}
}
mysql工具类
package com.easymall.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class MySqlUtils {
// 创建数据库连接池--数据连接池只允许有一个
private static ComboPooledDataSource cpds = new ComboPooledDataSource();
// 将构造函数私有化,不允许创建该实例
private MySqlUtils() {
super();
}
// 获取连接
public static Connection getConn() {
Connection conn = null;
try {
conn = cpds.getConnection();
} catch (SQLException e) {
// 没有获得数据库连接的异常处理[有待详细处理]
throw new RuntimeException(e);
}
return conn;
}
// 关闭资源
public static void close(Connection conn, Statement stat, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
stat = null;
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs = null;
}
}
}
}
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/easymall
c3p0.user=root
c3p0.password=root
CREATE TABLE `user` (
`username` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`nickname` varchar(32) NOT NULL,
`email` varchar(32) NOT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
web.xml
encode
utf-8
RegisteSer
com.easymall.ser.RegisteSer
UserNameHasServlet
com.easymall.ser.UserNameHasServlet
ValiImageServlet
com.easymall.ser.ValiImageServlet
RegisteSer
/RegisteSer
UserNameHasServlet
/UserNameHasServlet
ValiImageServlet
/ValiImageServlet
index.jsp