您的位置:首页 > 其它

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

2016-04-24 17:39 239 查看
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> 

调试成功!

还有不完善的地方,各位见谅;如果有错误的地方,欢迎大家指出来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dao