JavaWeb综合案例(黑马程序员2021年JavaWeb课程总结,所有功能均实现,包含数据库sql文件)

12 篇文章 0 订阅
4 篇文章 1 订阅

目录

1.案例介绍:

2.项目结构:

3.BrandMapper接口类

4.Brand实体类

5.PageBean实体类

6.BrandService接口类

7.BrandServiceimpl实现类

8.SqlSessionFactoryUtils工具类

9.BaseServlet

10.BrandServlet

11.UserServlet(没有写)

12.BrandMapper.xml映射文件

13.mybatis-config.xml连接数据库文件

14.brand.html

15.pom.xml Maven配置文件

 16.mysql数据库文件

16.成品效果 


1.案例介绍:

1.前端:Vue.js + element-ui + ajax(axios)+ html

2.后端:maven + mybatis + servlet 

2.项目结构:

3.BrandMapper接口类

package com.itheima.mapper;

import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

public interface BrandMapper {
    /**
     * 查询所有
     *
     * @return
     */
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

    /**
     * dao层添加数据
     *
     * @param brand
     */
    @Insert("insert into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

    /**
     * 修改字段(修改全部字段你和修改部分字段),我用的是修改全部字段
     *sql语句写到了映射文件
     * @param brand
     * @return
     */
    int update(Brand brand);

    /**
     * 单个删除
     * @param id
     */
    @Delete("delete from  tb_brand where id = #{id};")
    void deleteById(int id);

    /**
     * 批量删除
     * @param ids
     */
    void deleteByIds( @Param("ids")int [] ids);

    /**
     * 因为有两个参数,所以要用param注解,我也不知道为啥(分页查询)
     * @param begin
     * @param size
     * @return
     */
    @Select("select * from tb_brand limit #{begin},#{size}")
    @ResultMap("brandResultMap")
    List<Brand> selectByPage(@Param("begin") int begin,@Param("size")int size);

    /**
     * 查询总记录数
     * @return
     */
    @Select("select Count(*) from tb_brand")
    int selectTotalCount();

    /**
     * 分页条件查询
     * @param begin
     * @param size
     * @param brand
     * @return
     */
    List<Brand> selectByPageAndCondition(@Param("begin") int begin,@Param("size")int size,@Param("brand") Brand brand);

    /**
     * 查询总记录数(分页版本)(根据条件查询)
     * @param brand
     * @return
     */
    int selectTotalCountByCondition(Brand brand);
}

4.Brand实体类

package com.itheima.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 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 String getStatusStr(){
        if (status == null){
            return "未知";
        }
        return status == 0 ? "禁用":"启用";
    }

    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 +
                '}';
    }
}

5.PageBean实体类

package com.itheima.pojo;

import java.util.List;

/**
 * 分页查询的的JavaBean,目的是为了给前端提供数据
 */
public class PageBean<T> {


    //总记录数
    private int totalCount;
    //当前页数据,泛型T,是为了更好的适配各种各样的实体
    private List<T> rows;



    public int getTotalCount() {
        return totalCount;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }
}

6.BrandService接口类

package com.itheima.service;

import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BrandService {
    /**
     * 查询所有
     *
     * @return
     */
    List<Brand> selectAll();

    /**
     * 插入表单
     *
     * @param brand
     */
    void add(Brand brand);

    /**
     * 部分和全部修改全部有
     *
     * @param brand
     * @return
     */
    int update(Brand brand);

    /**
     * 删除一个
     *
     * @param id
     */
    void deleteById(int id);

    /**
     * 批量删除
     *
     * @param ids
     */
    void deleteByIds(int[] ids);

    /**
     * 分页查询
     *
     * @param currentPage 当前页码
     * @param pageSize    每页展示条数
     * @return
     */
    PageBean<Brand> selectByPage(int currentPage, int pageSize);

    /**
     * 分页条件查询
     * @param currentPage
     * @param pageSize
     * @param brand
     * @return
     */
    PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand);

}

7.BrandServiceimpl实现类

package com.itheima.service.impl;

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

import java.util.List;

