【JavaWeb】基于前后端分离的JavaWeb小项目---新生报道案例的详细实现过程(下)

前言

致想要与本文一起实现案例的小伙伴:
本文包含实现的全部过程,有想要一起实现案例的小伙伴可以跟着一步一步实现。
由于本案例的重点是JavaWeb,且实现了前后端分离,所以在文章中不会有前端代码的实现过程。
不过前端的部分我已经写好啦,并且已经打包编译了,所以小伙伴们可以直接下载打包好的前端文件到自己的电脑上去(大概2M左右),然后用浏览器打开就可以直接运行啦~~~~
前端文件下载地址:https://github.com/BEIJIU601/NewStuReport
前端文件详细说明和使用:https://blog.csdn.net/weixin_43760020/article/details/105281230
博客的上篇在这里:https://blog.csdn.net/weixin_43760020/article/details/105228035
注意:假设我们在做一个前后端分离、需要通过接口文档对接的项目。要仔细查看前端所需的api接口和参数字段,不然与后端的交互有可能会失败!

博客的上篇点这里。

1、 项目Java环境搭建

2、后端代码编写

二、后端详细实现

下篇主要有后端Java的详细实现,包含全部Java代码

案例搭建使用到的工具如下,

  • 数据库:MySQL
  • 数据库图形工具:SQLyog
  • 编译器:IDEA
  • 服务器软件:Tomcat
  • 涉及的Jar包:
    mysql-connector ---------JDBC连接MySQL数据库的驱动
    druid --------阿里巴巴的数据库连接池,能够重复利用数据库连接,提高对请求的响应时间和服务器的性能。
    commons-dbutils ---------Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。
    fastjson --------阿里巴巴开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。

如下:

1、 项目Java环境搭建

首先使用IDEA来创建项目:

查看前端接口文档:https://blog.csdn.net/weixin_43760020/article/details/105281230
发现前端请求的基础地址为:http://localhost:9601/reactLogin

故配置Tomcat如下:
(点击锤子旁边的Tomcat,在下拉框中选择 Edit Configurations…)


接下来是导入Jar包:
(1)、首先创建一个lib目录

(2)、将所需的jar包复制到该目录

(3)、然后将其添加到 Libray 即可。
在 lib 目录上右键 —> add Libray —> 点击确定即可。

至此所有环境搭建完毕,可以开始编写代码了。

2、 后端编写

(1)、简单回顾案例结构

上一篇,我们已经新建了五个包,

  • beans:存放的是JavaBean。即实体类包,负责封装数据。
  • controller:存放的是servlet,即负责控制器的内容。
  • service:存放的是与业务逻辑相关的类,负责业务处理,实现核心需求
  • dao:存放与数据库连接相关的类,负责连接数据库
  • utils:存放的是连接数据库的工具类,是用来连接数据库的工具

分为五个层次,调用关系如下:

(2)、实现JavaBean对象

我们先实现JavaBean:
由上篇得出,数据库一共有两张表,即 新生登录表新生报道表
所以我们的JavaBean即为两个实体类,NewStu.java 和 Report.java
(即在beans包下新建两个类NewStu.java 和 Report.java)
参考上篇的字段,可得到两个实体类的属性和方法如下:

NewStu.java

//对应数据库的新生登录表
import java.io.Serializable;

public class NewStu implements Serializable {
   
    private long newstuid;
    private String newstuname;

    public NewStu(long newstuid, String newstuname) {
   
        this.newstuid = newstuid;
        this.newstuname = newstuname;
    }

    public NewStu() {
   

    }

    public long getNewstuid() {
   
        return newstuid;
    }

    public void setNewstuid(long newstuid) {
   
        this.newstuid = newstuid;
    }

    public String getNewstuname() {
   
        return newstuname;
    }

    public void setNewstuname(String newstuname) {
   
        this.newstuname = newstuname;
    }

    @Override
    public String toString() {
   
        return "NewStu{" +
                "newstuid=" + newstuid +
                ", newstuname='" + newstuname + '\'' +
                '}';
    }
}

