前端页面
<%--a标签用来跳转,并且要带上当前数据的id--%>
<td><a href="/brand_demo/SelectByIdServlet?id=${brand.id}">修改</a>
表现层
@WebServlet("/SelectByIdServlet")
public class selectByIdServlet 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");
Integer.parseInt(id);
// 调用业务逻辑层通过id查询数据
Brand brand = brandService.selectByid(Integer.parseInt(id));
// 将查询到的数据放入request域中
request.setAttribute("brand",brand);
// 使用请求转发
request.getRequestDispatcher("updateBrand.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
业务逻辑层
public class BrandService {
// 业务逻辑层操作数据库通过id查询数据库
public Brand selectByid(Integer id){
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand = mapper.selectById(id);
sqlSession.close();
return brand;
}
}
数据访问层
public interface BrandMapper {
// 通过id查询数据
Brand selectById(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>
<select id="selectById" resultMap="brand">
select * from tb_brand where id = #{id}
</select>
</mapper>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加品牌</title>
</head>
<body>
<%--添加数据的前端页面相似,只是需要将查询到的数据回显到页面当中--%>
<%--将每一个控件中的value设置成数据展示--%>
<h3>添加品牌</h3>
<form action="/brand_demo/updateBrandServlet" method="post">
<input type="hidden" name="id" value="${brand.id}">
品牌名称:<input type="text" name="brandName" onblur="checkName()" id="brandName" value="${brand.brandName}"><br>
企业名称:<input name="companyName" value="${brand.companyName}"><br>
排序:<input name="ordered" value="${brand.ordered}"><br>
描述信息:<textarea rows="5" cols="20" name="description" >${brand.description}</textarea><br>
状态:
<%--使用java语句进行判断,checked表示单选框被点亮--%>
<c:if test="${brand.status == 0}">
<input type="radio" name="status" value="0" checked>禁用
<input type="radio" name="status" value="1">启用<br>
</c:if>
<c:if test="${brand.status == 1}">
<input type="radio" name="status" value="0" >禁用
<input type="radio" name="status" value="1" checked>启用<br>
</c:if>
<input type="submit" value="提交">
</form>
</body>
</html>