项目实战:service业务逻辑组件引入

1、第一层DAO层

1.1、FruitDao接口

java 复制代码
package com.csdn.fruit.dao;
import com.csdn.fruit.pojo.Fruit;
import java.util.List;
//dao :Data Access Object 数据访问对象
//接口设计
public interface FruitDao {

    void addFruit(Fruit fruit);

    void delFruit(String fname);

    //通过 fid 删除 水果库存记录
    void delFruitByFid(Integer fid);

    void updateFruit(Fruit fruit);

    @Deprecated
    List<Fruit> getFruitList();
    @Deprecated
    List<Fruit> getFruitList(Integer pageNo, Integer pageSize);

    List<Fruit> getFruitList(Integer pageNo, Integer pageSize,String keyword);

    Fruit getFruitByFname(String fname);

    Fruit getFruitByFid(Integer fid);

    //查询总记录条数
    @Deprecated
    Integer getRecordCount();

    Integer getRecordCount(String keyword);
}

1.2、FruitDaoImpl实现类

java 复制代码
package com.csdn.fruit.dao.impl;
import com.csdn.fruit.dao.FruitDao;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.mymvc.dao.BaseDao;
import java.util.List;
public class FruitDaoImpl extends BaseDao<Fruit> implements FruitDao {
    @Override
    public void addFruit(Fruit fruit) {
        String sql = "insert into t_fruit values (0,?,?,?,?)";
        super.executeUpdate(sql, fruit.getFname(), fruit.getPrice(), fruit.getFcount(), fruit.getRemark());
    }

    @Override
    public void delFruit(String fname) {
        String sql = "delete from t_fruit where fname=?";
        super.executeUpdate(sql, fname);
    }

    //通过 fid 删除水果库存记录
    @Override
    public void delFruitByFid(Integer fid) {
        super.executeUpdate("delete from t_fruit where fid = ? ", fid);
    }

    //通过 fid 可以修改所有的属性值
    @Override
    public void updateFruit(Fruit fruit) {
        String sql = "update  t_fruit set fname=?,price=?,fcount=?,remark=? where fid = ?";
        super.executeUpdate(sql, fruit.getFname(), fruit.getPrice(), fruit.getFcount(), fruit.getRemark(), fruit.getFid());
    }

    @Override
    public List<Fruit> getFruitList() {
        return super.executeQuery("select * from t_fruit");
    }

    @Override
    public List<Fruit> getFruitList(Integer pageNo, Integer pageSize) {
        return super.executeQuery("select * from t_fruit limit ?,?", (pageNo - 1) * pageSize, pageSize);
    }

    @Override
    public List<Fruit> getFruitList(Integer pageNo, Integer pageSize, String keyword) {
        return super.executeQuery("select * from t_fruit where fname like ? or remark like?  limit ?,?", "%" + keyword + "%", "%" + keyword + "%", (pageNo - 1) * pageSize, pageSize);
    }

    @Override
    public Fruit getFruitByFname(String fname) {
        return load("select * from t_fruit where fname = ?", fname);
    }

    @Override
    public Fruit getFruitByFid(Integer fid) {
        return load("select * from t_fruit where fid=?", fid);
    }

    @Override
    public Integer getRecordCount() {
        String sql = "select count(*) from t_fruit";
        return ((Long) executeComplexQuery(sql).get(0)[0]).intValue();
    }

    @Override
    public Integer getRecordCount(String keyword) {
        String sql = "select count(*) from t_fruit where fname like ? or remark like ? ";
        return ((Long) executeComplexQuery(sql, "%" + keyword + "%", "%" + keyword + "%").get(0)[0]).intValue();
    }
}

2、第二层Service层

2.1、FruitService接口

java 复制代码
package com.csdn.fruit.service;
import com.csdn.fruit.dto.PageInfo;
import com.csdn.fruit.dto.PageQueryParam;
import com.csdn.fruit.pojo.Fruit;
public interface FruitService {
    PageInfo<Fruit> getFruitPageInfo(PageQueryParam pageQueryParam);

    void addFruit(Fruit fruit);

    void updateFruit(Fruit fruit);

    void delFruit(Integer fid);

    Fruit getFruitById(Integer fid);

    Fruit getFruitByFname(String fname);
}

2.2、FruitServiceImpl实现类

java 复制代码
package com.csdn.fruit.service.impl;
import com.csdn.fruit.dao.FruitDao;
import com.csdn.fruit.dao.impl.FruitDaoImpl;
import com.csdn.fruit.dto.PageInfo;
import com.csdn.fruit.dto.PageQueryParam;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.service.FruitService;
import java.util.List;
public class FruitServiceImpl implements FruitService {

    private FruitDao fruitDao = new FruitDaoImpl();