Report.java

import com.alibaba.fastjson.annotation.JSONField;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

public class Report implements Serializable {
   
    private long r_id;
    private String newstuname;
    private String sex;
    private String major;
    private String classes;
    private String province;
    private String telephone;
    //JSONField注解用于格式化时间,如果不使用,在JavaBean和JSON字符串互相转换时会出错。
    @JSONField(format="yyyy-MM-dd")	 
    private Date to_date;
    @JSONField(format="HH:mm")
    private Date to_time;
    private String transport;
    private String transport_num;
    private String trsp_remark;
    private short is_loan;
    private BigDecimal loan_amount;
    private BigDecimal loan_pay;
    private String pay_way;
    private String pay_remark;
    private short is_photo;
    private String rec_people;
    private String rec_phone;

    public Report() {
   

    }

    public Report(long r_id, String newstuname,
                  String sex, String major,
                  String classes, String province,
                  String telephone, Date to_date,
                  Date to_time, String transport,
                  String transport_num, String trsp_remark,
                  short is_loan, BigDecimal loan_amount,
                  BigDecimal loan_pay, String pay_way,
                  String pay_remark, short is_photo,
                  String rec_people, String rec_phone)
    {
   
        this.r_id = r_id;
        this.newstuname = newstuname;
        this.sex = sex;
        this.major = major;
        this.classes = classes;
        this.province = province;
        this.telephone = telephone;
        this.to_date = to_date;
        this.to_time = to_time;
        this.transport = transport;
        this.transport_num = transport_num;
        this.trsp_remark = trsp_remark;
        this.is_loan = is_loan;
        this.loan_amount = loan_amount;
        this.loan_pay = loan_pay;
        this.pay_way = pay_way;
        this.pay_remark = pay_remark;
        this.is_photo = is_photo;
        this.rec_people = rec_people;
        this.rec_phone = rec_phone;
    }

    public long getR_id() {
   
        return r_id;
    }

    public void setR_id(long r_id) {
   
        this.r_id = r_id;
    }

    public String getNewstuname() {
   
        return newstuname;
    }

    public void setNewstuname(String newstuname) {
   
        this.newstuname = newstuname;
    }

    public String getSex() {
   
        return sex;
    }

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

    public String getMajor() {
   
        return major;
    }

    public void setMajor(String major) {
   
        this.major = major;
    }

    public String getClasses() {
   
        return classes;
    }

    public void setClasses(String classes) {
   
        this.classes = classes;
    }

    public String getProvince() {
   
        return province;
    }

    public void setProvince(String province) {
   
        this.province = province;
    }

    public String getTelephone() {
   
        return telephone;
    }

    public void setTelephone(String telephone) {
   
        this.telephone = telephone;
    }

    public Date getTo_date() {
   
        return to_date;
    }

    public void setTo_date(Date to_date) {
   
        this.to_date = to_date;
    }

    public Date getTo_time() {
   
        return to_time;
    }

    public void setTo_time(Date to_time) {
   
        this.to_time = to_time;
    }

    public String getTransport() {
   
        return transport;
    }

    public void setTransport(String transport) {
   
        this.transport = transport;
    }

    public String getTransport_num() {
   
        return transport_num;
    }

    public void setTransport_num(String transport_num) {
   
        this.transport_num = transport_num;
    }

    public String getTrsp_remark() {
   
        return trsp_remark;
    }

    public void setTrsp_remark(String trsp_remark) {
   
        this.trsp_remark = trsp_remark;
    }

    public short getIs_loan() {
   
        return is_loan;
    }

    public void setIs_loan(short is_loan) {
   
        this.is_loan = is_loan;
    }

    public BigDecimal getLoan_amount() {
   
        return loan_amount;
    }

    public void setLoan_amount(BigDecimal loan_amount) {
   
        this.loan_amount = loan_amount;
    }

    public BigDecimal getLoan_pay() {
   
        return loan_pay;
    }

