1、JSP

mvc jquery session过时 jsp过时_sql


因为想要进行动态 web 的开发,不可避免的在 html 中修改一些数据,改的时候,在后端修改,想要在修改完成后在前端显示,那么不使用 jsp 的话,会使得在 Servlet 中 编写代码变得非常麻烦以及复杂,引入了 jsp 之后,可以在 Servlet 中存在 Servlet 代码以及 html 代码,一定程度上简化了代码;

1.1 jsp快速入门

mvc jquery session过时 jsp过时_html_02

1.2 jsp 原理

mvc jquery session过时 jsp过时_sql_03

1.3 jsp 脚本

mvc jquery session过时 jsp过时_数据_04

<%@ page import="com.luobin.pojo.Brand" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
  Created by IntelliJ IDEA.
  User: yimeng
  Date: 2022/3/12
  Time: 5:06 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    // 查询数据库
    List<Brand> brands = new ArrayList<Brand>();
    brands.add(new Brand(1, "三只松鼠", "三只松鼠", 100, "三只松鼠,好吃不上火", 1));
    brands.add(new Brand(2, "优衣库", "优衣库", 200, "优衣库,服适人生", 0));
    brands.add(new Brand(3, "小米", "小米科技有限公司", 1000, "为发烧而生", 1));
%>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="button" value="新增"><br>
        <hr>
        <table border="1" cellspacing="0" width="800">
            <tr>
                <th>序号</th>
                <th>品牌名称</th>
                <th>企业名称</th>
                <th>排序</th>
                <th>品牌介绍</th>
                <th>状态</th>
                <th>操作</th>

            </tr>

            <%
                for (int i = 0; i < brands.size(); i++) {
                    Brand brand = brands.get(i);
            %>

            <tr align="center">
                <td><%=brand.getId()%>
                </td>
                <td><%=brand.getBrandName()%>
                </td>
                <td><%=brand.getCompanyName()%>
                </td>
                <td><%=brand.getOrdered()%>
                </td>
                <td><%=brand.getDescription()%>
                </td>
                <td><%=brand.getStatus()%>
                </td>
                <td><a href="#">修改</a> <a href="#">删除</a></td>
            </tr>

            <%
                }
            %>
        </table>

    </body>
</html>

mvc jquery session过时 jsp过时_sql_05


mvc jquery session过时 jsp过时_html_06

1.4 EL 表达式

是为了获取数据,为了下一步的为 JSTL 对数据进行判断,想要获取数据,前提是需要将数据放置在域中

mvc jquery session过时 jsp过时_数据_07

