JavaWeb_书城项目配置步骤及流程

JavaWeb_书城项目配置步骤及流程_第1张图片

1.新建Java Enterprise项目,在java下新建相关软件包,并将web项目导入

JavaWeb_书城项目配置步骤及流程_第2张图片

2.新建数据库表,新建实例,编写数据库连接工具类和数据库关闭连接工具类,测试

JavaWeb_书城项目配置步骤及流程_第3张图片

package pojo;

public class t_user {
    private int id;
    private String username;
    private String password;
    private String email;

    public t_user() {
    }

    public t_user(int id, String username, String password, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

    @Override
    public String toString() {
        return "t_user{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}
public class JDBCUtils {
    /**
     * 数据库连接工具类
     */
    private static DataSource dataSource;
    static {
        try {
            Properties properties=new Properties();
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties"));
            //properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            System.out.println(properties.getProperty("username"));
            dataSource= DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        Connection connection=null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    /**
     * 数据库关闭工具类
     */
    public static  void getConnectionClose(Connection connection){
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

 driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/bookproject?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC

username=root

password=123456

注:idea2020版本后,在Java Enterprise项目中,在写jdbc.properties时,默认路径不放在src之下,要放到resources目录下,并将resources提升为根路径。不然空指针异常。

流程:https://blog.csdn.net/FoverLove1314/article/details/118991697

步骤:

1.右击resources-->Mark Directory as点击-->Resources Root

2.在 File -->Project Structure–>Modules–>Resources 中找到resources目录-->右击选中Resources-->OK

3.编写通用的增删改和查询语句,用于灵活调用

注:abstract和接口和实现类关系:实现类继承abstract实现接口

public abstract class BaseDao {
    QueryRunner queryRunner=new QueryRunner();

    /**
     * 通用的增、删、改方法
     */
    public int update(String sql,Object ...args){
        Connection connection = JDBCUtils.getConnection();
        try {
            return queryRunner.update(connection,sql,args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.getConnectionClose(connection);
        }
        return -1;
    }

    /**
     * 通用的查询对象
     */
    public  T selectObject(String sql,Class type,Object ... args){
        Connection connection = JDBCUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new BeanHandler<>(type),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.getConnectionClose(connection);
        }
        return null;
    }

    /**
     * 通用查询对象组成集合
     */
    public  List selectObjectList(String sql,Class type,Object ... args){
        Connection connection = JDBCUtils.getConnection();
        try {
            return queryRunner.query(connection, sql, new BeanListHandler<>(type), args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.getConnectionClose(connection);
        }
        return null;
    }

    /**
     * 通用查询特定值
     */
    public Object selectsingle(String sql,Object ...args){
        Connection connection = JDBCUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new ScalarHandler(),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.getConnectionClose(connection);
        }
        return null;
    }
}

4.编写UserDao和测试类

JavaWeb_书城项目配置步骤及流程_第4张图片

public interface UserDao {

    /**
     * 用于用户名查询用户是否存在
     */
    public t_user selectUser(String username);

    /**
     * 用于用户名和密码查询用户信息
     */
    public t_user selectUser1(String username,String password);

    /**
     * 保存用户信息
     */
    public int inertUser(t_user t);
}
public class UserDaoImpl extends BaseDao implements UserDao {

    @Override
    public t_user selectUser(String username) {
        String sql="SELECT id,username,password,email FROM t_user WHERE username=?";
        return selectObject(sql,t_user.class,username);
    }

    @Override
    public t_user selectUser1(String username, String password) {
        String sql="SELECT id,username,password,email FROM t_user WHERE username=? and password=?";
        return selectObject(sql,t_user.class,username,password);
    }

    @Override
    public int inertUser(t_user t) {
        String sql="INSERT INTO t_user VALUES (null,?,?,?)";
        return update(sql,t.getUsername(),t.getUsername(),t.getPassword());
    }
}
public class DaoTest {
    UserDao userDao=new UserDaoImpl();

    @Test
    public void selectUser(){
        t_user admin = userDao.selectUser("admin1");
        if (admin!=null){
            System.out.println("用户名以存在!");
        }else {
            System.out.println("用户名不存在");
        }
    }

    @Test
    public void selectUser1(){
        if (userDao.selectUser1("admin","123456")==null){
            System.out.println("用户名或密码错误");
        }else {
            System.out.println("登陆成功");
        }
    }

    @Test
    public void inertUser(){
        t_user t=new t_user();
        t.setUsername("admin1");
        t.setPassword("123123");
        t.setEmail("[email protected]");
        if (userDao.inertUser(t)!=-1){
            System.out.println("用户添加成功");
        }else {
            System.out.println("用户添加失败");
        }
    }
}

5.编写UsetService和测试类

public interface UserService {
    /**
     * 注册用户
     * @return
     */
    public int registUser(t_user t);

    /**
     * 根据用户名和密码登陆
     */
    public t_user login(t_user t);

    /**
     * 检查用户名是否存在
     */
    public boolean existusername(String username);
}
public class UserServiceImpl implements UserService {
    UserDao userDao=new UserDaoImpl();
    @Override
    public int registUser(t_user t) {
        return userDao.inertUser(t);
    }

    @Override
    public t_user login(t_user t) {
        return userDao.selectUser1(t.getUsername(),t.getPassword());
    }

    @Override
    public boolean existusername(String username) {
        if (userDao.selectUser(username)!=null){
            return true;
        }
        return false;
    }
}
public class ServiceTest {
    UserService userService=new UserServiceImpl();

    @Test
    public void registUser(){
        t_user t=new t_user();
        t.setUsername("admin2");
        t.setPassword("123456");
        t.setEmail("[email protected]");
        userService.registUser(t);
    }

    @Test
    public void login(){
        t_user t=new t_user();
        t.setUsername("admin2");
        t.setPassword("admin2");
        if (userService.login(t)!=null){
            System.out.println("登陆成功");
        }else {
            System.out.println("用户名或密码错误");
        }
    }

    @Test
    public void existusername(){
        boolean admin1 = userService.existusername("admin3");
        if (admin1==false){
            System.out.println("用户名不存在");
        }else{
            System.out.println("用户存在");
        }
    }


}

5.用户注册功能实现

注:base标签用于改变相对路径的参考,所有进行跳转的页面都可以用base标签实现

注:ClassLoader.getSystemClassLoader()获取的是系统类加载器也就是AppClassLoader,但是tomcat类加载器是WebappClassLoader,资源目录在/WEB-INF/classes/下,用系统类加载器获取不到文件空指针。在Tomcat中配置文件加载应写成以下形式,不然会出现空指针异常。

//properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties"));
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));


	
		
		会员注册页面
		
		
		
		
	
	
	
		
书城.Copyright ©2019


    
        Regist
        web.Regist
    
    
        Regist
        /regist
    
public class Regist extends HttpServlet {
    private  UserService userService=new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据name值进行获取
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        if ("bnbnp".equalsIgnoreCase(code)){
            if (userService.existusername(username)){
                System.out.println("用户名已存在");
                req.getRequestDispatcher("/pages/user/regist.html").forward(req,resp);
            }else {
                userService.registUser(new t_user(4,username,password,email));
                req.getRequestDispatcher("/pages/user/regist_success.html").forward(req,resp);
            }
        }else {
            req.getRequestDispatcher("/pages/user/regist.html").forward(req,resp);
        }

    }
}

6.Debug

注:如果idea中启动Tomcat慢需要点击。

JavaWeb_书城项目配置步骤及流程_第5张图片

debug相关解释:

JavaWeb_书城项目配置步骤及流程_第6张图片

 JavaWeb_书城项目配置步骤及流程_第7张图片

 7.登陆功能实现





会员登录页面




		
书城.Copyright ©2019
 
        Login
        web.Login
    
    
        Login
        /login
    
public class Login 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");
        t_user t=new t_user();
        t.setUsername(username);
        t.setPassword(password);
        if (userService.login(t)!=null){
            req.getRequestDispatcher("/pages/user/login_success.html").forward(req,resp);
        }else {
            req.getRequestDispatcher("/pages/user/login.html").forward(req,resp);
        }
    }
}

你可能感兴趣的:(java,数据库,mybatis)