【Java前后端分离项目 01】

一、个人主页项目架构

浏览器-->java代码后端-->数据仓库。

Java代码是本次实现的核心部分,具体包括如下部分:

  • 工具类:DButil  -->(作用:1、连接数据库,2、关闭链接)
  • 数据操作工具:DAO(数据操作对象)-->(作用:往数据库里面存数据,取数据)
  • 数据服务:DBservice(针对DAO做一个服务,如果有多个对象存取数据时,就可以先找DBservice然后由DBservice去连接DAO进行存取操作)
  • Servlet  -->(作用:1、接浏览器数据,2、回复给浏览器结果),接到浏览器的格式是文字格式,把文字格式存到数据库里面需要打包成一个整体,这个整体就是bean类
  • bean类 -->(作用:封装信息)

以上三部分完成了Java代码和数据库直接的操作,下面写的是接受用户(浏览器)的信息的内容

完整的流程如下:

二、前端内容准备

1、idea-->file-->project Structure-->facets点击加号,选择web

2、把工程内web的文件全部复制到idea刚生成的web包里面

3、引用lib下的jar包:idea-->file-->project Structure-->Librarits点击加号,选择lib下面的jar-->ok

三、代码实现

1、先设置以上类对应的package

 

2、util包-->DButil类   (按照上图编写顺序,首先编写此类)

步骤:

1)连接数据库

  |--加载数据库驱动

  |--获取数据库连接

  |--将连接返回给工具的使用者   

2)断开连接

详细代码如下:

package com.wufq.util;

import java.sql.*;

/**
 * @Author wufq
 * @Date 2021/3/10 10:26
 * 此类作用:用于连接数据库,得到的结果是数据库的连接对象,链接对象具备了操作数据库的很多功能
 */
public class DButil {


//    1、连接数据库
    public static Connection getConn(){
        // 1、加载数据库驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //2、获取数据库连接
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://wufq.rwlb.rds.aliyuncs.com/wufqdb", "wufq", "123456");
            //3、将连接返回给工具的使用者
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;  //这个含义是程序执行到26行有返回时就执行28行,如果出现异常就会执行19-31行,然后返回一个null
    }

//    2、断开连接,释放资源
    