    @Override
    public PageInfo<Fruit> getFruitPageInfo(PageQueryParam pageQueryParam) {
        Integer pageNo = pageQueryParam.getPageNo();
        Integer pageSize = pageQueryParam.getPageSize();
        String keyword = pageQueryParam.getKeyword();
        List<Fruit> fruitList = fruitDao.getFruitList(pageNo, pageSize, keyword);
        Integer recordCount = fruitDao.getRecordCount(pageQueryParam.getKeyword());
        PageInfo<Fruit> fruitPageInfo = new PageInfo<>(fruitList, pageNo, recordCount);
        return fruitPageInfo;
    }

    @Override
    public void addFruit(Fruit fruit) {
        if (fruitDao.getFruitByFname(fruit.getFname()) == null) {
            fruitDao.addFruit(fruit);
        }
    }

    @Override
    public void updateFruit(Fruit fruit) {
            fruitDao.updateFruit(fruit);
    }

    @Override
    public void delFruit(Integer fid) {
            fruitDao.delFruitByFid(fid);
    }

    @Override
    public Fruit getFruitById(Integer fid) {
        return fruitDao.getFruitByFid(fid);
    }

    @Override
    public Fruit getFruitByFname(String fname) {
        return fruitDao.getFruitByFname(fname);
    }
}

3、Servlet层

3.1、IndexServlet

java 复制代码
package com.csdn.fruit.servlet;
import com.csdn.fruit.dto.PageInfo;
import com.csdn.fruit.dto.PageQueryParam;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.service.FruitService;
import com.csdn.fruit.service.impl.FruitServiceImpl;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    private FruitService fruitService = new FruitServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer pageNo = 1;
        String pageNoStr = req.getParameter("pageNo");
        if (pageNoStr != null && !"".equals(pageNoStr)) {
            pageNo = Integer.parseInt(pageNoStr);
        }

        String keyword = "";
        String keywordStr = req.getParameter("keyword");
        if (keywordStr!=null) {
            keyword = keywordStr;
        }
        PageQueryParam pageQueryParam = new PageQueryParam(pageNo, 5, keyword);
        PageInfo<Fruit> pageInfo = fruitService.getFruitPageInfo(pageQueryParam);
        
        Result result = Result.OK(pageInfo);

        ResponseUtil.print(resp, result);
    }
}

3.2、EditServlet

java 复制代码
package com.csdn.fruit.servlet;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.service.FruitService;
import com.csdn.fruit.service.impl.FruitServiceImpl;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/edit")
public class EditServlet extends HttpServlet {
    private FruitService fruitService = new FruitServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer fid = Integer.parseInt(req.getParameter("fid"));
        Fruit fruit = fruitService.getFruitById(fid);
        ResponseUtil.print(resp, Result.OK(fruit));
    }
}

3.3、GetFnameServlet

java 复制代码
package com.csdn.fruit.servlet;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.service.FruitService;
import com.csdn.fruit.service.impl.FruitServiceImpl;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.GenericServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/getFname")
public class GetFnameServlet extends GenericServlet {
    private FruitService fruitService = new FruitServiceImpl();
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        String fname = servletRequest.getParameter("fname");
        Fruit fruit = fruitService.getFruitByFname(fname);
        ResponseUtil.print(servletResponse, fruit == null ? Result.OK() : Result.Fail());
    }
}

3.4、UpdateServlet

java 复制代码
package com.csdn.fruit.servlet;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.service.FruitService;
import com.csdn.fruit.service.impl.FruitServiceImpl;
import com.csdn.fruit.util.RequestUtil;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
    private FruitService fruitService = new FruitServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Fruit fruit = (Fruit) RequestUtil.readObject(req, Fruit.class);
        fruitService.updateFruit(fruit);
        ResponseUtil.print(resp, Result.OK());
    }
}

3.5、DelServlet

java 复制代码
package com.csdn.fruit.servlet;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.service.FruitService;
import com.csdn.fruit.service.impl.FruitServiceImpl;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/del")
public class DelServlet extends HttpServlet {
    private FruitService fruitService = new FruitServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer fid = Integer.parseInt(req.getParameter("fid"));
        fruitService.delFruit(fid);
        ResponseUtil.print(resp, Result.OK());
    }
}

3.6、AddServlet

java 复制代码
package com.csdn.fruit.servlet;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.service.FruitService;
import com.csdn.fruit.service.impl.FruitServiceImpl;
import com.csdn.fruit.util.RequestUtil;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/add")
public class AddServlet extends HttpServlet {
    private FruitService fruitService = new FruitServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Fruit fruit = (Fruit) RequestUtil.readObject(req, Fruit.class);
        fruitService.addFruit(fruit);
        ResponseUtil.print(resp, Result.OK());
    }
}

4、DTO层

4.1、Result

