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>
调试成功!