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


    目录

    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接口类

    1. package com.itheima.mapper;
    2. import com.itheima.pojo.Brand;
    3. import org.apache.ibatis.annotations.*;
    4. import java.util.List;
    5. import java.util.Map;
    6. public interface BrandMapper {
    7. /**
    8. * 查询所有
    9. *
    10. * @return
    11. */
    12. @Select("select * from tb_brand")
    13. @ResultMap("brandResultMap")
    14. List selectAll();
    15. /**
    16. * dao层添加数据
    17. *
    18. * @param brand
    19. */
    20. @Insert("insert into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    21. void add(Brand brand);
    22. /**
    23. * 修改字段(修改全部字段你和修改部分字段),我用的是修改全部字段
    24. *sql语句写到了映射文件
    25. * @param brand
    26. * @return
    27. */
    28. int update(Brand brand);
    29. /**
    30. * 单个删除
    31. * @param id
    32. */
    33. @Delete("delete from tb_brand where id = #{id};")
    34. void deleteById(int id);
    35. /**
    36. * 批量删除
    37. * @param ids
    38. */
    39. void deleteByIds( @Param("ids")int [] ids);
    40. /**
    41. * 因为有两个参数,所以要用param注解,我也不知道为啥(分页查询)
    42. * @param begin
    43. * @param size
    44. * @return
    45. */
    46. @Select("select * from tb_brand limit #{begin},#{size}")
    47. @ResultMap("brandResultMap")
    48. List selectByPage(@Param("begin") int begin,@Param("size")int size);
    49. /**
    50. * 查询总记录数
    51. * @return
    52. */
    53. @Select("select Count(*) from tb_brand")
    54. int selectTotalCount();
    55. /**
    56. * 分页条件查询
    57. * @param begin
    58. * @param size
    59. * @param brand
    60. * @return
    61. */
    62. List selectByPageAndCondition(@Param("begin") int begin,@Param("size")int size,@Param("brand") Brand brand);
    63. /**
    64. * 查询总记录数(分页版本)(根据条件查询)
    65. * @param brand
    66. * @return
    67. */
    68. int selectTotalCountByCondition(Brand brand);
    69. }

    4.Brand实体类

    1. package com.itheima.pojo;
    2. public class Brand {
    3. // id 主键
    4. private Integer id;
    5. // 品牌名称
    6. private String brandName;
    7. // 企业名称
    8. private String companyName;
    9. // 排序字段
    10. private Integer ordered;
    11. // 描述信息
    12. private String description;
    13. // 状态:0:禁用 1:启用
    14. private Integer status;
    15. public Integer getId() {
    16. return id;
    17. }
    18. public void setId(Integer id) {
    19. this.id = id;
    20. }
    21. public String getBrandName() {
    22. return brandName;
    23. }
    24. public void setBrandName(String brandName) {
    25. this.brandName = brandName;
    26. }
    27. public String getCompanyName() {
    28. return companyName;
    29. }
    30. public void setCompanyName(String companyName) {
    31. this.companyName = companyName;
    32. }
    33. public Integer getOrdered() {
    34. return ordered;
    35. }
    36. public void setOrdered(Integer ordered) {
    37. this.ordered = ordered;
    38. }
    39. public String getDescription() {
    40. return description;
    41. }
    42. public void setDescription(String description) {
    43. this.description = description;
    44. }
    45. public Integer getStatus() {
    46. return status;
    47. }
    48. //逻辑视图
    49. public String getStatusStr(){
    50. if (status == null){
    51. return "未知";
    52. }
    53. return status == 0 ? "禁用":"启用";
    54. }
    55. public void setStatus(Integer status) {
    56. this.status = status;
    57. }
    58. @Override
    59. public String toString() {
    60. return "Brand{" +
    61. "id=" + id +
    62. ", brandName='" + brandName + '\'' +
    63. ", companyName='" + companyName + '\'' +
    64. ", ordered=" + ordered +
    65. ", description='" + description + '\'' +
    66. ", status=" + status +
    67. '}';
    68. }
    69. }

    5.PageBean实体类

    1. package com.itheima.pojo;
    2. import java.util.List;
    3. /**
    4. * 分页查询的的JavaBean,目的是为了给前端提供数据
    5. */
    6. public class PageBean {
    7. //总记录数
    8. private int totalCount;
    9. //当前页数据,泛型T,是为了更好的适配各种各样的实体
    10. private List rows;
    11. public int getTotalCount() {
    12. return totalCount;
    13. }
    14. public List getRows() {
    15. return rows;
    16. }
    17. public void setTotalCount(int totalCount) {
    18. this.totalCount = totalCount;
    19. }
    20. public void setRows(List rows) {
    21. this.rows = rows;
    22. }
    23. }

    6.BrandService接口类

    1. package com.itheima.service;
    2. import com.itheima.pojo.Brand;
    3. import com.itheima.pojo.PageBean;
    4. import org.apache.ibatis.annotations.Param;
    5. import java.util.List;
    6. public interface BrandService {
    7. /**
    8. * 查询所有
    9. *
    10. * @return
    11. */
    12. List selectAll();
    13. /**
    14. * 插入表单
    15. *
    16. * @param brand
    17. */
    18. void add(Brand brand);
    19. /**
    20. * 部分和全部修改全部有
    21. *
    22. * @param brand
    23. * @return
    24. */
    25. int update(Brand brand);
    26. /**
    27. * 删除一个
    28. *
    29. * @param id
    30. */
    31. void deleteById(int id);
    32. /**
    33. * 批量删除
    34. *
    35. * @param ids
    36. */
    37. void deleteByIds(int[] ids);
    38. /**
    39. * 分页查询
    40. *
    41. * @param currentPage 当前页码
    42. * @param pageSize 每页展示条数
    43. * @return
    44. */
    45. PageBean selectByPage(int currentPage, int pageSize);
    46. /**
    47. * 分页条件查询
    48. * @param currentPage
    49. * @param pageSize
    50. * @param brand
    51. * @return
    52. */
    53. PageBean selectByPageAndCondition(int currentPage, int pageSize, Brand brand);
    54. }

    7.BrandServiceimpl实现类

    1. package com.itheima.service.impl;
    2. import com.itheima.mapper.BrandMapper;
    3. import com.itheima.pojo.Brand;
    4. import com.itheima.pojo.PageBean;
    5. import com.itheima.service.BrandService;
    6. import com.itheima.util.SqlSessionFactoryUtils;
    7. import org.apache.ibatis.session.SqlSession;
    8. import org.apache.ibatis.session.SqlSessionFactory;
    9. import java.util.List;
    10. public class BrandServiceImpl implements BrandService {
    11. //初始化工具类
    12. private SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    13. /**
    14. * 查询所有
    15. *
    16. * @return
    17. */
    18. @Override
    19. public List selectAll() {
    20. //1.获取sqlsession的对象
    21. SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
    22. //2.获取BrandMapper映射文件
    23. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    24. //3.调取service接口的方法
    25. List brands = mapper.selectAll();
    26. //4.释放资源
    27. sqlSession.close();
    28. //5.返回集合
    29. return brands;
    30. }
    31. /**
    32. * 插入表单
    33. *
    34. * @param brand
    35. */
    36. @Override
    37. public void add(Brand brand) {
    38. //1.获取sqlsession的对象
    39. SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
    40. //2.获取BrandMapper映射文件
    41. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    42. //3.调取service接口的方法
    43. mapper.add(brand);
    44. //4.释放资源
    45. sqlSession.close();
    46. }
    47. /**
    48. * 更新,因为是部分更新,所以全部更新1也能用
    49. *
    50. * @param brand
    51. * @return
    52. */
    53. @Override
    54. public int update(Brand brand) {
    55. //1.获取sqlsession的对象
    56. SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
    57. //2.获取BrandMapper映射文件
    58. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    59. //3.调取service接口的方法
    60. int update = mapper.update(brand);
    61. //4.释放资源
    62. sqlSession.close();
    63. //5.给返回值
    64. return update;
    65. }
    66. /**
    67. * 删除一个
    68. *
    69. * @param id
    70. */
    71. @Override
    72. public void deleteById(int id) {
    73. //1.获取sqlsession的对象
    74. SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
    75. //2.获取BrandMapper映射文件
    76. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    77. //3.调取service接口的方法
    78. mapper.deleteById(id);
    79. //4.释放资源
    80. sqlSession.close();
    81. }
    82. /**
    83. * 批量删除
    84. *
    85. * @param ids
    86. */
    87. @Override
    88. public void deleteByIds(int[] ids) {
    89. //1.获取sqlsession的对象
    90. SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
    91. //2.获取BrandMapper映射文件
    92. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    93. //3.调取service接口的方法
    94. mapper.deleteByIds(ids);
    95. //4.释放资源
    96. sqlSession.close();
    97. }
    98. /**
    99. * 分页查询(学到了新知识,真高兴,激动的不得了)
    100. *
    101. * @param currentPage 当前页码
    102. * @param pageSize 每页展示条数
    103. * @return
    104. */
    105. @Override
    106. public PageBean selectByPage(int currentPage, int pageSize) {
    107. //1.获取sqlsession的对象
    108. SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
    109. //2.获取BrandMapper映射文件
    110. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    111. //3.计算
    112. int begin = (currentPage - 1) * pageSize;
    113. int size = pageSize;
    114. //4.查询当前页的数据
    115. List rows= mapper.selectByPage(begin, size);
    116. //5.查询总记录数
    117. int totalCount = mapper.selectTotalCount();
    118. //6.把rows与totalCount封装成一个PageBean对象
    119. PageBean pageBean = new PageBean<>();
    120. pageBean.setRows(rows);
    121. pageBean.setTotalCount(totalCount);
    122. //7.释放资源
    123. sqlSession.close();
    124. //8.返回值
    125. return pageBean;
    126. }
    127. /**
    128. * 分页条件查询
    129. *
    130. * @param currentPage
    131. * @param pageSize
    132. * @param brand
    133. * @return
    134. */
    135. @Override
    136. public PageBean selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
    137. //1.获取sqlsession的对象
    138. SqlSession sqlSession = sqlSessionFactory.openSession(true);//自定提交事务
    139. //2.获取BrandMapper映射文件
    140. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    141. //3.计算,,处理一下brand条件,模糊表达式
    142. int begin = (currentPage - 1) * pageSize;
    143. int size = pageSize;
    144. //处理brand条件,模糊表达式
    145. String brandName = brand.getBrandName();
    146. if(brandName != null && brandName.length()>0){
    147. brand.setBrandName("%"+brandName+"%");
    148. }
    149. String companyName = brand.getCompanyName();
    150. if(companyName != null && companyName.length()>0){
    151. brand.setCompanyName("%"+companyName+"%");
    152. }
    153. //4.查询当前页的数据
    154. List rows= mapper.selectByPageAndCondition(begin, size,brand);
    155. //5.查询总记录数
    156. int totalCount = mapper.selectTotalCountByCondition(brand);
    157. //6.把rows与totalCount封装成一个PageBean对象
    158. PageBean pageBean = new PageBean<>();
    159. pageBean.setRows(rows);
    160. pageBean.setTotalCount(totalCount);
    161. //7.释放资源
    162. sqlSession.close();
    163. //8.返回值
    164. return pageBean;
    165. }
    166. }

    8.SqlSessionFactoryUtils工具类

    1. package com.itheima.util;
    2. import org.apache.ibatis.io.Resources;
    3. import org.apache.ibatis.session.SqlSessionFactory;
    4. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    5. import java.io.IOException;
    6. import java.io.InputStream;
    7. public class SqlSessionFactoryUtils {
    8. private static SqlSessionFactory sqlSessionFactory;
    9. static {
    10. //静态代码块会随着类的加载而自动执行,且只执行一次
    11. try {
    12. String resource = "mybatis-config.xml";
    13. InputStream inputStream = Resources.getResourceAsStream(resource);
    14. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    15. } catch (IOException e) {
    16. e.printStackTrace();
    17. }
    18. }
    19. public static SqlSessionFactory getSqlSessionFactory(){
    20. return sqlSessionFactory;
    21. }
    22. }

    9.BaseServlet

    1. package com.itheima.web.servlet;
    2. import javax.servlet.*;
    3. import javax.servlet.http.*;
    4. import javax.servlet.annotation.*;
    5. import java.io.BufferedReader;
    6. import java.io.IOException;
    7. import java.lang.reflect.InvocationTargetException;
    8. import java.lang.reflect.Method;
    9. /**
    10. * 1.替换HttpServlet的protected service的方法,使之很具请求最后一段路径名来进行方法分发
    11. * 2.重写protected service方法准备重写
    12. */
    13. public class BaseServlet extends HttpServlet {
    14. /**
    15. * service的方法是servlet会自动调用的,如果没有复写,就会去调用HttpServlet中的service方法
    16. * 根据请求的最后一段来进行方法分发
    17. */
    18. @Override
    19. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    20. //1.获取请求路径(获取地址栏输入的url地址路径),短路径,req.getRequestURL()(长路径)
    21. String uri = req.getRequestURI(); //uri形式为/Brand-case/brand/selectAll
    22. //2.截取 整条路经的最后的执行文件(方法名)(截取字符串)
    23. int index = uri.lastIndexOf("/");//从后往前数 “/” 第一次出现的索引
    24. String methodName = uri.substring(index+1);//由于结果是 /selectAll带斜杆---我不是很理解
    25. //3.执行方法
    26. //3.1 获取BrandServlet/UserServlet的字节码文件 Class
    27. //this 谁调用我,我代表谁(谁调用this所在的方法,谁就是this,可以是brandServlet,UserServlet,Base的任何子类)
    28. Classextends BaseServlet> cls = this.getClass();
    29. //3.2获取方法method对象()请求参数
    30. try {
    31. //3.2获取方法method对象()请求参数
    32. Method method = cls.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
    33. //3.3执行方法
    34. method.invoke(this,req,resp);
    35. } catch (NoSuchMethodException e) {
    36. e.printStackTrace();
    37. } catch (InvocationTargetException e) {
    38. e.printStackTrace();
    39. } catch (IllegalAccessException e) {
    40. e.printStackTrace();
    41. }
    42. }
    43. }

    10.BrandServlet

    1. package com.itheima.web.servlet;
    2. import com.alibaba.fastjson.JSON;
    3. import com.alibaba.fastjson.JSONObject;
    4. import com.itheima.pojo.Brand;
    5. import com.itheima.pojo.PageBean;
    6. import com.itheima.service.BrandService;
    7. import com.itheima.service.impl.BrandServiceImpl;
    8. import javax.servlet.ServletException;
    9. import javax.servlet.annotation.*;
    10. import javax.servlet.http.HttpServletRequest;
    11. import javax.servlet.http.HttpServletResponse;
    12. import java.io.BufferedReader;
    13. import java.io.IOException;
    14. import java.util.List;
    15. @WebServlet("/brand/*")
    16. public class BrandServlet extends BaseServlet {
    17. //如果将来service层的代码发生了变化,相对应的servlet的代码也得跟着变,而接口不用变化,
    18. private BrandService brandService = new BrandServiceImpl();
    19. /**
    20. * selectAll查询所有
    21. *
    22. * @param request
    23. * @param response
    24. * @throws ServletException
    25. * @throws IOException
    26. */
    27. public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    28. //1.获取service实现类中的方法
    29. List brands = brandService.selectAll();
    30. //2.把service实现类中返回值改成json格式,
    31. String s = JSON.toJSONString(brands);
    32. //3.别忘了编码问题,从数据库出来,改成json的格式,并设置data的结果值
    33. response.setContentType("text/json;charset=utf-8");
    34. response.getWriter().write(s);
    35. }
    36. /**
    37. * 添加数据(暂时没有灵活性的添加数据)
    38. *
    39. * @param request
    40. * @param response
    41. * @throws ServletException
    42. * @throws IOException
    43. */
    44. public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    45. //1.获取请求行数据(获取json格式的独特方法JavaWeb)
    46. BufferedReader reader = request.getReader();
    47. //2.读取请求行数据(json字符串)
    48. String s = reader.readLine();
    49. //3.把json格式转为java对象
    50. Brand brand = JSONObject.parseObject(s, Brand.class);
    51. //4.调用BrandServiceImpl方法,并且传入数据
    52. brandService.add(brand);
    53. //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
    54. response.getWriter().write("success");
    55. }
    56. /**
    57. * 删除数据(根据单个的id传入参数,进行传入id)
    58. *
    59. * @param request
    60. * @param response
    61. * @throws ServletException
    62. * @throws IOException
    63. */
    64. public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    65. //1.获取请求行数据(获取json格式的独特方法JavaWeb)
    66. BufferedReader reader = request.getReader();
    67. //2.读取请求行数据(json字符串)
    68. String s = reader.readLine();
    69. //3.把json格式转为java对象
    70. Brand brand = JSONObject.parseObject(s, Brand.class);
    71. //4.调用BrandServiceImpl方法,并且传入数据
    72. brandService.deleteById(brand.getId());
    73. //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
    74. response.getWriter().write("success");
    75. }
    76. /**
    77. * 部分数据,和全部数据更新都有了
    78. *
    79. * @param request
    80. * @param response
    81. * @throws ServletException
    82. * @throws IOException
    83. */
    84. public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    85. //1.获取请求行数据(获取json格式的独特方法JavaWeb)
    86. BufferedReader reader = request.getReader();
    87. //2.读取请求行数据(json字符串)
    88. String s = reader.readLine();
    89. //3.把json格式转为java对象
    90. Brand brand = JSONObject.parseObject(s, Brand.class);
    91. //4.调用BrandServiceImpl方法,并且传入数据
    92. brandService.update(brand);
    93. //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
    94. response.getWriter().write("success");
    95. }
    96. /**
    97. * 批量删除
    98. *
    99. * @param request
    100. * @param response
    101. * @throws ServletException
    102. * @throws IOException
    103. */
    104. public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    105. //1.获取请求行数据(获取json格式的独特方法JavaWeb)(获取数据形式多种多样)
    106. BufferedReader reader = request.getReader();
    107. //2.读取请求行数据(json字符串)
    108. String s = reader.readLine();
    109. //3.把json格式转为java对象
    110. int[] ids = JSONObject.parseObject(s, int[].class);
    111. //4.调用BrandServiceImpl方法,并且传入数据
    112. brandService.deleteByIds(ids);
    113. //5.相应成功后的数据(如果代码正常执行,给与前端一个相应成功的字符串)
    114. response.getWriter().write("success");
    115. }
    116. /**
    117. * 分页查询
    118. *
    119. * @param request
    120. * @param response
    121. * @throws ServletException
    122. * @throws IOException
    123. */
    124. public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    125. //1.获取当前页码handleCurrentChange,和每页展示条数handleSizeChange url?currentPage=1&pageSize=5,把参数放到请求之后
    126. String _currentPage = request.getParameter("currentPage");
    127. String _pageSize = request.getParameter("pageSize");
    128. //2.把接收的数据,转换成Integer
    129. int currentPage = Integer.parseInt(_currentPage);
    130. int pageSize = Integer.parseInt(_pageSize);
    131. //3.调用service进行查询
    132. PageBean brandPageBean = brandService.selectByPage(currentPage, pageSize);
    133. //4.把service实现类中返回值改成json格式,
    134. String s = JSON.toJSONString(brandPageBean);
    135. //5.别忘了编码问题,从数据库出来,改成json的格式,并设置data的结果值
    136. response.setContentType("text/json;charset=utf-8");
    137. response.getWriter().write(s);
    138. }
    139. /**
    140. * 分页动态条件查询
    141. *
    142. * @param request
    143. * @param response
    144. * @throws ServletException
    145. * @throws IOException
    146. */
    147. public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    148. //1.获取当前页码handleCurrentChange,和每页展示条数handleSizeChange url?currentPage=1&pageSize=5,把参数放到请求之后
    149. String _currentPage = request.getParameter("currentPage");
    150. String _pageSize = request.getParameter("pageSize");
    151. //2.把接收的数据,转换成Integer
    152. int currentPage = Integer.parseInt(_currentPage);
    153. int pageSize = Integer.parseInt(_pageSize);
    154. //1.获取请求行数据(获取json格式的独特方法JavaWeb)
    155. BufferedReader reader = request.getReader();
    156. //2.读取请求行数据(json字符串)
    157. String s = reader.readLine();
    158. //3.把json格式转为java对象
    159. Brand brand = JSONObject.parseObject(s, Brand.class);
    160. //3.调用service进行查询
    161. PageBean brandPageBean = brandService.selectByPageAndCondition(currentPage, pageSize, brand);
    162. //4.把service实现类中返回值改成json格式,
    163. String s2 = JSON.toJSONString(brandPageBean);
    164. //5.别忘了编码问题,从数据库出来,改成json的格式,并设置data的结果值
    165. response.setContentType("text/json;charset=utf-8");
    166. response.getWriter().write(s2);
    167. }
    168. }

    11.UserServlet(没有写)

    12.BrandMapper.xml映射文件

    1. "1.0" encoding="UTF-8" ?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.itheima.mapper.BrandMapper">
    6. <resultMap id="brandResultMap" type="brand">
    7. <result property="brandName" column="brand_name"/>
    8. <result property="companyName" column="company_name"/>
    9. resultMap>
    10. <update id="update">
    11. update tb_brand
    12. <set>
    13. <if test="companyName != null and companyName != '' ">
    14. company_name=#{companyName},
    15. if>
    16. <if test="brandName != null and brandName != '' ">
    17. brand_name=#{brandName},
    18. if>
    19. <if test="ordered != null ">
    20. ordered=#{ordered},
    21. if>
    22. <if test="description != null and description != '' ">
    23. description=#{description},
    24. if>
    25. <if test="status != null ">
    26. status=#{status}
    27. if>
    28. set>
    29. where id = #{id};
    30. update>
    31. <delete id="deleteByIds">
    32. delete from tb_brand where id in
    33. <foreach collection="ids" item="id" separator="," open="(" close=")">#{id}foreach>
    34. ;
    35. delete>
    36. <select id="selectByPageAndCondition" resultType="com.itheima.pojo.Brand" resultMap="brandResultMap">
    37. select * from tb_brand
    38. <where>
    39. <if test="brand.status != null">
    40. and status = #{brand.status}
    41. if>
    42. <if test="brand.companyName != null and brand.companyName != '' ">
    43. and company_name like #{brand.companyName}
    44. if>
    45. <if test="brand.brandName != null and brand.brandName != ''">
    46. and brand_name like #{brand.brandName}
    47. if>
    48. where>
    49. limit #{begin},#{size}
    50. select>
    51. <select id="selectTotalCountByCondition" resultType="java.lang.Integer">
    52. select count(*) from tb_brand
    53. <where>
    54. <if test="status != null">
    55. and status = #{status}
    56. if>
    57. <if test="companyName != null and companyName != '' ">
    58. and company_name like #{companyName}
    59. if>
    60. <if test="brandName != null and brandName != ''">
    61. and brand_name like #{brandName}
    62. if>
    63. where>
    64. select>
    65. mapper>

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

    1. "1.0" encoding="UTF-8" ?>
    2. configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <typeAliases>
    7. <package name="com.itheima.pojo"/>
    8. typeAliases>
    9. <environments default="development">
    10. <environment id="development">
    11. <transactionManager type="JDBC"/>
    12. <dataSource type="POOLED">
    13. <property name="driver" value="com.mysql.jdbc.Driver"/>
    14. <property name="url" value="jdbc:mysql:///db1?useSSL=false"/>
    15. <property name="username" value="root"/>
    16. <property name="password" value="root"/>
    17. dataSource>
    18. environment>
    19. environments>
    20. <mappers>
    21. <package name="com.itheima.mapper"/>
    22. mappers>
    23. configuration>

    14.brand.html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. <style>
    7. .el-table .warning-row {
    8. background: oldlace;
    9. }
    10. .el-table .success-row {
    11. background: #f0f9eb;
    12. }
    13. style>
    14. head>
    15. <body>
    16. <div id="app">
    17. <el-form :inline="true" :model="brand" class="demo-form-inline">
    18. <el-form-item label="当前状态">
    19. <el-select v-model="brand.status" placeholder="当前状态">
    20. <el-option label="启用" value="1">el-option>
    21. <el-option label="禁用" value="0">el-option>
    22. el-select>
    23. el-form-item>
    24. <el-form-item label="企业名称">
    25. <el-input v-model="brand.companyName" placeholder="企业名称">el-input>
    26. el-form-item>
    27. <el-form-item label="品牌名称">
    28. <el-input v-model="brand.brandName" placeholder="品牌名称">el-input>
    29. el-form-item>
    30. <el-form-item>
    31. <el-button type="primary" @click="onSubmit">查询el-button>
    32. el-form-item>
    33. el-form>
    34. <el-row>
    35. <el-button type="danger" plain @click="deleteByIds">批量删除el-button>
    36. <el-button type="primary" plain @click="dialogVisible = true">新增el-button>
    37. el-row>
    38. <el-dialog
    39. title="新增品牌"
    40. :visible.sync="dialogVisible"
    41. width="30%"
    42. >
    43. <el-form ref="form" :model="brand" label-width="80px">
    44. <el-form-item label="品牌名称">
    45. <el-input v-model="brand.brandName">el-input>
    46. el-form-item>
    47. <el-form-item label="企业名称">
    48. <el-input v-model="brand.companyName">el-input>
    49. el-form-item>
    50. <el-form-item label="排序">
    51. <el-input v-model="brand.ordered">el-input>
    52. el-form-item>
    53. <el-form-item label="备注">
    54. <el-input type="textarea" v-model="brand.description">el-input>
    55. el-form-item>
    56. <el-form-item label="状态">
    57. <el-switch v-model="brand.status"
    58. active-value="1"
    59. inactive-value="0"
    60. >el-switch>
    61. el-form-item>
    62. <el-form-item>
    63. <el-button type="primary" @click="addBrand">提交el-button>
    64. <el-button @click="dialogVisible = false">取消el-button>
    65. el-form-item>
    66. el-form>
    67. el-dialog>
    68. <el-dialog
    69. title="修改品牌"
    70. :visible.sync="updateDialogVisible"
    71. width="30%"
    72. >
    73. <el-form ref="form" :model="brand" label-width="80px">
    74. <el-input v-model="brand.id" type="hidden">el-input>
    75. <el-form-item label="品牌名称">
    76. <el-input v-model="brand.brandName">el-input>
    77. el-form-item>
    78. <el-form-item label="企业名称">
    79. <el-input v-model="brand.companyName">el-input>
    80. el-form-item>
    81. <el-form-item label="排序">
    82. <el-input v-model="brand.ordered">el-input>
    83. el-form-item>
    84. <el-form-item label="备注">
    85. <el-input type="textarea" v-model="brand.description">el-input>
    86. el-form-item>
    87. <el-form-item label="状态">
    88. <el-switch v-model="brand.status"
    89. active-value="1"
    90. inactive-value="0"
    91. >el-switch>
    92. el-form-item>
    93. <el-form-item>
    94. <el-button type="primary" @click="updateBrand">提交el-button>
    95. <el-button @click="updateDialogVisible = false">取消el-button>
    96. el-form-item>
    97. el-form>
    98. el-dialog>
    99. <template>
    100. <el-table
    101. :data="tableData"
    102. style="width: 100%"
    103. :row-class-name="tableRowClassName"
    104. @selection-change="handleSelectionChange"
    105. >
    106. <el-table-column
    107. type="selection"
    108. width="55">
    109. el-table-column>
    110. <el-table-column
    111. type="index"
    112. width="50">
    113. el-table-column>
    114. <el-table-column
    115. prop="brandName"
    116. label="品牌名称"
    117. align="center"
    118. >
    119. el-table-column>
    120. <el-table-column
    121. prop="companyName"
    122. label="企业名称"
    123. align="center"
    124. >
    125. el-table-column>
    126. <el-table-column
    127. prop="ordered"
    128. align="center"
    129. label="排序">
    130. el-table-column>
    131. <el-table-column
    132. prop="status"
    133. align="center"
    134. label="当前状态">
    135. el-table-column>
    136. <el-table-column
    137. align="center"
    138. label="操作">
    139. <template slot-scope="scope">
    140. <el-row>
    141. <el-button type="primary" @click=startUpdate(scope.row)>修改el-button>
    142. <el-button type="danger" @click="open(scope.row)">删除el-button>
    143. el-row>
    144. template>
    145. el-table-column>
    146. el-table>
    147. template>
    148. <el-pagination
    149. @size-change="handleSizeChange"
    150. @current-change="handleCurrentChange"
    151. :current-page="currentPage"
    152. :page-sizes="[5, 10, 15, 20]"
    153. :page-size="5"
    154. layout="total, sizes, prev, pager, next, jumper"
    155. :total="totalCount"
    156. background
    157. layout="prev, pager, next"
    158. :total="100">
    159. el-pagination>
    160. div>
    161. <script src="js/vue.js">script>
    162. <script src="element-ui/lib/index.js">script>
    163. <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    164. <script src="js/axios-0.18.0.js">script>
    165. <script>
    166. new Vue({
    167. el: "#app",
    168. mounted() {
    169. //调用selectAll方法直接使用
    170. this.selectAll();
    171. },
    172. methods: {
    173. selectAll() {
    174. //var _this = this;//提生命周期
    175. axios({
    176. method: "post",
    177. url: "http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize + "",
    178. data: this.brand,
    179. }).then(resp => { //新特性,然后就可以在then里面的下划线say no了
    180. this.tableData = resp.data.rows;//此时{rows:[],totalCount:[]}
    181. this.totalCount = resp.data.totalCount;
    182. })
    183. },
    184. tableRowClassName({row, rowIndex}) {
    185. if (rowIndex === 1) {
    186. return 'warning-row';
    187. } else if (rowIndex === 3) {
    188. return 'success-row';
    189. }
    190. return '';
    191. },
    192. // 复选框选中后执行的方法
    193. handleSelectionChange(val) {
    194. this.multipleSelection = val;
    195. console.log(this.multipleSelection)
    196. },
    197. // 添加数据
    198. addBrand() {
    199. //console.log(this.brand);
    200. //发送Ajax请求,发送json数据
    201. //var _this = this;
    202. axios({
    203. method: "post",
    204. url: "http://localhost:8080/brand-case/brand/add",
    205. data: this.brand
    206. }).then(resp => {
    207. if (resp.data == "success") {
    208. //录入成功,关闭窗口,并且重新查询数据
    209. this.dialogVisible = false;
    210. this.selectAll();
    211. this.$message({
    212. message: '成功添加一条数据',
    213. type: 'success'
    214. });
    215. }
    216. })
    217. },
    218. // 修改数据
    219. updateBrand() {
    220. //console.log(this.brand);可以获取完整数据
    221. //发送Ajax请求,发送json数据
    222. //var _this = this;
    223. axios({
    224. method: "post",
    225. url: "http://localhost:8080/brand-case/brand/update",
    226. data: this.brand
    227. }).then(resp => {
    228. if (resp.data == "success") {
    229. //录入成功,关闭窗口,并且重新查询数据
    230. this.updateDialogVisible = false;
    231. this.selectAll();
    232. this.$message({
    233. message: '成功添加一条数据',
    234. type: 'success'
    235. });
    236. }
    237. })
    238. },
    239. //执行修改的onclick
    240. startUpdate(row) {
    241. // 获取改行已经有的数据,以供填入修改框
    242. // var _this = this
    243. this.brand = JSON.parse(JSON.stringify(row));
    244. // 弹出修改框
    245. this.updateDialogVisible = true;
    246. },
    247. //打开删除的提示框,并根据提示进行操作
    248. open(row) {
    249. this.brand = JSON.parse(JSON.stringify(row));
    250. //var _this = this;
    251. this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    252. confirmButtonText: '确定',
    253. cancelButtonText: '取消',
    254. type: 'warning'
    255. }).then(() => { //确认之后执行axios请求
    256. axios({
    257. method: "post",
    258. url: "http://localhost:8080/brand-case/brand/deleteById",
    259. data: this.brand
    260. }).then(resp => {
    261. if (resp.data == "success") {
    262. //录入成功,关闭窗口,并且重新查询数据
    263. this.selectAll();
    264. this.$message({
    265. message: '删除成功',
    266. type: 'success'
    267. });
    268. }
    269. })
    270. }).catch(() => { //取消之后执行标签
    271. this.$message({
    272. type: 'info',
    273. message: '已取消删除'
    274. });
    275. });
    276. },
    277. //批量删除的单击事件
    278. deleteByIds() {
    279. //console.log(this.multipleSelection);
    280. //1.创建id数组[1,2,3],从multipleSelection模型里面来的数据
    281. for (let i = 0; i < this.multipleSelection.length; i++) {
    282. let element = this.multipleSelection[i];
    283. //获取遍历后得到id值
    284. this.selectByIds[i] = element.id;
    285. }
    286. //var _this = this;
    287. this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    288. confirmButtonText: '确定',
    289. cancelButtonText: '取消',
    290. type: 'warning'
    291. }).then(() => {
    292. axios({
    293. method: "post",
    294. url: "http://localhost:8080/brand-case/brand/deleteByIds",
    295. data: this.selectByIds
    296. }).then(resp => {
    297. if (resp.data == "success") {
    298. //录入成功,关闭窗口,并且重新查询数据
    299. this.selectAll();
    300. this.$message({
    301. message: '成功删除数据',
    302. type: 'success'
    303. });
    304. }else{
    305. this.$message({
    306. message: '没有数据可以删除',
    307. type: 'info'
    308. });
    309. }
    310. })
    311. }).catch(() => {
    312. this.$message({
    313. type: 'info',
    314. message: '已取消删除'
    315. });
    316. });
    317. },
    318. //
    319. // 查询方法
    320. onSubmit() {
    321. //console.log(this.brand);
    322. this.selectAll();
    323. },
    324. //每页显示条数
    325. handleSizeChange(val) {
    326. //console.log(`每页 ${val} 条`);
    327. //重新设置当每页显示的条数
    328. this.pageSize = val;
    329. this.selectAll();
    330. },
    331. //当前页码
    332. handleCurrentChange(val) {
    333. //console.log(`当前页: ${val}`);
    334. //重新去设置当前页码,动态改变
    335. this.currentPage = val;
    336. this.selectAll();
    337. }
    338. },
    339. data() {
    340. return {
    341. pageSize: 5,
    342. //页码的总记录数
    343. totalCount: 100,
    344. // 当前页码
    345. currentPage: 1,
    346. // 添加数据对话框是否展示的标记
    347. dialogVisible: false,
    348. updateDialogVisible: false,
    349. // 品牌模型数据
    350. brand: {
    351. status: '',
    352. brandName: '',
    353. companyName: '',
    354. id: '',
    355. ordered: "",
    356. description: ""
    357. },
    358. //被选中的id数组
    359. selectByIds: [],
    360. // 复选框选中数据集合
    361. multipleSelection: [],
    362. // 表格数据
    363. tableData: [{
    364. brandName: '华为',
    365. companyName: '华为科技有限公司',
    366. ordered: '100',
    367. status: "1"
    368. }, {
    369. brandName: '华为',
    370. companyName: '华为科技有限公司',
    371. ordered: '100',
    372. status: "1"
    373. }, {
    374. brandName: '华为',
    375. companyName: '华为科技有限公司',
    376. ordered: '100',
    377. status: "1"
    378. }, {
    379. brandName: '华为',
    380. companyName: '华为科技有限公司',
    381. ordered: '100',
    382. status: "1"
    383. }]
    384. }
    385. }
    386. })
    387. script>
    388. body>
    389. html>

    15.pom.xml Maven配置文件

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <groupId>org.examplegroupId>
    7. <artifactId>brand-caseartifactId>
    8. <version>1.0-SNAPSHOTversion>
    9. <properties>
    10. <maven.compiler.source>18maven.compiler.source>
    11. <maven.compiler.target>18maven.compiler.target>
    12. properties>
    13. <packaging>warpackaging>
    14. <build>
    15. <plugins>
    16. <plugin>
    17. <groupId>org.apache.tomcat.mavengroupId>
    18. <artifactId>tomcat7-maven-pluginartifactId>
    19. <version>2.2version>
    20. plugin>
    21. <plugin>
    22. <groupId>org.apache.maven.pluginsgroupId>
    23. <artifactId>maven-compiler-pluginartifactId>
    24. <configuration>
    25. <source>17source>
    26. <target>17target>
    27. configuration>
    28. plugin>
    29. plugins>
    30. build>
    31. <dependencies>
    32. <dependency>
    33. <groupId>javax.servletgroupId>
    34. <artifactId>javax.servlet-apiartifactId>
    35. <version>3.1.0version>
    36. <scope>providedscope>
    37. dependency>
    38. <dependency>
    39. <groupId>commons-iogroupId>
    40. <artifactId>commons-ioartifactId>
    41. <version>2.6version>
    42. dependency>
    43. <dependency>
    44. <groupId>org.mybatisgroupId>
    45. <artifactId>mybatisartifactId>
    46. <version>3.5.5version>
    47. dependency>
    48. <dependency>
    49. <groupId>mysqlgroupId>
    50. <artifactId>mysql-connector-javaartifactId>
    51. <version>8.0.29version>
    52. dependency>
    53. <dependency>
    54. <groupId>junitgroupId>
    55. <artifactId>junitartifactId>
    56. <version>4.13.2version>
    57. <scope>Testscope>
    58. dependency>
    59. <dependency>
    60. <groupId>org.slf4jgroupId>
    61. <artifactId>slf4j-apiartifactId>
    62. <version>1.7.36version>
    63. dependency>
    64. <dependency>
    65. <groupId>ch.qos.logbackgroupId>
    66. <artifactId>logback-classicartifactId>
    67. <version>1.2.3version>
    68. dependency>
    69. <dependency>
    70. <groupId>ch.qos.logbackgroupId>
    71. <artifactId>logback-coreartifactId>
    72. <version>1.2.3version>
    73. dependency>
    74. <dependency>
    75. <groupId>jstlgroupId>
    76. <artifactId>jstlartifactId>
    77. <version>1.2version>
    78. dependency>
    79. <dependency>
    80. <groupId>taglibsgroupId>
    81. <artifactId>standardartifactId>
    82. <version>1.1.2version>
    83. dependency>
    84. <dependency>
    85. <groupId>com.alibabagroupId>
    86. <artifactId>fastjsonartifactId>
    87. <version>1.2.62version>
    88. dependency>
    89. dependencies>
    90. project>

     16.mysql数据库文件

    1. -- 删除tb_brand表
    2. drop table if exists tb_brand;
    3. -- 创建tb_brand表
    4. create table tb_brand
    5. (
    6. -- id 主键
    7. id int primary key auto_increment,
    8. -- 品牌名称
    9. brand_name varchar(20),
    10. -- 企业名称
    11. company_name varchar(20),
    12. -- 排序字段
    13. ordered int,
    14. -- 描述信息
    15. description varchar(100),
    16. -- 状态:0:禁用 1:启用
    17. status int
    18. );
    19. -- 添加数据
    20. insert into tb_brand (brand_name, company_name, ordered, description, status)
    21. values
    22. ('华为', '华为技术有限公司', 100, '万物互联', 1),
    23. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    24. ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
    25. ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
    26. ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
    27. ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
    28. ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
    29. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    30. ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
    31. ('华为', '华为技术有限公司', 100, '万物互联', 1),
    32. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    33. ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
    34. ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
    35. ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
    36. ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
    37. ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
    38. ('华为', '华为技术有限公司', 100, '万物互联', 1),
    39. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    40. ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
    41. ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
    42. ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
    43. ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
    44. ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
    45. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    46. ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
    47. ('华为', '华为技术有限公司', 100, '万物互联', 1),
    48. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    49. ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
    50. ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
    51. ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
    52. ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
    53. ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
    54. ('华为', '华为技术有限公司', 100, '万物互联', 1),
    55. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    56. ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
    57. ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
    58. ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
    59. ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
    60. ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
    61. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    62. ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
    63. ('华为', '华为技术有限公司', 100, '万物互联', 1),
    64. ('小米', '小米科技有限公司', 50, 'are you ok', 1),
    65. ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
    66. ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
    67. ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
    68. ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
    69. ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1)
    70. ;
    71. SELECT * FROM tb_brand;

    16.成品效果 

     

     

     

  • 相关阅读:
    缓存综合项目--秒杀架构
    手把手教你如何Vue项目打包dist文件并Tomcat发布【超级详细】
    老司机 - 今天去加油
    外贸人如何快速学好英语
    从零开始学习 Java:简单易懂的入门指南之IO字符流(三十一)
    文件混淆-界面介绍
    OPC C#连接OPC C#上位机链接PLC程序源码
    工控网络协议模糊测试:用peach对modbus协议进行模糊测试
    vue cli 打包、生产环境http-proxy-middleware代理
    的修大数据管理平台有哪些功能模块?它可以为企业带来什么好处?
  • 原文地址:https://blog.csdn.net/qq_51272114/article/details/127039314