JavaWeb——登录注册功能实现
文章目录
- JavaWeb——登录注册功能实现
-
- jdbcUtils
-
- 实体类
- Dao层(持久层)
-
- BaseDao
- UserDao接口
- UserDaoImpl实现类
- Service业务层
-
- UserService接口
- UserServiceImpl实现类
- web层(Servlet)
-
jdbcUtils
public class JDBCutils {
public static void closeResource(Connection conn, Statement ps){
try {
if (ps != null) {
ps.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void closeResource(Connection conn, Statement ps, ResultSet rs){
try {
if (ps != null) {
ps.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(rs!=null){
rs.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static Connection getConnection1(){
Connection conn = null;
try {
Properties pro = new Properties();
pro.load(JDBCutils.class.getClassLoader().getResourceAsStream("druid.properties"));
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
conn = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return conn;
}
public static void main(String[] args) {
System.out.println(getConnection1());
}
}
druid配置文件
- mysql8.0配置(mysql5.0的配置有些许不同,具体看我以前的博客JDBC)
#mysql8.0配置
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=123456
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
实体类
public class User {
private Integer id;
private String username;
private String password;
private String email;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
public User(Integer id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Dao层(持久层)
BaseDao
public class BaseDao {
private QueryRunner queryRunner= new QueryRunner();
public int update(String sql,Object...args) {
Connection conn = JDBCutils.getConnection1();
try {
return queryRunner.update(conn,sql,args);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCutils.closeResource(conn,null);
}
return -1;
}
public <T>T queryForone(Class<T> clazz, String sql, Object ... args){
Connection conn = JDBCutils.getConnection1();
try {
return queryRunner.query(conn, sql,new BeanHandler<T>(clazz), args);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCutils.closeResource(conn,null);
}
return null;
}
public <T> List<T> queryForList(Class<T> clazz, String sql, Object ... args){
Connection conn = JDBCutils.getConnection1();
try {
return queryRunner.query(conn, sql,new BeanListHandler<T>(clazz), args);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCutils.closeResource(conn,null);
}
return null;
}
public Object queryForSingleValue(String sql,Object ... args){
Connection conn = JDBCutils.getConnection1();
try {
return queryRunner.query(conn, sql, new ScalarHandler(),args);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCutils.closeResource(conn,null);
}
return null;
}
}
UserDao接口
public interface UserDao {
public User queryUserByUsername(String username);
public int saveUser(User user);
public User queryUsernameAndPassword(String username,String password);
}
UserDaoImpl实现类
public class UserDaoImpl extends BaseDao implements UserDao{
@Override
public User queryUserByUsername(String username) {
String sql="select id,username,password,email from t_user where username = ?";
return queryForone(User.class,sql,username);
}
@Override
public int saveUser(User user) {
String sql="insert into t_user(username,password,email)values(?,?,?)";
return update(sql,user.getUsername(),user.getPassword(),user.getEmail());
}
@Override
public User queryUsernameAndPassword(String username, String password) {
String sql=" select id,username,password,email from t_user where username=? and password = ? ";
return queryForone(User.class,sql,username,password);
}
}
Service业务层
UserService接口
public interface UserService {
public void registerUser(User user);
public User login(User user);
public boolean existsUserName(String userName);
}
UserServiceImpl实现类
public class UserServiceImpl implements UserService{
private UserDao userDao= new UserDaoImpl();
@Override
public void registerUser(User user) {
userDao.saveUser(user);
}
@Override
public User login(User user) {
return userDao.queryUsernameAndPassword(user.getUsername(),user.getPassword());
}
@Override
public boolean existsUserName(String userName) {
if (userDao.queryUserByUsername(userName)==null){
return false;
}
return true;
}
}
web层(Servlet)
登陆的Servlet
@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User login = userService.login(new User(null, username, password, null));
if (login == null) {
request.setAttribute("msg","用户名或密码错误");
request.setAttribute("username",username);
request.getRequestDispatcher("pages/user/login.jsp").forward(request, response);
}else {
request.getRequestDispatcher("pages/user/login_success.jsp").forward(request, response);
}
}
}
注册的Servlet
@WebServlet(name = "RegistServlet", value = "/registServlet")
public class RegistServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("表单数据来了<%@ page contentType=\"text/html;charset=UTF-8\" language=\"java\" pageEncoding=\"utf-8\" %>");
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String code = request.getParameter("code");
if ("abce".equals(code)) {
if (userService.existsUserName(username)) {
System.out.println("用户名已存在");
request.setAttribute("msg","用户名已存在");
request.setAttribute("username",username);
request.setAttribute("email",email);
request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
}else{
userService.registerUser(new User(null,username,password,email));
request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response);
}
}else {
request.setAttribute("msg","验证码错误");
request.setAttribute("username",username);
request.setAttribute("email",email);
System.out.println("验证码错误");
request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
}
}
}
- 上述验证码是写死的,可以暂时忽略
- 以上是基于MVC三层架构去书写,如有不懂即可评论区私信我