    public void setLoan_pay(BigDecimal loan_pay) {
   
        this.loan_pay = loan_pay;
    }

    public String getPay_way() {
   
        return pay_way;
    }

    public void setPay_way(String pay_way) {
   
        this.pay_way = pay_way;
    }

    public String getPay_remark() {
   
        return pay_remark;
    }

    public void setPay_remark(String pay_remark) {
   
        this.pay_remark = pay_remark;
    }

    public short getIs_photo() {
   
        return is_photo;
    }

    public void setIs_photo(short is_photo) {
   
        this.is_photo = is_photo;
    }

    public String getRec_people() {
   
        return rec_people;
    }

    public void setRec_people(String rec_people) {
   
        this.rec_people = rec_people;
    }

    public String getRec_phone() {
   
        return rec_phone;
    }

    public void setRec_phone(String rec_phone) {
   
        this.rec_phone = rec_phone;
    }

    @Override
    public String toString() {
   
        return "Report{" +
                "r_id=" + r_id +
                ", newstuname='" + newstuname + '\'' +
                ", sex='" + sex + '\'' +
                ", major='" + major + '\'' +
                ", classes='" + classes + '\'' +
                ", province='" + province + '\'' +
                ", telephone='" + telephone + '\'' +
                ", to_date=" + to_date +
                ", to_time=" + to_time +
                ", transport='" + transport + '\'' +
                ", transport_num='" + transport_num + '\'' +
                ", trsp_remark='" + trsp_remark + '\'' +
                ", is_loan=" + is_loan +
                ", loan_amount=" + loan_amount +
                ", loan_pay=" + loan_pay +
                ", pay_way='" + pay_way + '\'' +
                ", pay_remark='" + pay_remark + '\'' +
                ", is_photo=" + is_photo +
                ", rec_people='" + rec_people + '\'' +
                ", rec_phone='" + rec_phone + '\'' +
                '}';
    }
}

(3)、实现控制器controller

①解决跨域
首先,因为前端文件是在本地打开的,所以请求我们的后端必然存在跨域问题,此时我们需要使用到拦截器Filter,来对跨域请求进行拦截:
(在controller包下新建一个Filter子包,然后子包下新建一个拦截器类 CrossFilter.java)

使用filter,那么在每次访问servlet前都会被filter拦截并进行处理,其实只要对请求头做一些处理,就可以解决跨域问题了。

CrossFilter.java

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "ajaxFilter",value = "/*")
public class CrossFilter implements Filter {
   
    public void destroy() {
   
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
   
        //解决跨域问题
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        httpServletRequest.getSession();
        HttpServletResponse httpResponse = (HttpServletResponse) resp;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", 
        						"Origin, X-Requested-With, Content-Type,Accept, Connection, User-Agent, Cookie");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Content-type", "application/json");
        httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
        chain.doFilter(req, httpResponse);
    }

    public void init(FilterConfig config) throws ServletException {
   

    }
}

**②编写servlet **
(本案例通过servlet实现controller)
controller调用service层。
通过查看前端接口,发现一共有三个接口需要对接,如下

  • 新生登录:http://localhost:9601/reactLogin/login,post

  • 初始化新生报道页 :http://localhost:9601/reactLogin/initReport,post

  • 新生提交填写的个人信息:http://localhost:9601/reactLogin/report,post

故需编写三个servlet: loginServlet.javainitReportServlet.javareportServlet.java

在写servlet过程中,我发现使用servlet接收前端发送的JSON参数时,不能使用request.getParameter来获取前端请求的参数,只能采用传统的流的方式接收。因为使用post方法,参数是放到请求体中的,且请求体中的数据会以json字符串的形式发送到后端。所以我写了一个commonServlet类,使用读取输入流来获取参数,通过也将一些servlet通用方法放到该类中,以达到代码复用的效果。
如下:
commonServlet.java

//该类作用是使用读取输入流来获取前端传递的JSON字符串参数,以及一些servlet通用方法
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;