public class BrandServiceImpl implements BrandService {
    //初始化工具类
    private SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<Brand> selectAll() {
        //1.获取sqlsession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
        //2.获取BrandMapper映射文件
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.调取service接口的方法
        List<Brand> brands = mapper.selectAll();
        //4.释放资源
        sqlSession.close();
        //5.返回集合
        return brands;
    }

    /**
     * 插入表单
     *
     * @param brand
     */
    @Override
    public void add(Brand brand) {
        //1.获取sqlsession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
        //2.获取BrandMapper映射文件
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.调取service接口的方法
        mapper.add(brand);
        //4.释放资源
        sqlSession.close();

    }

    /**
     * 更新,因为是部分更新,所以全部更新1也能用
     *
     * @param brand
     * @return
     */
    @Override
    public int update(Brand brand) {
        //1.获取sqlsession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
        //2.获取BrandMapper映射文件
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.调取service接口的方法
        int update = mapper.update(brand);
        //4.释放资源
        sqlSession.close();
        //5.给返回值
        return update;
    }

    /**
     * 删除一个
     *
     * @param id
     */
    @Override
    public void deleteById(int id) {
        //1.获取sqlsession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
        //2.获取BrandMapper映射文件
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.调取service接口的方法
        mapper.deleteById(id);
        //4.释放资源
        sqlSession.close();
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(int[] ids) {
        //1.获取sqlsession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
        //2.获取BrandMapper映射文件
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.调取service接口的方法
        mapper.deleteByIds(ids);
        //4.释放资源
        sqlSession.close();
    }

    /**
     * 分页查询(学到了新知识,真高兴,激动的不得了)
     *
     * @param currentPage 当前页码
     * @param pageSize    每页展示条数
     * @return
     */
    @Override
    public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
        //1.获取sqlsession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
        //2.获取BrandMapper映射文件
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //3.计算
        int begin = (currentPage - 1) * pageSize;
        int size = pageSize;

        //4.查询当前页的数据
        List<Brand> rows= mapper.selectByPage(begin, size);

        //5.查询总记录数
        int totalCount = mapper.selectTotalCount();

        //6.把rows与totalCount封装成一个PageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        //7.释放资源
        sqlSession.close();

        //8.返回值
        return pageBean;
    }

    /**
     * 分页条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param brand
     * @return
     */
    @Override
    public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
        //1.获取sqlsession的对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
        //2.获取BrandMapper映射文件
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //3.计算,,处理一下brand条件,模糊表达式
        int begin = (currentPage - 1) * pageSize;
        int size = pageSize;

        //处理brand条件,模糊表达式
        String brandName = brand.getBrandName();
        if(brandName != null  && brandName.length()>0){
            brand.setBrandName("%"+brandName+"%");
        }
        String companyName = brand.getCompanyName();
        if(companyName != null  && companyName.length()>0){
            brand.setCompanyName("%"+companyName+"%");
        }

        //4.查询当前页的数据
        List<Brand> rows= mapper.selectByPageAndCondition(begin, size,brand);

        //5.查询总记录数
        int totalCount = mapper.selectTotalCountByCondition(brand);

        //6.把rows与totalCount封装成一个PageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        //7.释放资源
        sqlSession.close();

        //8.返回值
        return pageBean;
    }

}

8.SqlSessionFactoryUtils工具类

package com.itheima.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;
    }
}

9.BaseServlet

package com.itheima.web.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 1.替换HttpServlet的protected service的方法,使之很具请求最后一段路径名来进行方法分发
 * 2.重写protected service方法准备重写
 */

public class BaseServlet extends HttpServlet {

