MVC pattern and three-tier architecture - application case

Table of contents

1. Environment preparation

2. Create a project  

3. Create package

4. Create table

5. Create entity class

6. Prepare the mybatis environment

7. Query all

7.1 Write BrandMapper

7.2 Writing tool classes

7.3 Write BrandService

7.4 Writing Servlets

7.5 Write brand.jsp page

8. Rest of the code download:


1. Environment preparation

Environment preparation, we implement in the following steps:

  • Create a new module brand_demo, import coordinates

  • Create a package structure for a three-tier architecture

  • Database table tb_brand

  • Entity class Brand

  • MyBatis basic environment

    • Mybatis-config.xml

    • BrandMapper.xml

    • BrandMapper interface

2. Create a project  

Create a new module brand_demo and import coordinates. As long as we analyze what technologies are to be used, then what coordinates are needed will be clear

  • Need to operate the database. mysql driver package

  • To use the mybatis framework. Dependency package of mybaits

  • Web projects need to use servlet and jsp. Dependency packages for servlet and jsp

  • Need to use jstl for data display. jstl dependency package

pom.xmlThe content is as follows:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>test</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>brand-demo</artifactId>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>

        <!--servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!--jsp-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>

        <!--jstl,JSP标准标签库-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>

</project>

3. Create package

Create different package structures to store different classes. The package structure is as follows

 4. Create table

-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);

5. Create entity class

pojoCreate a class named under the package Brand.

package com.pojo;

/**
 * 品牌实体类
 */

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;


    public Brand() {
    }

    public Brand(Integer id, String brandName, String companyName, String description) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.description = description;
    }

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

6. Prepare the mybatis environment

Define the core configuration file Mybatis-config.xmland place the file resourcesunder

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--起别名-->
    <typeAliases>
        <package name="com.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                //数据库地址
                <property name="url" value="jdbc:mysql://localhost:13306/db1"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--扫描mapper-->
        <package name="com.mapper"/>
    </mappers>
</configuration>

resourcesCreate a directory structure for placing mapping configuration files under and create mapping configuration files under this directorycom/mapper(注意:这个包名创建时只能使用"/",不能使用".",xml和原文件包的结构应该一样)BrandMapper.xml

<?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.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>

    <insert id="add">
        insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status});
    </insert>

    <update id="update">
        update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},
                            description=#{description},status=#{status} where id=#{id};
    </update>

    <delete id="delete">
        delete from tb_brand where id=#{id};
    </delete>

    <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
    </select>

    <select id="selectByIdBrand"  resultMap="brandResultMap">
        select * from tb_brand where id=#{id};
    </select>

</mapper>

7. Query all

When we click index.htmlon 查询所有this hyperlink in the page, we can query the data in the right half of the figure above.

For the above functions, clicking on 查询所有the hyperlink requires the backend first servlet, and servletjumps to the corresponding page for dynamic display of data. The whole process is as follows:

 7.1 Write BrandMapper

mapperCreate an interface under the package  BrandMapperand define selectAll()a method

List<Brand> selectAll();

7.2 Writing tool classes

com Create utilsa package , and create SqlSessionFactoryUtilsa tool class named tool under the package

package com.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        //静态代码块会随着类的加载而自动执行,且只执行一次
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

7.3 Write BrandService

Create class under servicepackage BrandService

package com.service;

import com.mapper.BrandMapper;
import com.pojo.Brand;
import com.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

//    查询所有
    public List<Brand> selectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        List<Brand> brands = mapper.selectAll();

        sqlSession.close();

        return brands;
    }

//    添加数据
    public void add(Brand brand)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        mapper.add(brand);

//        增删改需要提交事务才能正常进行,查询不需要
        sqlSession.commit();

        sqlSession.close();
    }

    //按照id查询
    public Brand selectById(int id){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        Brand brand = mapper.selectByIdBrand(id);

        sqlSession.close();

        return brand;
    }

    //修改
    public void Update(Brand brand){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        mapper.update(brand);

        sqlSession.commit();

        sqlSession.close();
    }

    //删除
    public void Delete(Brand brand){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        mapper.delete(brand);

        sqlSession.commit();

        sqlSession.close();
    }
}

7.4 Writing Servlets

Create a package named under webthe package , the logic of is as follows:SelectAllServletservletservlet

  • BrandServiceCall selectAll()the method for business logic processing and receive the returned result

  • Store the result returned by the previous step into requestthe domain object

  • Jump to brand.jspthe page for data display

The specific code is as follows

package com.web;

import com.pojo.Brand;
import com.service.BrandService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "SelectAllServlet", value = "/SelectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BrandService brandService = new BrandService();
        List<Brand> brands = brandService.selectAll();

        request.setAttribute("brands",brands);

        request.getRequestDispatcher("/brand.jsp").forward(request,response);
    }

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

7.5 Write brand.jsp page

 Use and in thebrand.jsp table on the page to get the collection data named and display it. The content of the page is as follows:JSTLEL表达式brands

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>显示页面</title>
</head>
<body>
<input type="button" value="新增" id="add"><br>
   <table border="1px">
    <tr>
        <th>序号</th>
        <th>品牌名称</th>
        <th>企业名称</th>
        <th>排序</th>
        <th>品牌介绍</th>
        <th>状态</th>
        <th>操作</th>
    </tr>

    <c:forEach items="${brands}" var="brand">
        <tr align="center"bgcolor="#ffc0cb">
            <td>${brand.id}</td>
            <td>${brand.brandName}</td>
            <td>${brand.companyName}</td>
            <td>${brand.ordered}</td>
            <td>${brand.description}</td>
            <c:if test="${brand.status==1}">
                <td>启用</td>
            </c:if>
            <c:if test="${brand.status!=1}">
                <td>禁止</td>
            </c:if>
            <td><a href="/brand-demo/selectByIdServlet?id=${brand.id}">修改</a> <a href="/brand-demo/DeleteServlet?id=${brand.id}">删除</a></td>
        </tr>
    </c:forEach>
   </table>

<script>
    document.getElementById("add").onclick=function (){
        location.href="/brand-demo/AddBrand.jsp";
    }
</script>

</body>
</html>

8. Rest of the code download:

MVC three-tier architecture application case simple code-Java Documentation Resources-CSDN Library

Can you give me a free like! !    

Guess you like

Origin blog.csdn.net/weixin_59798969/article/details/126076714