项目实战: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应用程序中扮演着重要的角色,起到了整合、控制和管理业务逻辑的作用,是一个高层次的、中间的业务处理层。

相关推荐
weixin_5375904521 小时前
《Java编程入门官方教程》第八章练习答案
java·开发语言·servlet
Ttang232 天前
Tomcat原理(4)——尝试手动Servlet的实现
java·开发语言·servlet·java-ee·tomcat·intellij-idea
loop lee3 天前
计算机网络 - HTTP 协议和万维网
java·网络协议·servlet·tomcat
不修×蝙蝠3 天前
搭建Tomcat(四)---Servlet容器
java·服务器·servlet·tomcat·搭建resquest
像污秽一样3 天前
简易记事本开发-(SSM+Vue)
java·vue.js·spring boot·spring·servlet·maven·mybatis
计算机学无涯5 天前
Servlet学习中遇到的一些问题及解决
servlet
测试工程师成长之路5 天前
解锁 Jenkins 搭建全攻略
运维·servlet·jenkins
进击的编程浪人5 天前
jsp中的四个域对象(Spring MVC)
servlet
怒放de生命20106 天前
jenkins 出现 Jenkins: 403 No valid crumb was included in the request
java·servlet·jenkins
爱小黄6 天前
从Servlet到Spring MVC,从Spring MVC到Spring BootC
spring·servlet·mvc