    //conn:断开执行连接,statement:断开执行sql语句命令/要释放的执行环境,resultSet:断开从数据仓库查询的结果命令/要释放的结果集
    public static void close(Connection conn, Statement statement, ResultSet resultSet){

        if(conn == null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(statement == null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(resultSet == null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

3、bean包-->User类

封装浏览器给予的信息对象

详细代码:

package com.wufq.bean;

/**
 * @Author wufq
 * @Date 2021/3/10 11:23
 * 存储用户的基本信息
 */
public class User {
    //用户编号
    private int id;
    //用户姓名
    private String name;
    //年龄
    private int age;
    //城市
    private String city;
    //详细住址
    private String address;
    //邮箱
    private String email;
    //电话
    private String phone;
    //微信
    private String weixin;
    //qq
    private String qq;
    //微博
    private String weibo;
    //性别
    private String sex;
    //简介
    private String description;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getWeixin() {
        return weixin;
    }

    public void setWeixin(String weixin) {
        this.weixin = weixin;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getWeibo() {
        return weibo;
    }

    public void setWeibo(String weibo) {
        this.weibo = weibo;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public User(int id, String name, int age, String city, String address, String email, String phone, String weixin, String qq, String weibo, String sex, String description) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.city = city;
        this.address = address;
        this.email = email;
        this.phone = phone;
        this.weixin = weixin;
        this.qq = qq;
        this.weibo = weibo;
        this.sex = sex;
        this.description = description;
    }

    public User() {
    }

    public User(String name, int age, String city, String address, String email, String phone, String weixin, String qq, String weibo, String sex, String description) {
        this.name = name;
        this.age = age;
        this.city = city;
        this.address = address;
        this.email = email;
        this.phone = phone;
        this.weixin = weixin;
        this.qq = qq;
        this.weibo = weibo;
        this.sex = sex;
        this.description = description;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (id != user.id) return false;
        if (age != user.age) return false;
        if (name != null ? !name.equals(user.name) : user.name != null) return false;
        if (city != null ? !city.equals(user.city) : user.city != null) return false;
        if (address != null ? !address.equals(user.address) : user.address != null) return false;
        if (email != null ? !email.equals(user.email) : user.email != null) return false;
        if (phone != null ? !phone.equals(user.phone) : user.phone != null) return false;
        if (weixin != null ? !weixin.equals(user.weixin) : user.weixin != null) return false;
        if (qq != null ? !qq.equals(user.qq) : user.qq != null) return false;
        if (weibo != null ? !weibo.equals(user.weibo) : user.weibo != null) return false;
        if (sex != null ? !sex.equals(user.sex) : user.sex != null) return false;
        return description != null ? description.equals(user.description) : user.description == null;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + age;
        result = 31 * result + (city != null ? city.hashCode() : 0);
        result = 31 * result + (address != null ? address.hashCode() : 0);
        result = 31 * result + (email != null ? email.hashCode() : 0);
        result = 31 * result + (phone != null ? phone.hashCode() : 0);
        result = 31 * result + (weixin != null ? weixin.hashCode() : 0);
        result = 31 * result + (qq != null ? qq.hashCode() : 0);
        result = 31 * result + (weibo != null ? weibo.hashCode() : 0);
        result = 31 * result + (sex != null ? sex.hashCode() : 0);
        result = 31 * result + (description != null ? description.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", city='" + city + '\'' +
                ", address='" + address + '\'' +
                ", email='" + email + '\'' +
                ", phone='" + phone + '\'' +
                ", weixin='" + weixin + '\'' +
                ", qq='" + qq + '\'' +
                ", weibo='" + weibo + '\'' +
                ", sex='" + sex + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

4、db包-->BaseDao接口 

 作用:制定对数据库存取的规范接口

package com.wufq.db;

/**
 * @Author wufq
 * @Date 2021/3/10 14:21
 * 作用:往数据库内存、取数据。由于是5个表格的存取,所以定义一个接口来规范,
 */
public interface BaseDao <T>{  //泛型:指定类型T,用于不同类型的都可以使用接口内的方法

    /*
    *用于规范操作数据库五个表格的新增数据规则
    * t :新增的数据t
    * rerurn 返回的新增结果,是一个数字,大于0表示新增成功
    * */
    int insert(T t);


    /*
    * 用于规范操作数据库五个表格的获取数据规则, 通过用户的编号来查找
    * rerurn返回的是获取的数据
    * */
    T findByUserId();
    
}

5、db包-->UserDaoImp
作用:真正实现用户信息插入数据库和从数据库里面取数据

步骤:

1)实现BaseDao接口,并实现接口内的insert、findByUserId方法

2)insert方法内进行一系列的操作

  |-- 得到连接

  |-- 得到执行环境

  |-- 向执行环境中,填充参数

  |-- 执行

  |-- 将数据的插入,返回结果

3)findByUserId方法内进行一系列的操作

  |-- 得到连接

  |-- 得到执行环境

  |-- 向执行环境中,填充参数

  |-- 执行并获取结果

详细代码:

package com.wufq.db;

import com.wufq.bean.User;
import com.wufq.util.DButil;

import java.sql.*;

/**
 * @Author wufq
 * @Date 2021/3/10 14:47
 */
public class UserDaoImp implements BaseDao<User>{

    private static final String SQL_INSERT = "insert into wufq_user(name,age,city,address,email,phone,weixin,qq,weibo,sex,description) values(?,?,?,?,?,?,?,?,?,?,?)";
    private static final String SQL_FIND_BY_USERID = "select * from wufq_user where id=?";


    @Override
    public int insert(User user) {
        //1、得到连接(连接数据库)
        Connection conn = DButil.getConn();
        PreparedStatement state=null;

        try {
            //2、得到执行环境    Statement.RETURN_GENERATED_KEYS:获取用户编号
            state = conn.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);

            //3、向执行环境中填充参数
            state.setString(1,user.getName());
            state.setInt(2,user.getAge());
            state.setString(3,user.getCity());
            state.setString(4,user.getAddress());
            state.setString(5,user.getEmail());
            state.setString(6,user.getPhone());
            state.setString(7,user.getWeixin());
            state.setString(8,user.getQq());
            state.setString(9,user.getWeibo());
            state.setString(10,user.getSex());
            state.setString(11,user.getDescription());

            //4、执行
            state.executeUpdate();

            //5、将数据插入以后会生成一个编号,通过编号判断结果
            if(state.getGeneratedKeys().next()){
                return state.getGeneratedKeys().getInt(1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //释放数据库资源
            DButil.close(conn,state,null);
        }

        return -1;  //如果程序在41行执行以后,没有返回正常的结果,程序会返回-1
    }

    @Override
    public User findByUserId(int ussrId) {
        //1、连接数据库
        Connection conn = DButil.getConn();

        try {
            //2、获取执行环境(预编译sql语句)
            PreparedStatement state = conn.prepareStatement(SQL_FIND_BY_USERID);

            //3、填充执行参数(sql语句中填充的参数)
            state.setInt(1,ussrId);

            //4、执行(执行sql语句,并判断返回结果)
            ResultSet resultSet = state.executeQuery();

            while (resultSet.next()){
                int age = resultSet.getInt("age");
                String name = resultSet.getString("name");
                String city = resultSet.getString("city");
                String address = resultSet.getString("address");
                String email = resultSet.getString("email");
                String phone = resultSet.getString("phone");
                String weixin = resultSet.getString("weixin");
                String qq = resultSet.getString("qq");
                String weibo = resultSet.getString("weibo");
                String sex = resultSet.getString("sex");
                String description = resultSet.getString("description");

                //把上面获取到的结果信息,封装成一个结果集
                User user = new User(name, age, city, address, email, phone, weixin, qq, weibo, sex, description);
                //5、返回结果并判断
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }

        return null;
    }
}

5、service包-->DBservice类

作用:不做任何操作,中转的作用,以至于我们对数据库做很多操作时,不至于对UserDaoImp做很多操作

详细代码:

package com.wufq.service;

import com.wufq.bean.User;
import com.wufq.db.BaseDao;
import com.wufq.db.UserDaoImp;

/**
 * @Author wufq
 * @Date 2021/3/10 17:07
 * 不做任何操作,中转的作用,以至于我们对数据库做很多操作时,不至于对UserDaoImp做很多操作
 */
public class DBservice {
    private static BaseDao<User> userDao = new UserDaoImp();

    //主要是找到UserDaoImp的insert方法
    public static int inserUser(User user){
        return userDao.insert(user);
    }

}

6、servlet包-->Userservlet类

作用:接受用户传入的数据

步骤:

1)避免乱码

2)接受浏览器传递的数据

3)调用service,将数据存储到数据库中

4)将存储的结果,分装成JSON格式,发送给浏览器

  |-- 封装json时,单独写一个result类用于输出json结果(其中json返回三要素:status,msg,data)

Userservlet类详细代码

package com.wufq.servlet;

import com.wufq.bean.Result;
import com.wufq.bean.User;
import com.wufq.service.DBservice;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;

/**
 * @Author wufq
 * @Date 2021/3/10 17:24
 */

@WebServlet("/v1/user/insert") //请求URL:http://域名/v1/user/insert
public class UserServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

       // 1)避免乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");

       // 2)接受浏览器传递的数据
        String name = request.getParameter("name");
        String city = request.getParameter("city");
        String address = request.getParameter("address");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String weixin = request.getParameter("weixin");
        String qq = request.getParameter("qq");
        String weibo = request.getParameter("weibo");
        String sex = request.getParameter("sex");
        String description = request.getParameter("description");
        String ageText = request.getParameter("age");
        int age = -1;
        try {
            age = Integer.parseInt(ageText);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

       // 3)调用service,将数据存储到数据库中
        User user = new User(name, age, city, address, email, phone, weixin, qq, weibo, sex, description);
        int userId = DBservice.inserUser(user);

        // 4)将存储的结果,分装成JSON格式,发送给浏览器
        Result r=null;

        if(userId>0){
            r = new Result(00000,"用户新增成功",userId);
        }else{
            r = new Result(-1,"用户新增失败");
        }

        String json = r.toJSON();//这时候就已经封装成json格式了

        response.getWriter().append(json);//发送给浏览器的代码通过response来实现的



    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        doPost(request,response);
    }
}

Result类详细代码

package com.wufq.bean;

import com.alibaba.fastjson.JSON;

/**
 * @Author wufq
 * @Date 2021/3/11 10:19
 */
public class Result {
    private int status;
    private String msg;
    private Object data;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Result(int status) {
        this.status = status;
    }

    public Result(int status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public Result(String msg, Object data) {
        this.msg = msg;
        this.data = data;
    }

    public Result(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public String toJSON(){
        return JSON.toJSONString(this);
    }
}

   

posted @ 2021-03-09 17:45  尘封~~  阅读(408)  评论(0编辑  收藏  举报