public class commonServlet {
   
    //设置响应和请求的字符编码
    public void setCharset(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
   
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
    }

    //使用读取输入流来获取参数
    public String getString(HttpServletRequest request) {
   
        BufferedReader reader = null;
        String line = "";
        String s = null;
        try {
   
            reader = request.getReader();
            StringBuffer inputString = new StringBuffer();

            while ((line = reader.readLine()) != null) {
   
                inputString.append(line);
            }
            s = inputString.toString();
        } catch (Exception e) {
   
// throw new YppException(PayException.xmlParseError);
        }
        return s;
    }

}

实现新生登录接口的servlet:loginServlet.java

import com.alibaba.fastjson.JSON;
import com.beijiu.www.beans.NewStu;
import com.beijiu.www.service.Impl.NewStuServiceImpl;
import com.beijiu.www.service.NewStuService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "loginServlet",value = "/login")
public class loginServlet extends HttpServlet {
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
		 //设置请求和响应的字符编码
        commonServlet commonServlet = new commonServlet();
        commonServlet.setCharset(request,response);

        //获取前端传来的JSON字符串
        String json = commonServlet.getString(request);

        //获取前端传过来的JSON字符串,注意,这里的s不是JSON字符串,而是String类型的,不能直接就用SON.parseObject
        String s = getString(request);
        NewStu newStu = getJsonObeject(s);

        //调用service层,接收结果
        NewStuService newStuService = new NewStuServiceImpl();

        int result = newStuService.Verification(newStu.getNewstuname(),newStu.getNewstuid());

        //响应结果给前端
        PrintWriter writer = response.getWriter();
        writer.print(result);
    }

    //使用读取输入流来获取参数
    private String getString(HttpServletRequest request) {
   
        BufferedReader reader = null;
        String line = "";
        String String = null;
        try {
   
            reader = request.getReader();
            StringBuffer inputString = new StringBuffer();

            while ((line = reader.readLine()) != null) {
   
                inputString.append(line);
            }
            String = inputString.toString();
        } catch (Exception e) {
   
// throw new YppException(PayException.xmlParseError);
        }
        return String;
    }

    //将JSON字符串转换为JSON对象
    private NewStu getJsonObeject(String json){
   
        NewStu newStu =JSON.parseObject(json,NewStu.class);
        return newStu;
    }
}

初始化新生报道页接口的servlet:initReportServlet.java

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.beijiu.www.beans.Report;
import com.beijiu.www.service.Impl.ReportServiceImpl;
import com.beijiu.www.service.ReportService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "initServlet",value = "/initReport")
public class initReportServlet extends HttpServlet {
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        //设置请求和响应的字符编码
        commonServlet commonServlet = new commonServlet();
        commonServlet.setCharset(request,response);

        //获取前端传来的JSON字符串
        String json = commonServlet.getString(request);

        //将json字符串转换为javabean对象
        Report report = getJavaBean(json);

        //调用service层
        ReportService service = new ReportServiceImpl();
        Report report1 = service.getInitNewStu(report.getR_id());
        String s = JSON.toJSONString(report1, SerializerFeature.WriteMapNullValue);

        //响应给前端
        PrintWriter writer = response.getWriter();
        writer.print(s);
    }

    //将JSON字符串转换为JSON对象
    private Report getJavaBean(String json){
   
        Report report = JSON.parseObject(json,Report.class);
        return report;
    }
}

新生提交填写的个人信息接口的servlet:reportServlet.java

import com.alibaba.fastjson.JSON;
import com.beijiu.www.beans.Report;
import com.beijiu.www.service.Impl.ReportServiceImpl;
import com.beijiu.www.service.ReportService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "reportServlet",value = "/report")
public class reportServlet extends HttpServlet {
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        //设置请求和响应的字符编码
        commonServlet commonServlet = new commonServlet();
        commonServlet.setCharset(request,response);

        //获取前端传过来的JSON字符串,注意,这里的s不是JSON字符串,而是String类型的,不能直接就用SON.parseObject
        String s = commonServlet.getString(request);
        Report report = getJsonObeject(s);

