一、JavaEE三层架构&环境搭建
包结构(先建包): web层 com.atguigu.web/servlet/controller
service层 com.atguigu.service service接口包 com.atguigu.service.impl service接口实现类
dao持久层 com.atguigu.dao Dao接口包 com.atguigu.dao.impl Dao接口实现类
实体bean对象 com.atguigu.pojp/entity/domain/bean JavaBean类
测试包 com.atguigu.test/junit
工具类 com.atguigu.utils
二、流程
1. 先创建书城需要的数据库和表(注册功能)
用户名称、密码、邮箱
drop database if exists book;
create DATABASE book;
use book;
create TABLE t_user(
`id` int primary key auto_increment,
`username` varchar(20) not null unique,
`password` varchar(32) not null,
`email` varchar(200)
);
insert into t_user(`username`,`password`,`email`) values('admin','admin','admin@126.com');
select * from t_user;
2. 编写数据库表对应的JavaBean对象
pojo包下建一个User类,自动生成一些code…(ORM思想)
3. 编写工具类Utils
package com.atguigu.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcUtils {
private static DruidDataSource dataSource;
static {
try
{
Properties properties=new Properties();
InputStream is=JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(is);
dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
}catch (Exception e)
{
e.printStackTrace();
}
}
public static Connection getConnection()
{
Connection conn= null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn)
{
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
编写测试
public class JdbcUtilsTest {
@Test
public void testJdbcUtils()
{
System.out.println(JdbcUtils.getConnection());
}
}
4. 编写baseDAO
package com.atguigu.dao.impl;
import com.atguigu.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public abstract class BaseDao {
private QueryRunner queryRunner=new QueryRunner();
public int update(String sql,Object... args)
{
Connection conn= JdbcUtils.getConnection();
try {
return queryRunner.update(conn,sql,args);
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
public <T> T queryForOne(Class<T> type, String sql,Object... args)
{
Connection conn=JdbcUtils.getConnection();
try {
return queryRunner.query(conn,sql,new BeanHandler<T>(type),args);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public <T> List<T> queryForList(Class<T> type,String sql,Object... args)
{
Connection conn=JdbcUtils.getConnection();
try {
List<T> result=queryRunner.query(conn,sql,new BeanListHandler<T>(type),args);
return result;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Object queryForSingleValue(String sql,Object... args)
{
Connection conn=JdbcUtils.getConnection();
try {
return queryRunner.query(conn,sql,new ScalarHandler(),args);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
5. 编写UserDao和测试
测试:ctrl+shift+T 在UserDao中。用的是JUnit4,勾上要测试的方法
package com.atguigu.dao.impl;
import com.atguigu.pojo.User;
public interface UserDao {
public User queryUserByUsername(String Username);
public int saveUser(User user);
public User queryUserByUsernameAndPassword(String Username,String password);
}
package com.atguigu.dao.impl;
import com.atguigu.pojo.User;
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=?";
User user = queryForOne(User.class, sql, username);
return user;
}
@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 queryUserByUsernameAndPassword(String username, String password) {
String sql="select `id`,`username`,`password`,`email` from t_user where username=? and password=?";
User user = queryForOne(User.class, sql, username,password);
return user;
}
}
测试:
package com.atguigu.test;
import com.atguigu.dao.impl.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;
import com.atguigu.pojo.User;
import org.junit.Test;
import static org.junit.Assert.*;
public class UserDaoTest {
UserDao userDao=new UserDaoImpl();
@Test
public void queryUserByUsername() {
if(userDao.queryUserByUsername("admin")==null)
{
System.out.println("用户名可用");
}
else System.out.println("用户名已存在!");
}
@Test
public void saveUser() {
User newUser=new User(null,"zjx1","123","zjx@163.com");
System.out.println(userDao.saveUser(newUser));
}
@Test
public void queryUserByUsernameAndPassword() {
if(userDao.queryUserByUsernameAndPassword("admin","admin")==null)
System.out.println("用户名或密码错误,登录失败");
else System.out.println("查询成功");
}
}
6. 编写UserService和测试
package com.atguigu.service;
import com.atguigu.pojo.User;
public interface UserService {
public void registerUser(User user);
public User login(User user);
public boolean existsUsername(String username);
}
package com.atguigu.test;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import org.junit.Test;
import static org.junit.Assert.*;
public class UserServiceTest {
UserService userService=new UserServiceImpl();
@Test
public void registerUser() {
userService.registerUser(new User(null,"1","1","1"));
}
@Test
public void login() {
System.out.println(userService.login(new User(null,"1","1","1")));
}
@Test
public void existsUsername() {
System.out.println(userService.existsUsername("1"));
if(userService.existsUsername("1")) System.out.println("用户名已经存在");
else System.out.println("用户名不存在");
}
}
7. 注册功能业务逻辑
package com.atguigu.web;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RegisterServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
String code = req.getParameter("code");
if("abcde".equalsIgnoreCase(code))
{
if(userService.existsUsername(username)==false)
{
userService.registerUser(new User(null,username,password,email));
req.getRequestDispatcher("pages/user/regist_success.html").forward(req,resp);
}
else
{
System.out.println("用户名"+username+"已存在");
req.getRequestDispatcher("pages/user/regist.html").forward(req,resp);
}
}else
{
System.out.println("验证码错误");
req.getRequestDispatcher("pages/user/regist.html").forward(req,resp);
}
}
}
|