✨✨个人主页:沫洺的主页
📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏
📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏
📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏
💖💖如果文章对你有所帮助请留下三连✨✨
具体实现的功能包括:
- 🎐查询所有(查询所有品牌数据)
- 🎐新增品牌(增加新的品牌数据)
- 🎐修改品牌(修改品牌数据)
- 🎐删除品牌(删除品牌数据)
- 🎐批量删除(删除多条品牌数据)
- 🎐分页查询(分页展示品牌数据)
- 🎐条件查询(通过条件精确查询品牌数据)
💖💖环境搭建步骤
- 🎐创建maven Web项目,配置pom.xml文件,添加坐标依赖,配置tomcat服务器
- 🎐采用三层架构(web service mapper)的模式创建项目目录结构,工具类文件夹util,实体类文件夹pojo
- 🎐搭建MyBatis环境,创建mybatis-config.xml核心配置文件,BrandMapper.xml映射文件,BrandMapper接口
- 🎐使用navicat工具创建数据库db5,表tb_brand,添加数据,(也可使用其他工具,自定义库名,记得在mybatis核心配置文件中修改连接信息)
- 🎐webapp创建js文件夹引入vue.js和axios-0.18.0.js本地js,引入element-ui饿了么组件库
💖💖前言说明
- 🎐由于本片文章给出的主要是项目源码,在复制时不用将import导包部分一同复制,原因是如果是自定义的项目目录,导包的路径就不一致会让你重新导包,最好的方法是先创建文件,再将除了import的其他部分复制,再IDEA工具中有个自动导包的设置,会根据自己的项目目录进行导包,可以设置一下,这里的项目目录就是com/moming
💖💖IDEA工具设置自动导包
💖💖接下来开始搭建环境:
🍱创建maven Web项目
🍱配置pom.xml文件(添加坐标依赖,配置tomcat服务器)
🍚注意在tomcat配置中,端口号和虚拟目录可自定义
🍖pom.xml
"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.0modelVersion> <groupId>org.examplegroupId> <artifactId>brand-caseartifactId> <version>1.0-SNAPSHOTversion> <packaging>warpackaging> <properties> <maven.compiler.source>8maven.compiler.source> <maven.compiler.target>8maven.compiler.target> properties> <dependencies> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>3.5.5version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.49version> dependency> <dependency> <groupId>com.github.pagehelpergroupId> <artifactId>pagehelperartifactId> <version>5.1.2version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>javax.servlet-apiartifactId> <version>3.1.0version> <scope>providedscope> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.13version> dependency> <dependency> <groupId>cn.hutoolgroupId> <artifactId>hutool-allartifactId> <version>5.8.5version> dependency> <dependency> <groupId>ch.qos.logbackgroupId> <artifactId>logback-classicartifactId> <version>1.2.3version> dependency> <dependency> <groupId>ch.qos.logbackgroupId> <artifactId>logback-coreartifactId> <version>1.2.3version> dependency> <dependency> <groupId>org.projectlombokgroupId> <artifactId>lombokartifactId> <version>1.18.24version> <scope>compilescope> dependency> <dependency> <groupId>javax.servlet.jspgroupId> <artifactId>jsp-apiartifactId> <version>2.2version> <scope>providedscope> dependency> <dependency> <groupId>jstlgroupId> <artifactId>jstlartifactId> <version>1.2version> dependency> <dependency> <groupId>taglibsgroupId> <artifactId>standardartifactId> <version>1.1.2version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>5.3.2version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>fastjsonartifactId> <version>1.2.62version> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.mavengroupId> <artifactId>tomcat7-maven-pluginartifactId> <version>2.2version> <configuration> <port>8080port> <path>/momingpath> <uriEncoding>utf-8uriEncoding> configuration> plugin> plugins> build> project>🍱创建项目目录结构
🍚目录结构com/moming可自定义
🍱搭建MyBatis环境
🍚如果自定义了目录结构,那么在核心配置文件中将com.moming改为自己的结构路径
然后就是数据库连接信息配置,数据库名,账号,密码
🍖mybatis-config.xml核心配置文件
"1.0" encoding="UTF-8" ?> configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.moming.pojo"/> typeAliases> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> plugin> plugins> <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:///db5?useSSL=false&useServerPrepStmts=true&characterencoding=utf-8&allowPublicKeyRetrieval=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> dataSource> environment> environments> <mappers> <package name="com.moming.mapper"/> mappers> configuration>🍱创建BrandMapper.xml映射文件,BrandMapper接口
🍱创建数据库db5,表tb_brand,添加数据(库名可自定义,和MyBatis核心配置文件中的库名保持一致)
🍖tb_brand.sql
-- 删除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;🍱webapp配置js和element组件库
由于文件比较大,在上一篇结尾处可找到这三个文件,将element-ui解压后复制到项目中,上一篇文章可去JavaWeb专栏去找
🍖Brand
package com.moming.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor 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 String getStatusStr(){ if(status == null){ return "未知"; } return status == 0 ? "禁用" : "启用"; } }🍖PageBean
package com.moming.pojo; import lombok.Data; import java.util.List; //分页查询的JavaBean @Data public class PageBean{ // 总记录数 private int totalCount; // 当前页数据 private Listrows; }
🍖SqlSessionFactoryUtils
package com.moming.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 SqlSessionFactoryUtils() { } private static SqlSessionFactory sqlSessionFactory; static { try { //1.加载mybatis的核心配置文件,获取SqlSessionFactory //定义配置文件的路径 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; } }🍖BaseServlet
package com.moming.util; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 对tomcat来讲,都是找servlet中的service方法,因此将来定义的servlet只需要继承BaseServlet * 在BaseServlet中,重写service方法,根据url的地址值获取方法名并反射对应的方法,执行即可 */ //用来替换HttpServlet,根据请求的最后一段路径进行方法分发,代替HttpServlet根据请求方法分发 public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取请求路径 // /moming/brand/selectAll String uri = req.getRequestURI(); //2.获取最后一段路径,方法名 // /selectAll String[] arr = uri.split("/"); String methodName = arr[arr.length - 1]; //int index = uri.lastIndexOf("/"); //String methodName = uri.substring(index+1); //3.执行方法 //3.1获取BrandServlet 或者 UserServlet的字节码对象 //谁调用(this 所在的方法),(this)就代表谁 //也就是BaseServlet的子类对象 Class extends BaseServlet> cls = this.getClass(); //3.2通过反射获取方法的Method对象 try { 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(); } } }
🍖BrandMapper接口
package com.moming.mapper; import com.moming.pojo.Brand; import org.apache.ibatis.annotations.*; import java.util.List; public interface BrandMapper { //注意数据库字段名称和实体类字段名称不一致问题,可以通过开启驼峰命名支持,也可以使用resultMap映射 //如果使用resultMap需要在这里添加注解@ResultMap("brandResultMap") /** * 查询所有 * * @return */ @Select("select * from tb_brand") @ResultMap("brandResultMap") ListselectAll(); /** * 添加数据 * * @param brand */ @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})") int add(Brand brand); /** * 修改 * * @param brand * @return */ int updateBrand(Brand brand); /** * 批量删除 * * @param ids */ void deleteByIds(@Param("ids") int[] ids); /** * 单个删除 * * @param id */ @Delete("delete from tb_brand where id=#{id}") void deleteById(String id); /** * 分页查询 * * @param begin * @param size * @return */ @Select("select * from tb_brand limit #{begin} , #{size}") @ResultMap("brandResultMap") ListselectByPage(@Param("begin") int begin, @Param("size") int size); /** * 查询总记录数 * * @return */ @Select("select count(*) from tb_brand ") int selectTotalCount(); /** * 分页条件查询 * * @param begin * @param size * @return */ ListselectByPageAndCondition(@Param("begin") int begin, @Param("size") int size, @Param("brand") Brand brand); /** * 根据条件查询总记录数 * * @return */ int selectTotalCountByCondition(Brand brand); }🍚注意配置中namespace路径改为自己的
🍖BrandMapper.xml
"1.0" encoding="UTF-8" ?> mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.moming.mapper.BrandMapper"> <resultMap id="brandResultMap" type="brand"> <result column="brand_name" property="brandName">result> <result column="company_name" property="companyName">result> resultMap> <update id="updateBrand"> update tb_brand <set> <if test="brandName !=null and brandName!=''"> brand_name = #{brandName}, if> <if test="companyName !=null and companyName!=''"> company_name = #{companyName}, if> <if test="ordered !=null and ordered!=0"> ordered = #{ordered}, if> <if test="description !=null and description!=''"> description = #{description}, if> <if test="status !=null "> status = #{status} if> set> where id=#{id}; update> <delete id="deleteByIds"> delete from tb_brand where id in <foreach collection="ids" item="id" separator="," open="(" close=")"> #{id} foreach> delete> <select id="selectByPageAndCondition" resultMap="brandResultMap"> select * from tb_brand <where> <if test="brand.brandName != null and brand.brandName != '' "> and brand_name like #{brand.brandName} if> <if test="brand.companyName != null and brand.companyName != '' "> and company_name like #{brand.companyName} if> <if test="brand.status != null"> and status = #{brand.status} if> where> limit #{begin} , #{size} select> <select id="selectTotalCountByCondition" resultType="java.lang.Integer"> select count(*) from tb_brand <where> <if test="brandName != null and brandName != '' "> and brand_name like #{brandName} if> <if test="companyName != null and companyName != '' "> and company_name like #{companyName} if> <if test="status != null"> and status = #{status} if> where> select> mapper>
🍚为了方便代码维护,创建一个接口BrandService,创建impl/BrandServiceImpl实现类去实现接口
🍖BrandService接口
package com.moming.service; import com.moming.pojo.Brand; import com.moming.pojo.PageBean; import java.util.List; public interface BrandService { /** * 查询所有 * @return */ ListselectAll(); /** * 添加数据 * @param brand */ void add(Brand brand); /** * 添加或修改 * @param brand * @return */ String addOrUpdate(Brand brand); /** * 批量删除 * @param ids */ void deleteByIds(int[] ids); /** * 单个删除 * @param id */ void deleteById(String id); /** * 分页条件查询 * @param currentPage 当前页码 * @param pageSize 每页展示条数 * @return */ PageBeanselectByPage(int currentPage, int pageSize); /** * 分页条件查询 * @param currentPage * @param pageSize * @param brand * @return */ PageBeanselectByPageAndCondition(int currentPage, int pageSize,Brand brand); }🍖BrandServiceImpl
package com.moming.service.impl; import com.moming.mapper.BrandMapper; import com.moming.pojo.Brand; import com.moming.pojo.PageBean; import com.moming.service.BrandService; import com.moming.util.SqlSessionFactoryUtils; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.List; public class BrandServiceImpl implements BrandService { //1.创建SqlSessionFactory 工厂对象 SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory(); /** * 查询所有 * * @return */ @Override public ListselectAll() { //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取mapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //4.调用方法 Listbrands = mapper.selectAll(); //5.释放资源 sqlSession.close(); return brands; } /** * 添加 * * @param brand */ @Override public void add(Brand brand) { //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取mapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //4.调用方法 mapper.add(brand); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); } /** * 添加或修改 * @param brand * @return */ @Override public String addOrUpdate(Brand brand) { //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取mapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //判断brand对象中的id是否有效,如果有效,则执行修改的行为,无效则执行添加的行为 //业务层,返回1表示添加成功,2修改成功,3添加失败,4修改失败 if(brand.getId()!=null&&brand.getId()!=0){ //修改 int i = mapper.updateBrand(brand); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); if(i>=1){ return "修改成功"; }else { return "修改失败"; } }else { //添加 int i = mapper.add(brand); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); if(i>=1){ return "添加成功"; }else { return "添加失败"; } } } /** * 批量删除 * @param ids */ @Override public void deleteByIds(int[] ids) { //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取mapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //4.调用方法 mapper.deleteByIds(ids); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); } /** * 单个删除 * @param id */ @Override public void deleteById(String id) { //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取mapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //4.调用方法 mapper.deleteById(id); //提交事务 sqlSession.commit(); //5.释放资源 sqlSession.close(); } /** * 分页查询 * @param currentPage 当前页码 * @param pageSize 每页展示条数 * @return */ @Override public PageBeanselectByPage(int currentPage, int pageSize) { //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取mapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //4. 计算开始索引 int begin = (currentPage - 1) * pageSize; // 计算查询条目数 int size = pageSize; //5. 查询当前页数据 Listrows = mapper.selectByPage(begin, size); //6. 查询总记录数 int totalCount = mapper.selectTotalCount(); //7. 封装PageBean对象 PageBeanpageBean = new PageBean<>(); pageBean.setRows(rows); pageBean.setTotalCount(totalCount); //8. 释放资源 sqlSession.close(); return pageBean; } /** * 分页条件查询 * @param currentPage * @param pageSize * @param brand * @return */ @Override public PageBeanselectByPageAndCondition(int currentPage, int pageSize, Brand brand) { //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.获取mapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //4. 计算开始索引 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 + "%"); } //5. 查询当前页数据 Listrows = mapper.selectByPageAndCondition(begin, size, brand); //6. 查询总记录数 int totalCount = mapper.selectTotalCountByCondition(brand); //7. 封装PageBean对象 PageBeanpageBean = new PageBean<>(); pageBean.setRows(rows); pageBean.setTotalCount(totalCount); //8. 释放资源 sqlSession.close(); return pageBean; } }
🍖BrandServlet
package com.moming.web; import com.alibaba.fastjson.JSON; import com.moming.pojo.Brand; import com.moming.pojo.PageBean; import com.moming.service.BrandService; import com.moming.service.impl.BrandServiceImpl; import com.moming.util.BaseServlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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 { private BrandService brandService = new BrandServiceImpl(); //这个方法就是专门出来查询所有商品的方法 public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.调用service查询 Listbrands = brandService.selectAll(); //2.将list集合转换为JSON String jsonString = JSON.toJSONString(brands); //3.响应JSON数据 //设置响应编码格式 response.setContentType("text/json;charset=utf-8"); response.getWriter().write(jsonString); } //添加 public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.接收品牌数据 BufferedReader reader = request.getReader(); String params = reader.readLine(); //转为Brand对象 Brand brand = JSON.parseObject(params,Brand.class); //2.调用service添加 brandService.add(brand); //3.响应成功标识 response.getWriter().write("success"); } //添加或修改 public void addOrUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.接收品牌数据 BufferedReader reader = request.getReader(); String params = reader.readLine(); //转为Brand对象 Brand brand = JSON.parseObject(params,Brand.class); //调用service 业务层,返回1表示添加成功,2修改成功,3添加失败,4修改失败 //2.调用service添加 String msg = brandService.addOrUpdate(brand); response.setContentType("text/html;charset=utf-8"); //3.响应 response.getWriter().write(msg); } //批量删除 public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.接收数据 BufferedReader reader = request.getReader(); String params = reader.readLine(); //转为int[] int[] ids = JSON.parseObject(params, int[].class); //2.调用service添加 brandService.deleteByIds(ids); //3.响应成功标识 response.getWriter().write("success"); } //删除 public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.接收数据 String id = request.getParameter("id"); //2.调用service添加 brandService.deleteById(id); //3.响应成功标识 response.getWriter().write("success"); } /** * 分页查询 * @param request * @param response * @throws ServletException * @throws IOException */ public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 接收 当前页码 和 每页展示条数 url?currentPage=1&pageSize=5 String _currentPage = request.getParameter("currentPage"); String _pageSize = request.getParameter("pageSize"); //转换 int currentPage = Integer.parseInt(_currentPage); int pageSize = Integer.parseInt(_pageSize); //2. 调用service查询 PageBeanpageBean = brandService.selectByPage(currentPage, pageSize); //2. 转为JSON String jsonString = JSON.toJSONString(pageBean); //3. 写数据 response.setContentType("text/json;charset=utf-8"); response.getWriter().write(jsonString); } /** * 分页条件查询 * @param request * @param response * @throws ServletException * @throws IOException */ public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 接收 当前页码 和 每页展示条数 url?currentPage=1&pageSize=5 String _currentPage = request.getParameter("currentPage"); String _pageSize = request.getParameter("pageSize"); int currentPage = Integer.parseInt(_currentPage); int pageSize = Integer.parseInt(_pageSize); // 获取查询条件对象 BufferedReader br = request.getReader(); String params = br.readLine();//json字符串 //转为 Brand Brand brand = JSON.parseObject(params, Brand.class); //2. 调用service查询 PageBeanpageBean = brandService.selectByPageAndCondition(currentPage,pageSize,brand); //2. 转为JSON String jsonString = JSON.toJSONString(pageBean); //3. 写数据 response.setContentType("text/json;charset=utf-8"); response.getWriter().write(jsonString); } }
🍚在发送axios异步请求设置中url的路径要改成自己的
🍖brand.xml
html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Titletitle> <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="">el-option> <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="openDialog('新增商品')">新增el-button> el-row> <el-dialog :title="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="addOrUpdateBrand">提交el-button> <el-button @click="dialogVisible = 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="statusStr" align="center" label="当前状态"> el-table-column> <el-table-column align="center" label="操作"> <template slot-scope="scope"> <el-button @click="handleEdit(scope.$index, scope.row)">修改 el-button> <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除 el-button> 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"> el-pagination> div> <script src="js/axios-0.18.0.js">script> <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> let v = new Vue({ el: "#app", data() { return { //每页显示条数 pageSize: 5, //总记录数 totalCount: 100, //当前页码 currentPage: 1, //添加数据对话框是否展示的标记 dialogVisible: false, //对话框标题 title: '新增商品', // 品牌模型数据 brand: { status: '', brandName: '', companyName: '', id: "", ordered: "", description: "" }, //被选中的id数组 selectedIds: [], // 复选框选中数据集合 multipleSelection: [], // 表格数据,假数据 tableData: [{ id: '', brandName: '华为', companyName: '华为科技有限公司', ordered: '100', status: "1" }] } }, mounted() { this.selectAll(); }, methods: { //查询所有的方法 selectAll() { //提升生命周期 //没有发送异步请求之前,this表示vue对象,发送之后this表示window对象 // var _this=this; // //页面加载完成之后执行的函数,发送异步请求,获取JSON函数,给vue中的tableDate变量赋值 // axios({ // method: "get", // url: "http://localhost:8080/moming/brand/selectAll" // }).then(function (resp) { // _this.tableData = resp.data; // }) // //查询分页数据 // var _this=this; // //页面加载完成之后执行的函数,发送异步请求,获取JSON函数,给vue中的tableDate变量赋值 // axios({ // method: "post", // url: "http://localhost:8080/moming/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize, // data: this.brand // }).then(function (resp) { // //设置表格数据 // _this.tableData = resp.data.rows;// {rows:[],totalCount:100} // //设置总记录数 // _this.totalCount = resp.data.totalCount; // }) //查询分页数据 var _this = this; //页面加载完成之后执行的函数,发送异步请求,获取JSON函数,给vue中的tableDate变量赋值 axios({ method: "post", url: "http://localhost:8080/moming/brand/selectByPageAndCondition?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize, data: this.brand }).then(resp => { //设置表格数据 this.tableData = resp.data.rows;// {rows:[],totalCount:100} //设置总记录数 this.totalCount = resp.data.totalCount; }) }, tableRowClassName({row, rowIndex}) { if (rowIndex % 4 === 1) { return 'warning-row'; } else if (rowIndex % 4 === 3) { return 'success-row'; } return ''; }, // 复选框选中后执行的方法 handleSelectionChange(val) { this.multipleSelection = val; console.log(this.multipleSelection) }, // 提交按钮时查询方法 onSubmit() { // console.log(this.brand); this.selectAll(); }, //添加或修改数据执行方法 addOrUpdateBrand() { var _this = this; //发送ajax请求,添加数据 axios({ method: "post", url: "http://localhost:8080/moming/brand/addOrUpdate", data: _this.brand }).then(function (r) { //添加或修改成功 //提示信息 _this.$message({ message: r.data, type: 'success' }); //刷新页面,重新查询数据 _this.selectAll(); //关闭窗口 _this.dialogVisible = false; }) }, //批量删除方法 deleteByIds() { //弹出确认提示框 this.$confirm('此操作将删除该数据, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { //1.创建id数组,从this.multipleSelection获取即可 for (let i = 0; i < this.multipleSelection.length; i++) { let selectionElement = this.multipleSelection[i]; this.selectedIds[i] = selectionElement.id; } //2.发送AJAX请求 var _this = this; //发送ajax请求,添加数据 axios({ method: "post", url: "http://localhost:8080/moming/brand/deleteByIds", data: _this.selectedIds }).then(function (r) { if (r.data == "success") { //添加成功 //提示信息 _this.$message({ message: '恭喜你,删除成功', type: 'success' }); //刷新页面,重新查询数据 _this.selectAll(); } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); }, //修改按钮回显数据的方法 handleEdit(i, row) { //打开对话框(可以和添加商品的对话框公用同一个) //需要给对话框设置一个标题和回显的数据 v.dialogVisible = true; v.title = '修改商品'; v.brand = row; }, //单个删除 handleDelete(i, row) { this.$confirm('此操作将删除' + row.brandName + ', 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { //点击确定按钮会执行到这里 //发送ajax请求 //2.发送AJAX请求 var _this = this; //发送ajax请求,添加数据 axios({ method: "post", url: "http://localhost:8080/moming/brand/deleteById?id=" + row.id, }).then(function (r) { if (r.data == "success") { //删除成功 //提示信息 _this.$message({ message: '恭喜你,删除成功', type: 'success' }); //刷新页面,重新查询数据 _this.selectAll(); } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); }, //分页 handleSizeChange(val) { // console.log(`每页 ${val} 条`); //重新设置每页显示的条数 this.pageSize = val; this.selectAll(); }, handleCurrentChange(val) { // console.log(`当前页: ${val}`); //重新设置当前页码 this.currentPage = val; this.selectAll(); }, //打开添加商品对话框 openDialog(t) { v.brand = {}; v.title = t; v.dialogVisible = true; } }, }) script> body> html>
💖💖以上就是全部源代码了,可以结合我前几篇有关JavaWeb登录注册案例进行一下整合,在登录注册案例中,有个success.jsp文件,可用brand.html将其替换,然后在SuccessServlet中将转发到success.jsp改为brand.html
(request.getRequestDispatcher("/brand.html").forward(request,response);)
这样就可以实现登录成功后跳转到Brand管理系统界面
具体的登录注册案例连接如下(三篇)
代码量比较大,如果想要进一步了解的我找到了一篇大佬详解的步骤可去参考
博主:鲁棒最小二乘支持向量机 --- 黑马程序员最新版JavaWeb综合案例(前后端完整版)