        //调用service层,接收结果
        ReportService reportService = new ReportServiceImpl();
        int result = reportService.updateNewStu(report);

        //响应结果给前端
        PrintWriter writer = response.getWriter();
        writer.print(result);
    }

    //将JSON字符串转换为JSON对象
    private Report getJsonObeject(String json){
   
        Report report = JSON.parseObject(json,Report.class);
        return report;
    }
}

(4)、实现service层(业务逻辑)

一共有三个业务功能需实现:
①验证学号和姓名是否存在
②初始化新生个人信息
③提交新生填写的个人信息。
由于需要用到两个表,故写两个接口(interface) NewStuServiceReportService,用两个实现类 NewStuServiceImpl.javaReportServiceImpl.java实现。service层调用dao层。
如下所示:

两个接口,分别如下:
NewStuService

public interface NewStuService {
   
    //验证学号和姓名是否存在
    //学号和姓名均存在,则为1
    //姓名和学号其中之一不存在,则为0
    int Verification(String newstuname,long newstuid);
}

ReportService

import com.beijiu.www.beans.Report;

public interface ReportService {
   
    //初始化新生个人信息
    Report getInitNewStu(long r_id);

    //新生填写的个人信息
    int updateNewStu(Report report);
}

两个接口的实现类,分别如下:

NewStuServiceImpl.java

import com.beijiu.www.dao.Impl.NewStuDaoImpl;
import com.beijiu.www.dao.NewStuDao;
import com.beijiu.www.service.NewStuService;

public class NewStuServiceImpl implements NewStuService {
   
    NewStuDao newStuDao = new NewStuDaoImpl();
    @Override
    public int Verification(String newstuname, long newstuid) {
   
   		//调用dao层
        int i = newStuDao.Verification(newstuname,newstuid);
        if (i==1){
   
            return 1;
        }else {
   
            return 0;
        }
    }
}

ReportServiceImpl.java

import com.beijiu.www.beans.Report;
import com.beijiu.www.dao.Impl.ReportDaoImpl;
import com.beijiu.www.dao.ReportDao;
import com.beijiu.www.service.ReportService;

public class ReportServiceImpl implements ReportService {
   
    //调用dao层
    ReportDao reportDao = new ReportDaoImpl();

    //初始化新生个人信息
    @Override
    public Report getInitNewStu(long r_id) {
   
        Report reportInit = reportDao.getInitNewStu(r_id);
        return reportInit;
    }

    //新生填写的个人信息
    @Override
    public int updateNewStu(Report reportSubmit) {
   
        int result = reportDao.updateNewStu(reportSubmit);
        if (result == 1){
   
            return 1;
        }else {
   
            return 0;
        }
    }
}

(5)、实现dao层

由于dao层需要连接数据库,所以我们需要先连接数据库,再提供接口给service层使用。
①连接数据库
注意配置文件要在src目录下:

首先druid连接池,需要一个配置文件进行连接设置,文件名需为database.properties
连接配置如下:
database.properties

#连接设置
driverClassName=com.mysql.cj.jdbc.Driver
#连接路径
url=jdbc:mysql://localhost:数据库端口号/要连接的数据库?serverTimezone=UTC
#数据库用户名
username=用户名
#数据库密码
password=密码
#初始化连接
initialSzie=10
#最大连接数量
maxActive=50
#最小空闲连接
minIdle=5
#超时等待时间以毫秒为单位,60000毫秒/1000等于60秒
maxWait=5000

编写连接数据库的工具类 DButils.java

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/* * 工具类不要实例化 * 工具类全是公开的静态方法 * 工具类只负责提供服务,多余的不属于工具类 * */

public class DButils {
   
    private static DruidDataSource dataSource;
    private static Connection connection;

