继续来做用户注册场景的验证问题,我们还有一个场景没有做,就是注册的时候没有判断用户名是否存在,如果存在就提醒用户换一个用户名再注册。
1.dao接口添加一个根据用户名查找方法
package com.anthony.dao;
import com.anthony.domain.User;
public interface UserDao {
/**
* 添加用户信息
* @param user
* @throws Exception
*/
public void addUser(User user) throws Exception;
/**
* 查找用户,返回一个User对象,例如欢迎你 xxx就需要用到返回user对象
* @param user
* @return
* @throws Exception
*/
public User findUser(User user) throws Exception;
/**
* 根据用户名查找数据库是否存在
* @param name
* @return
* @throws Exception
*/
public boolean findUserByName(String name) throws Exception;
}
2.dao.impl实现具体方法
package com.anthony.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import com.anthony.dao.UserDao;
import com.anthony.domain.User;
import com.anthony.utils.DBUtils;
public class UserDaoImpl implements UserDao {
public void addUser(User user) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement("INSERT INTO users(username,password,email,birthday) VALUES(?,?,?,?)");
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(user.getBirthday());
ps.setString(4, date);
//执行sql语句,这里是注册,插入数据
int i = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtils.close(conn, ps, null);
}
}
public User findUser(User user) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
User u = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement("SELECT * FROM users WHERE username=? AND PASSWORD=?");
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
rs = ps.executeQuery();
if(rs.next()) {
u = new User();
u.setId(rs.getInt(1));
u.setUsername(rs.getString(2));
u.setPassword(rs.getString(3));
u.setEmail(rs.getString(4));
u.setBirthday(rs.getDate(5));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
DBUtils.close(conn, ps, rs);
}
return u;
}
public boolean findUserByName(String name) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement("SELECT * FROM users WHERE username=?");
ps.setString(1, name);
rs = ps.executeQuery();
//查到了,返回true
if(rs.next()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtils.close(conn, ps, rs);
}
return false;
}
}
3.在UserService接口中添加方法
这里接着前面代码,新增下面代码
/**
* 根据用户名查找用户是否存在
* @param name
* @return
* @throws UserExistException
*/
public boolean findUserByName(String name) throws UserExistException;
这里用到一个自定义异常类,所以下面我们要在exception包下新建这个异常类
4.自定义一个异常类
package com.anthony.exception;
public class UserExistException extends Exception {
public UserExistException() {
super();
}
public UserExistException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UserExistException(String message, Throwable cause) {
super(message, cause);
}
public UserExistException(String message) {
super(message);
}
public UserExistException(Throwable cause) {
super(cause);
}
}
5. service层具体方法实现
public boolean findUserByName(String name) throws UserExistException {
boolean b = false;
try {
b = userDao.findUserByName(name);
} catch (Exception e) {
e.printStackTrace();
}
if(b) {
throw new UserExistException("用户名已存在!");
}
return b;
}
7.RegServlet.java代码更改如下
package com.anthony.web.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import com.anthony.domain.User;
import com.anthony.domain.UserForm;
import com.anthony.exception.UserExistException;
import com.anthony.service.UserService;
import com.anthony.service.impl.UserServiceImpl;
public class RegServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//获取表单数据
UserForm uf = new UserForm();
try {
BeanUtils.populate(uf, req.getParameterMap());
} catch (Exception e1) {
e1.printStackTrace();
}
if(!uf.validate()) { //如果msg map集合不为空,说明输入条件不符合要求
req.setAttribute("uf", uf);
req.getRequestDispatcher("/register.jsp").forward(req, resp);
return; //出错,不需要往下走注册流程,所以这里需要return空来终止代码往下执行
}
User user = new User();
try {
//解决日期是字符串的异常
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.populate(user, req.getParameterMap());
//调用业务层方法/逻辑
UserService us = new UserServiceImpl();
//注册之前判断用户是否存在
us.findUserByName(user.getUsername());
us.register(user);
} catch (UserExistException e1) {
req.setAttribute("error", "用户名已存在");
req.getRequestDispatcher("/register.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
//分发转向
resp.getWriter().write("注册成功,2秒之后跳转到主页");
resp.setHeader("refresh", "2;url="+req.getContextPath()+"/index.jsp");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
8.register.jsp
添加显示错误消息“用户名已存在”
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/regServlet" method="post">
用户名:<input type="text" name="username" value="${uf.username}"/>${uf.msg.username}${error}<br/>
密码:<input type="password" name="password"/>${uf.msg.password}<br/>
确认密码:<input type="password" name="repassword"/>${uf.msg.repassword}<br/>
邮箱:<input type="text" name="email" value="${uf.email}"/>${uf.msg.email}<br/>
生日:<input type="text" name="birthday" value="${uf.birthday}"/>${uf.msg.birthday}<br/>
<input type="submit" value="注册">
</form>
</body>
</html>
测试效果