    /**
     * service的方法是servlet会自动调用的,如果没有复写,就会去调用HttpServlet中的service方法
     * 根据请求的最后一段来进行方法分发
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.获取请求路径(获取地址栏输入的url地址路径),短路径,req.getRequestURL()(长路径)
        String uri = req.getRequestURI(); //uri形式为/Brand-case/brand/selectAll

        //2.截取  整条路经的最后的执行文件(方法名)(截取字符串)
        int index = uri.lastIndexOf("/");//从后往前数 “/” 第一次出现的索引
        String methodName = uri.substring(index+1);//由于结果是  /selectAll带斜杆---我不是很理解

        //3.执行方法
        //3.1 获取BrandServlet/UserServlet的字节码文件 Class
        //this 谁调用我,我代表谁(谁调用this所在的方法,谁就是this,可以是brandServlet,UserServlet,Base的任何子类)
        Class<? extends BaseServlet> cls = this.getClass();

        //3.2获取方法method对象()请求参数
        try {
            //3.2获取方法method对象()请求参数
            Method method = cls.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);

            //3.3执行方法
            method.invoke(this,req,resp);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}

10.BrandServlet

package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {

    //如果将来service层的代码发生了变化,相对应的servlet的代码也得跟着变,而接口不用变化,
    private BrandService brandService = new BrandServiceImpl();


    /**
     * selectAll查询所有
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取service实现类中的方法
        List<Brand> brands = brandService.selectAll();

        //2.把service实现类中返回值改成json格式,
        String s = JSON.toJSONString(brands);

        //3.别忘了编码问题,从数据库出来,改成json的格式,并设置data的结果值
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(s);
    }

    /**
     * 添加数据(暂时没有灵活性的添加数据)
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取请求行数据(获取json格式的独特方法JavaWeb)
        BufferedReader reader = request.getReader();

        //2.读取请求行数据(json字符串)
        String s = reader.readLine();

        //3.把json格式转为java对象
        Brand brand = JSONObject.parseObject(s, Brand.class);

        //4.调用BrandServiceImpl方法,并且传入数据
        brandService.add(brand);

        //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
        response.getWriter().write("success");
    }

    /**
     * 删除数据(根据单个的id传入参数,进行传入id)
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取请求行数据(获取json格式的独特方法JavaWeb)
        BufferedReader reader = request.getReader();

        //2.读取请求行数据(json字符串)
        String s = reader.readLine();

        //3.把json格式转为java对象
        Brand brand = JSONObject.parseObject(s, Brand.class);

        //4.调用BrandServiceImpl方法,并且传入数据
        brandService.deleteById(brand.getId());

        //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
        response.getWriter().write("success");
    }

    /**
     * 部分数据,和全部数据更新都有了
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取请求行数据(获取json格式的独特方法JavaWeb)
        BufferedReader reader = request.getReader();

        //2.读取请求行数据(json字符串)
        String s = reader.readLine();

        //3.把json格式转为java对象
        Brand brand = JSONObject.parseObject(s, Brand.class);
        //4.调用BrandServiceImpl方法,并且传入数据
        brandService.update(brand);

        //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
        response.getWriter().write("success");
    }

    /**
     * 批量删除
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取请求行数据(获取json格式的独特方法JavaWeb)(获取数据形式多种多样)
        BufferedReader reader = request.getReader();

        //2.读取请求行数据(json字符串)
        String s = reader.readLine();

        //3.把json格式转为java对象
        int[] ids = JSONObject.parseObject(s, int[].class);

        //4.调用BrandServiceImpl方法,并且传入数据
        brandService.deleteByIds(ids);

        //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
        response.getWriter().write("success");
    }

    /**
     * 分页查询
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取当前页码handleCurrentChange,和每页展示条数handleSizeChange url?currentPage=1&pageSize=5,把参数放到请求之后
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        //2.把接收的数据,转换成Integer
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        //3.调用service进行查询
        PageBean<Brand> brandPageBean = brandService.selectByPage(currentPage, pageSize);

        //4.把service实现类中返回值改成json格式,
        String s = JSON.toJSONString(brandPageBean);

        //5.别忘了编码问题,从数据库出来,改成json的格式,并设置data的结果值
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(s);
    }

    /**
     * 分页动态条件查询
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取当前页码handleCurrentChange,和每页展示条数handleSizeChange url?currentPage=1&pageSize=5,把参数放到请求之后
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        //2.把接收的数据,转换成Integer
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);


        //1.获取请求行数据(获取json格式的独特方法JavaWeb)
        BufferedReader reader = request.getReader();

        //2.读取请求行数据(json字符串)
        String s = reader.readLine();

        //3.把json格式转为java对象
        Brand brand = JSONObject.parseObject(s, Brand.class);


        //3.调用service进行查询
        PageBean<Brand> brandPageBean = brandService.selectByPageAndCondition(currentPage, pageSize, brand);

        //4.把service实现类中返回值改成json格式,
        String s2 = JSON.toJSONString(brandPageBean);

        //5.别忘了编码问题,从数据库出来,改成json的格式,并设置data的结果值
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(s2);
    }
}


11.UserServlet(没有写)

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

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

    <!--
         修改部分字段(当然也能修改全部字段)详细内容看https://blog.csdn.net/qq_51272114/article/details/
    -->
    <update id="update">
        update tb_brand
        <set>
            <if test="companyName != null and companyName != '' ">
                company_name=#{companyName},
            </if>
            <if test="brandName != null and brandName != '' ">
                brand_name=#{brandName},
            </if>
            <if test="ordered != null ">
                ordered=#{ordered},
            </if>
            <if test="description != null and description != '' ">
                description=#{description},
            </if>
            <if test="status != null ">
                status=#{status}
            </if>
        </set>
        where id = #{id};
    </update>

    <!--
        批量删除数据(遍历id集合),详细内容看https://blog.csdn.net/qq_51272114/article/details/
    -->
    <delete id="deleteByIds">
        delete from tb_brand where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">#{id}</foreach>
        ;
    </delete>

     <!--
          f分页条件查询
     -->

    <select id="selectByPageAndCondition" resultType="com.itheima.pojo.Brand" resultMap="brandResultMap">
        select * from tb_brand
        <where>
            <if test="brand.status  != null">
                and status = #{brand.status}
            </if>
            <if test="brand.companyName != null and brand.companyName != '' ">
                and company_name like #{brand.companyName}
            </if>
            <if test="brand.brandName != null and brand.brandName != ''">
                and brand_name like #{brand.brandName}
            </if>
        </where>
        limit #{begin},#{size}
    </select>

    <!--
            根据条件查询总记录数
    -->
    <select id="selectTotalCountByCondition" resultType="java.lang.Integer">
        select count(*) from tb_brand
        <where>
            <if test="status  != null">
                and status = #{status}
            </if>
            <if test="companyName != null and companyName != '' ">
                and company_name like #{companyName}
            </if>
            <if test="brandName != null and brandName != ''">
                and brand_name like #{brandName}
            </if>
        </where>
    </select>
</mapper>

13.mybatis-config.xml连接数据库文件

<?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.itheima.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:///db1?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
       <!--扫描mapper-->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

14.brand.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

        <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
            title="新增品牌"
            :visible.sync="dialogVisible"
            width="30%"
    >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>

    <!--update表单-->
    <el-dialog
            title="修改品牌"
            :visible.sync="updateDialogVisible"
            width="30%"
    >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-input v-model="brand.id" type="hidden"></el-input>
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="updateBrand">提交</el-button>
                <el-button @click="updateDialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>

    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="status"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">
                <template slot-scope="scope">
                    <el-row>
                        <el-button type="primary" @click=startUpdate(scope.row)>修改</el-button>
                        <el-button type="danger" @click="open(scope.row)">删除</el-button>
                    </el-row>
                </template>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            layout="prev, pager, next"
            :total="100">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script src="js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: "#app",

        mounted() {
            //调用selectAll方法直接使用
            this.selectAll();
        },
        methods: {
            selectAll() {
                //var _this = this;//提生命周期
                axios({
                    method: "post",
                    url: "http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize + "",
                    data: this.brand,
                }).then(resp => {  //新特性,然后就可以在then里面的下划线say no了
                    this.tableData = resp.data.rows;//此时{rows:[],totalCount:[]}
                    this.totalCount = resp.data.totalCount;
                })
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                console.log(this.multipleSelection)
            },
            // 添加数据
            addBrand() {
                //console.log(this.brand);
                //发送Ajax请求,发送json数据
                //var _this = this;
                axios({
                    method: "post",
                    url: "http://localhost:8080/brand-case/brand/add",
                    data: this.brand
                }).then(resp => {
                    if (resp.data == "success") {
                        //录入成功,关闭窗口,并且重新查询数据
                        this.dialogVisible = false;
                        this.selectAll();
                        this.$message({
                            message: '成功添加一条数据',
                            type: 'success'
                        });
                    }
                })
            },
            // 修改数据
            updateBrand() {
                //console.log(this.brand);可以获取完整数据
                //发送Ajax请求,发送json数据
                //var _this = this;
                axios({
                    method: "post",
                    url: "http://localhost:8080/brand-case/brand/update",
                    data: this.brand
                }).then(resp => {
                    if (resp.data == "success") {
                        //录入成功,关闭窗口,并且重新查询数据
                        this.updateDialogVisible = false;
                        this.selectAll();
                        this.$message({
                            message: '成功添加一条数据',
                            type: 'success'
                        });
                    }
                })
            },
            //执行修改的onclick
            startUpdate(row) {
                // 获取改行已经有的数据,以供填入修改框
                // var _this = this
                this.brand = JSON.parse(JSON.stringify(row));
                // 弹出修改框
                this.updateDialogVisible = true;
            },
            //打开删除的提示框,并根据提示进行操作
            open(row) {
                this.brand = JSON.parse(JSON.stringify(row));
                //var _this = this;
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {  //确认之后执行axios请求
                    axios({
                        method: "post",
                        url: "http://localhost:8080/brand-case/brand/deleteById",
                        data: this.brand
                    }).then(resp => {
                        if (resp.data == "success") {
                            //录入成功,关闭窗口,并且重新查询数据
                            this.selectAll();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        }
                    })

                }).catch(() => { //取消之后执行标签
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //批量删除的单击事件
            deleteByIds() {
                //console.log(this.multipleSelection);
                //1.创建id数组[1,2,3],从multipleSelection模型里面来的数据
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    let element = this.multipleSelection[i];
                    //获取遍历后得到id值
                    this.selectByIds[i] = element.id;
                }
                //var _this = this;
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios({
                        method: "post",
                        url: "http://localhost:8080/brand-case/brand/deleteByIds",
                        data: this.selectByIds
                    }).then(resp => {
                        if (resp.data == "success") {
                            //录入成功,关闭窗口,并且重新查询数据
                            this.selectAll();
                            this.$message({
                                message: '成功删除数据',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: '没有数据可以删除',
                                type: 'info'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            //
            // 查询方法
            onSubmit() {
                //console.log(this.brand);
                this.selectAll();
            },
            //每页显示条数
            handleSizeChange(val) {
                //console.log(`每页 ${val} 条`);
                //重新设置当每页显示的条数
                this.pageSize = val;
                this.selectAll();
            },
            //当前页码
            handleCurrentChange(val) {
                //console.log(`当前页: ${val}`);
                //重新去设置当前页码,动态改变
                this.currentPage = val;
                this.selectAll();
            }

        },
        data() {
            return {
                pageSize: 5,
                //页码的总记录数
                totalCount: 100,
                // 当前页码
                currentPage: 1,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,
                updateDialogVisible: false,
                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id: '',
                    ordered: "",
                    description: ""
                },
                //被选中的id数组
                selectByIds: [],
                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }]
            }
        }
    })

</script>

</body>
</html>

15.pom.xml Maven配置文件

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>brand-case</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>18</maven.compiler.source>
        <maven.compiler.target>18</maven.compiler.target>
    </properties>
    <packaging>war</packaging>

    <build>
        <plugins>
            <!--tomcat 的插件 (相当于在maven内部放置了个tomcat服务器)-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!--apache提供的与io适配的工具类,好用-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!--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>8.0.29</version>
        </dependency>
        <!--junit依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>Test</scope>
        </dependency>
        <!--添加slf4j-api日志api-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.36</version>
        </dependency>
        <!--添加logback-classic依赖-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--添加logback-core依赖-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
        <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>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
    </dependencies>
</project>

 16.mysql数据库文件

-- 删除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 
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1)
        ;
   

SELECT * FROM tb_brand;

16.成品效果 

 

 

 

  • 22
    点赞
  • 122
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 20
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

很丧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值