    static {
   
        //1、读取配置文件
        Properties properties = new Properties();
        InputStream inputStream = DButils.class.getClassLoader().getResourceAsStream("database.properties");
        try {
   
            properties.load(inputStream);
            //创建连接池对象
            dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
   
            e.printStackTrace();
        } catch (Exception e) {
   
            e.printStackTrace();
        }
    }

    //2、获得一个连接池
    public static DruidDataSource getDataSource(){
   
        return dataSource;
    }

    //3、获得连接返回
    public static Connection getConnection(){
   
        try {
   
            connection = dataSource.getConnection();
            return connection;
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        return null;
    }

    //4、关闭连接
    public static void closeAll(ResultSet resultSet, Statement statement, Connection connection){
   
        try {
   
            if(resultSet != null){
   
                resultSet.close();
            }
            if(statement != null){
   
                statement.close();
            }
            if(connection != null){
   
                connection.close();
            }
        } catch (SQLException e){
   
            e.printStackTrace();
        }
    }
}

接下来只要dao层中调用DButils类就可以访问数据库了。

②实现dao层
由于service层需要dao层提供接口,且service分为两个接口,故dao层也需两个接口类NewStuDaoReportDao,以及两个实现类NewStuDaoImpl.javaReportDaoImpl.java
如下:

接口类NewStuDao:

public interface NewStuDao {
   
    //1、验证学号和姓名是否存在
    int Verification(String newstuname,long newstuid);
}

接口实现类NewStuDaoImpl:

import com.beijiu.www.dao.NewStuDao;
import com.beijiu.www.utils.DButils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class NewStuDaoImpl implements NewStuDao {
   
    private QueryRunner queryRunner = new QueryRunner(DButils.getDataSource());
    @Override
    public int Verification(String newstuname, long newstuid) {
   
        String sql = "select count(*) from stunew where newstuid=? and newstuname=?;";
        int i = 0;
        long r =0;
        try {
   
            //注意:很多sql函数比如 count(),sum(),等可能会返回的结果是数值的,对应的java类型应该是long,而不是int类型
            r = queryRunner.query(sql, new ScalarHandler<>(),newstuid,newstuname);
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        i = new Long(r).intValue();
        return i;
    }
}

接口类ReportDao:

import com.beijiu.www.beans.Report;

public interface ReportDao {
   
    //初始化新生个人信息
    Report getInitNewStu(long r_id);

    //新生填写的个人信息
    int updateNewStu(Report report);
}

接口实现类类NewStuDaoImpl:

import com.beijiu.www.beans.Report;
import com.beijiu.www.dao.ReportDao;
import com.beijiu.www.utils.DButils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class ReportDaoImpl implements ReportDao {
   
    private QueryRunner queryRunner = new QueryRunner(DButils.getDataSource());
    @Override
    public Report getInitNewStu(long r_id) {
   
        String sql = "select * from stureport where r_id=?;";
        try {
   
            Report report = queryRunner.query(sql, new BeanHandler<>(Report.class),r_id);
            return report;
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int updateNewStu(Report report) {
   
        Object[] params = {
    report.getTelephone(),report.getTo_date(),report.getTo_time(),report.getTransport(),
                            report.getTransport_num(),report.getTrsp_remark(),report.getIs_loan(),report.getLoan_amount(),
                            report.getLoan_pay(),report.getPay_way(),report.getPay_remark(),report.getIs_photo(),
                            report.getR_id()
        };
        String sql =
                "UPDATE stureport SET telephone = ?,to_date = ?,to_time = ?,transport = ?,transport_num = ?,trsp_remark = ?,is_loan = ?,loan_amount = ?,loan_pay = ?,pay_way = ?,pay_remark = ?,is_photo = ? WHERE r_id = ?;";
        try {
   
            int result = queryRunner.update(sql,params);
            return result;
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        return 0;
    }
}

案例结束

至此,本案例结束。这是我用来检验自己JavaWeb的一个小项目,主要用于个人学习。

案例上篇如下:https://blog.csdn.net/weixin_43760020/article/details/105228035

全部评论

相关推荐

牛客279957775号:铁暗恋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务