java 复制代码
package com.csdn.fruit.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
    private boolean flag;
    private Object data;
    private String msg;

    public Result(boolean flag, Object data) {
        this.flag = flag;
        this.data = data;
    }

    public Result(boolean flag, String msg) {
        this.flag = flag;
        this.msg = msg;
    }

    public static Result OK() {
        return new Result(true, "操作成功");
    }

    public static Result OK(Object data) {
        return new Result(true, data);
    }

    public static Result Fail() {
        return new Result(false, "操作失败");
    }

    public static Result Fail(String msg) {
        return new Result(false, msg);
    }
}

4.2、PageInfo

java 复制代码
package com.csdn.fruit.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
//分页组件类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageInfo<T> {
    private List<T> list;
    private Integer pageNo = 1;
    private Integer pageSize = 5;
    private Integer recordCount = 0;
    private Integer pageCount = 0;

    public PageInfo(List<T> list, Integer pageNo, Integer recordCount) {
        this.list = list;
        this.pageNo = pageNo;
        this.recordCount = recordCount;
        this.pageCount = (recordCount + pageSize - 1) / pageSize;
    }
}

4.3、PageQueryParam

java 复制代码
package com.csdn.fruit.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageQueryParam {
    private Integer pageNo = 1;
    private Integer pageSize = 5;
    private String keyword = "";
}

5、Util层

5.1、RequestUtil

java 复制代码
package com.csdn.fruit.util;
import jakarta.servlet.ServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
public class RequestUtil {
    public static Object readObject(ServletRequest request, Class clazz) throws IOException {
        BufferedReader br = request.getReader();
        StringBuilder stringBuilder = new StringBuilder();
        String str = null;
        while ((str = br.readLine()) != null) {
            stringBuilder.append(str);
        }
        str = stringBuilder.toString();
        return GsonUtil.fromJson(str, clazz);
    }
}

5.2、GsonUtil

java 复制代码
package com.csdn.fruit.util;
import com.google.gson.Gson;
public class GsonUtil {
    public static String toJson(Object obj) {
        //java object ->  json string
        Gson gson = new Gson();
        return gson.toJson(obj);
    }

    //public static <T> T fromJson(String jsonStr, Class<T> clazz) {}

    public static Object fromJson(String jsonStr, Class clazz) {
        // json string -> java object
        Gson gson = new Gson();
        return gson.fromJson(jsonStr, clazz);
    }
}

5.3、ResponseUtil

java 复制代码
package com.csdn.fruit.util;
import com.csdn.fruit.dto.Result;
import jakarta.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ResponseUtil {
    public static void print(ServletResponse response, Result result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(GsonUtil.toJson(result));
        out.flush();
    }
}

6、Service层的文字解读

Java中的service层一般是作为业务逻辑处理的中间层,负责接收控制层的请求,进行业务逻辑的处理,并将处理结果返回给控制层。

具体来说,service层通常包括以下作用:

  1. 转发控制层请求:service层一般是与控制层紧密联系的,负责接收控制层的请求,通过调用DAO层提供的接口获取数据,进行业务逻辑的处理,并将处理结果返回给控制层。

  2. 处理业务逻辑:service层主要负责对业务逻辑进行处理,将底层的数据操作进行组合和加工,从而形成业务流程,实现对复杂业务操作的封装,方便控制层调用。

  3. 事务处理:service层通常是一个事务的边界,负责管理一系列操作的一致性和完整性,确保业务操作的正确性。

  4. 异常处理:service层也负责处理操作过程中的异常,确保业务操作的可靠性和稳定性,通过对异常的处理,提高系统的容错能力。

综上,service层在Java应用程序中扮演着重要的角色,起到了整合、控制和管理业务逻辑的作用,是一个高层次的、中间的业务处理层。

相关推荐
记录成长java4 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet
长安初雪6 小时前
Request 和 Response 万字详解
计算机网络·servlet
A-bodgie10 小时前
Spring 中的 Environment 对象
java·后端·spring·servlet·springboot
笔墨登场说说2 天前
JDK 里面的线程池和Tomcat线程池的区别
java·servlet·tomcat
听潮阁2 天前
【SpringCloud详细教程】-01-一文了解微服务
开发语言·spring boot·spring cloud·servlet·java-ee·mybatis
阑梦清川3 天前
JavaEE初阶-----servlet-api,Maven创建项目,部署,打包,测试全过程
servlet·java-ee·maven
阑梦清川3 天前
JavaEE初阶--servlet篇(三)HttpServlet/response/request对应方法使用
java·servlet·java-ee
awonw3 天前
[java][基础]HTTP&Tomcat&Servlet
java·http·servlet·tomcat
长安初雪4 天前
Servlet 3.0 注解开发
servlet
tian-ming5 天前
(九)JavaWeb后端开发——Servlet
servlet