@WebServlet("/el-demo1")
public class ServletEL1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、准备数据
        List<Brand> brands = new ArrayList<Brand>();
        brands.add(new Brand(1, "三只松鼠", "三只松鼠", 100, "三只松鼠,好吃不上火", 1));
        brands.add(new Brand(2, "优衣库", "优衣库", 200, "优衣库,服适人生", 0));
        brands.add(new Brand(3, "小米", "小米科技有限公司", 1000, "为发烧而生", 1));

        // 2 存储在 request 域中
        request.setAttribute("brands",brands);

        // 3 转发到 el-demo.jsp 中
        request.getRequestDispatcher("/el-demo.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

1.5 JSTL 标签

直接在 jsp 里面书写代码,对于项目的维护是十分不方便的,因为前端可能不懂 Java 代码,并且在 jsp 里面书写的 Java 代码经常需要代码的截断,读取以及书写都是不方便的,所以在 jsp 里面的判断代码以及循环代码,使用 jstl 标签代替,又可以简化一定的代码

mvc jquery session过时 jsp过时_sql_08


mvc jquery session过时 jsp过时_sql_09

mvc jquery session过时 jsp过时_sql_10

1.6 MVC 模式和三层架构

mvc jquery session过时 jsp过时_sql_11


mvc jquery session过时 jsp过时_sql_12

表现层:web 层或者叫做 controller 层

业务逻辑层:service 层
数据访问层:dao 层
业务了逻辑可以和数据访问放在一起,因为在执行业务逻辑的时候,一定上需要访问数据的;

三层架构可以说是对于三层模型的一种物理实现;

1.6.1 MVC 和 三层架构区别

mvc jquery session过时 jsp过时_数据_13

M ------业务逻辑层 数据访问层
V C ------表现层

1.7 案例 使用 MVC 进行数据的 CRUD

mvc jquery session过时 jsp过时_数据_14

1.7.1 创建的项目目录

mvc jquery session过时 jsp过时_数据_15

1.7.2 三层架构下的查询设计

mvc jquery session过时 jsp过时_html_16

1.7.3 三层架构下的添加数据

mvc jquery session过时 jsp过时_html_17

web层

@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {

    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 配置可能存在的乱码问题
        request.setCharacterEncoding("utf-8");

        // 1、接收表单中提交的数据,封装成为一个 Brand 对象,接收表单参数,封装成为对象的目的是将数据添加到数据库中
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setDescription(description);
        // 封装的对象的时候,因为这个数据从前端获取过来是 String ,在这里需要进行数据类型的转换
        brand.setStatus(Integer.parseInt(status));
        brand.setOrdered(Integer.parseInt(ordered));

        // 调用 service() 完成数据的添加
        service.add(brand);

        // 转发到查询所有的 Servlet
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

service 层

public class BrandService {
    // 通过提前写好的 utils 里面的工具创建一次工厂,减少系统的资源浪费
    SqlSessionFactory factory = SqlSessionFactoryUtil.getSqlSessionFactory();

    /**
     * 查询所有
     * @return
     */
    public List<Brand> selectAll() {
        // 调用 BrandMapper.selectAll()

        // 获得 SqlSessionFactory() 创建 sqlSession 对象方便执行 sql 语句
//        SqlSessionFactory factory = SqlSessionFactoryUtil.getSqlSessionFactory();

        SqlSession sqlSession = factory.openSession();

        // 获取 BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 调用方法
        List<Brand> brands = mapper.selectAll();

        // 因为知识查询操作,所以是不需要提交事务的,知识将资源进行关闭即可
        sqlSession.close();

        return brands;
    }

    public void add(Brand brand) {
        SqlSession sqlSession = factory.openSession();

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 调用方法
        mapper.add(brand);

        // 增删改的操作,需要事务的提交
        sqlSession.commit();

        sqlSession.close();
    }
}

dao 层(mapper 层)

public interface BrandMapper {
    /**
     * 查询 tb_brand 表中的所有数据
     * @return
     */
    @Select("select * from mybatis.tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

    /**
     * 向数据库中添加数据
     * @param brand
     */
    @Select("insert into mybatis.tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);
}

sql 映射文件

<?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.luobin.mapper.BrandMapper">
    <!--遇到的部分的字段查询不到的时候,一般可能是数据库的名字与 pojo 里面属性的名字不一致导致的-->
    <!--这个时候需要使用 resultMap 进行名字的匹配即可-->
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company" property="companyName"></result>
    </resultMap>

</mapper>

显示查询结果的 jsp

<%--
  Created by IntelliJ IDEA.
  User: yimeng
  Date: 2022/3/12
  Time: 6:16 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--如果接收不到转发的数据,添加下面的代码 是因为 jsp 和 servlet 版本导致的默认关闭--%>
<%@page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="button" value="新增" id="add"><br>
        <hr>
        <table border="1" cellspacing="0" width="80%">
            <tr>
                <th>序号</th>
                <th>品牌名称</th>
                <th>企业名称</th>
                <th>排序</th>
                <th>品牌介绍</th>
                <th>状态</th>
                <th>操作</th>
            </tr>

            <c:forEach items="${brands}" var="brand">
                <tr>
                    <th>${brand.id}</th>
                    <th>${brand.brandName}</th>
                    <th>${brand.companyName}</th>
                    <th>${brand.ordered}</th>
                    <th>${brand.description}</th>
                    <th>${brand.status}</th>
                </tr>
            </c:forEach>

            <c:if test="${status == 1}">
                启用
            </c:if>
            <c:if test="${status != 1}">
                禁用
            </c:if>
        </table>

    </body>

    <%--点击新增加的页面,跳转到 jsp 页面,里面的表单中填写数据,发送到 Servlet 中--%>
    <script>
        document.getElementById("add").onclick = function () {
            location.href = "/brand-demo/addBrand.jsp"
        }
    </script>
</html>

进行表单上传的 jsp

<%--
  Created by IntelliJ IDEA.
  User: yimeng
  Date: 2022/3/13
  Time: 2:48 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>添加品牌</title>
    </head>
    <body>
        <h3>添加品牌</h3>
        <form action="/brand-demo/AddServlet" method="post">
            品牌名称:<input name="brandName"><br>
            企业名称:<input name="companyName"><br>
            排序:<input name="ordered"><br>
            描述信息:<textarea rows="5" cols="20" name="description"></textarea><br>
            状态:
            <input type="radio" name="status" value="0">禁用
            <input type="radio" name="status" value="1">启用<br>

            <input type="submit" value="提交">
        </form>
    </body>
</html>

1.8 三层架构模型下的修改操作

1、进行数据回显

mvc jquery session过时 jsp过时_html_18