一、数据库连接c3p0--工具类
public class JDBCUtils {
//数据源是一个重量级对象,在项目中有一个实例即可,所以声明成静态成员
private static DataSource dataSource = new ComboPooledDataSource ("webDataSource" );
public static Connection getConnection(){
Connection connection = null;
try {
connection = dataSource . getConnection() ;
} catch ( SQLException e ) {
e . printStackTrace() ;
}
return connection;
}
/**
* 释放数据库连接
* @param connection
*/
public static void releaseConnection (Connection connection ) {
try {
if (connection != null ){
connection . close() ;
}
} catch ( SQLException e ) {
e . printStackTrace() ;
}
}
}
二、 规定 Dao实现类的功能,上层程序根据接口功能使用 Dao实现类。当实现类发生改变时,只要接口不变,上层的调用方式就不需要改变。
DAO接口定义:
public interface DAO <T > {
//实现数据库的增删改
void update (Connection conn ,String sql ,Object ... params) ;
//查询数据库返回单一对象
T getBean (Connection conn ,String sql ,Object ... params) ;
//查询数据库返回对象的集合
List < T> getBeanList (Connection conn ,String sql ,Object ... params) ;
}
UserDao接口定义:
public interface UserDAO {
//1.根据用户名和密码获取用户对象
User getUser (User user) ;
//2.根据用户名获取用户对象
User getUserByName (User user) ;
//3.保存用户对象
void saveUser (User user) ;
}
三、DAO实现类
DaoImpl实现类:
// Dao基类,使用时通过子类继承,传入泛型参数。创建子类对象使用。
public class DaoImpl <T > implements DAO <T >{
//使用QueryRunner对象
private QueryRunner runner =new QueryRunner() ;
//定义泛型对象
private Class< T > beanType =null;
public DaoImpl () {
Type superClass =this. getClass() . getGenericSuperclass() ;
if (superClass instanceof ParameterizedType){
ParameterizedType pt =( ParameterizedType) superClass ;
Type [] types = pt .getActualTypeArguments ();
beanType =( Class) types [0 ]; //获取泛型参数T,获得实际类型值对应的Class类对象
}
}
@Override
public void update( Connection conn, String sql, Object... params ) {
try {
runner .update (conn , sql, params) ;
} catch ( Exception e ) {
e . printStackTrace() ;
}
}
@Override
public T getBean( Connection conn, String sql, Object... params ) {
T t =null ;
try {
t = runner . query( conn, sql , new BeanHandler <T >( beanType) , params) ;
} catch ( Exception e ) {
e . printStackTrace() ;
}
return t;
}
@Override
public List< T > getBeanList (Connection conn , String sql , Object ... params ) {
List < T> beanList =null;
try {
beanList = runner . query( conn, sql , new BeanListHandler <>( beanType) ,params );
} catch ( Exception e ) {
e . printStackTrace() ;
}
return beanList;
}
}
UserDaoImpl实现类:
public class UserDaoImpl extends DaoImpl < User> implements UserDAO {
@Override
public User getUser (User user) {
Connection conn =JDBCUtils . getConnection() ;
String sql ="SELECT
user_id userId,user_name userName,user_pwd pwd,user_email email FROM `user`"
+ "
WHERE user_name=? AND user_pwd=?" ;
User querUser = this. getBean( conn , sql , user. getUserName() , user. getPwd()) ;
JDBCUtils . releaseConnection( conn) ;
return querUser;
}
@Override
public User getUserByName (User user) {
Connection conn = JDBCUtils .getConnection ();
String sql ="SELECT
user_id userId,user_name userName,user_pwd pwd,user_email email FROM `user`"
+ "
WHERE user_name=? " ;
User queryUser = this. getBean( conn, sql , user. getUserName()) ;
JDBCUtils . releaseConnection( conn) ;
return queryUser;
}
@Override
public void saveUser( User user) {
Connection conn =JDBCUtils . getConnection() ;
String sql = "INSERT
INTO `user` (user_name,user_pwd,user_email) VALUES(?,?,?)";
System . out. println( user .getUserName ());
this. update( conn , sql , user. getUserName() , user. getPwd() , user. getEmail()) ;
JDBCUtils . releaseConnection( conn) ;
}
}
测试UserDAO
public class UserDaoTest {
private UserDaoImpl userDao =new UserDaoImpl() ;
@Test
public void testGetUser() {
User user =userDao . getUser( new User( null, "tzq", "123" , null ));
System . out. println( user) ;
//User [userId=1, userName= tzq, pwd=123, [email protected]com]
}
@Test
public void testGetUserByName() {
User user =userDao . getUserByName( new User ( null, "admin" , null, null)) ;
System . out. println( user) ;
//User [userId=2, userName= admin, pwd=122, [email protected]com]
}
@Test
public void testSaveUser() {
User user = new User( null, "谭正强", "123456", "[email protected]" );
userDao .saveUser (user );
System . out. println( "数据保存成功" );
}
}
四、定义判断能否登陆的接口方法
public interface UserServiceInter {
//根据用户名、密码校验用户能否登陆
boolean login (User user) ;
//根据用户名验证能否注册,如果可以注册,则将User对象保存到数据库中
boolean regist (User user) ;
}
五、创建UserServiceInter 接口的实现类UserServiceImpl
public class UserServiceImpl implements UserServiceInter {
private UserDAO userDao =new UserDaoImpl() ;
@Override
public boolean login( User user) {
User queryuser = userDao. getUser( user) ;
return queryuser!= null;
}
@Override
public boolean regist( User user) {
User userByName = userDao. getUserByName (user );
if (userByName ==null ){
userDao .saveUser (user );
return true ;
} else{
return false ;
}
}
}
测试UserService
public class UserServiceTest {
private UserServiceInter userService = new UserServiceImpl ();
@Test
public void testLogin() {
User user =new User ( null, "tzq" , "123" , null );
boolean login = userService .login (user );
if (login ){
System . out. println( "登陆成功" );
} else{
System . out. println( "登陆失败" );
}
}
@Test
public void testRegist() {
User user = new User( null, "tzqq", "123", "[email protected]" );
boolean regist = userService .regist (user );
if (regist ) {
System . out. println( "注册成功" );
} else{
System . out. println( "注册失败" );
}
}
}
六、创建登陆以及注册Servlet
登陆处理逻辑:接受请求→处理请求→转发
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L ;
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
//1.获取请求参数
String userName = request. getParameter( "userName" );
String pwd = request .getParameter ("pwd" );
User user = new User( null, userName , pwd , null );
//2.处理请求参数
UserServiceImpl userServiceImpl = new UserServiceImpl ();
boolean login = userServiceImpl . login( user) ;
//3.派发页面
if (login ) {
//如果登录成功转发到loginSuccess.html
//①转发是服务器端完成,所以路径由服务器解析
//②第一个“/”代表当前Web应用的根目录
request . getRequestDispatcher( "/client/user/loginSuccess.html" ). forward( request , response );
} else{
//如果登录失败重定向到loginError.html
//①重定向中指定的地址是浏览器解析
//②第一个“/”代表当前服务器,还需要进一步指定当前Web应用的虚拟路径,通常为当前Web工程的名字
response . sendRedirect( "/BookStore02/client/user/loginError.html" );
}
}
}
注册处理逻辑:接受请求→处理请求→转发
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L ;
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
//1.获取请求参数
String userName = request. getParameter( "userName" );
String pwd = request .getParameter ("pwd" );
String email = request .getParameter ("email" );
User user = new User( null, userName , pwd , email) ;
//2.处理请求参数
UserServiceImpl userServiceImpl = new UserServiceImpl ();
boolean regist = userServiceImpl . regist( user) ;
//3.派发页面
if (regist ) {
//如果注册成功转发到registSuccess.html
request . getRequestDispatcher( "/client/user/registSuccess.html" ). forward( request , response );
} else{
//如果注册失败重定向到registError.html
response . sendRedirect( "/BookStore02/client/user/registError.html" );
}
}
}
项目图展示: