前端页面
<%--a标签用来跳转,并且要带上当前数据的id--%>
<a href="/brand_demo/deleteBrandServlet?id=${brand.id}">删除</a>
表现层
@WebServlet("/deleteBrandServlet")
public class deleteBrandServlet extends HttpServlet {
private BrandService brandService = new BrandService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String id = request.getParameter("id");
// 调用业务逻辑层删除数据,根据前端传来的id数据删除
brandService.deleteByid(Integer.parseInt(id));
// 当数据删除后,需要通过重定向到数据库查询表现层
// 将前端页面展示的数据进行更新
response.sendRedirect(request.getContextPath() + "/selectAllServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
业务逻辑层
public class BrandService {
// 业务逻辑层操作数据库删除数据
public void deleteByid(Integer id) {
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.deleteByid(id);
}
}
数据访问层
public interface BrandMapper {
// 通过id删除数据
void deleteByid(Integer id);
}
数据库操作
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cyf.mapper.BrandMapper">
<resultMap id="brand" type="com.cyf.pojo.Brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<delete id="deleteByid">
delete from tb_brand where id = #{id}
</delete>
</mapper>
|