用户注册,重复用户名时的处理

1.首先,在UserDaoImpl中添加一个判断是否有重名的方法

public boolean save_query(User u){
Connection con = null;
try{
con = DBUtil.getConnection();
String sqlQuery = "select count(*) from user_login where user_name = ?";
PreparedStatement psQuery = con.prepareStatement(sqlQuery);
psQuery.setString(1, u.getUser_name());
ResultSet rs = psQuery.executeQuery();
rs.next();
int count = rs.getInt(1);
if(count > 0){
return true;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}


2.在MainServlet模块中的注册方法中添加判断的代码块(红色部分):

private void access(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException{
//1.获取表单中的数据
req.setCharacterEncoding("utf-8");
String name = req.getParameter("user_name");
String pwd = req.getParameter("paw");
//System.out.println(name);
String email = req.getParameter("mail");
//2.处理数据
UserDao dao = new UserDaoImpl();
User u = new User();
u.setUser_name(name);

//如果用户名存在,则跳转到提示错误页面
if(dao.save_query(u)){
res.sendRedirect("access_error.do");
return;
}

u.setPwd(pwd);
u.setEmail(email);
dao.save(u);
//3.重定向到商品管理
//当前: /militaryShop/access.do
//目标: /militaryShop/login.do
res.sendRedirect("login.do");
}


3.增加一个错误页面access_error.jsp,当判断到有用户名重复时,页面跳转到输入密码的login页面或者重新输入注册信息的页面,

js代码如下:

<script language="javascript" type="text/javascript">
            var timer;
            //启动跳转的定时器
            function startTimes() {
                timer = window.setInterval(showSecondes,1000);
            }


            var i = 5;
            function showSecondes() {
                if (i > 0) {
                    i--;
                    document.getElementById("secondes").innerHTML = i;
                }
                else {
                    window.clearInterval(timer);

   //跳转到login界面
                    location.href = "login.do";
                }
            }


            //取消跳转,返回原注册界面
            function resetTimer() {
                if (timer != null && timer != undefined) {
                    window.clearInterval(timer);
                    location.href = "toAccess.do";
                }
            }
        </script> 


调试成功!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值