新建javaweb项目,在pom.xml引入以下依赖
| <?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>javaweb</artifactId> |
| <version>1.0-SNAPSHOT</version> |
| |
| <properties> |
| <maven.compiler.source>8</maven.compiler.source> |
| <maven.compiler.target>8</maven.compiler.target> |
| </properties> |
| <dependencies> |
| <dependency> |
| <groupId>org.projectlombok</groupId> |
| <artifactId>lombok</artifactId> |
| <version>1.18.24</version> |
| </dependency> |
| <dependency> |
| <groupId>org.mybatis</groupId> |
| <artifactId>mybatis</artifactId> |
| <version>3.4.6</version> |
| </dependency> |
| <dependency> |
| <groupId>mysql</groupId> |
| <artifactId>mysql-connector-java</artifactId> |
| <version>8.0.11</version> |
| </dependency> |
| <dependency> |
| <groupId>javax.servlet</groupId> |
| <artifactId>javax.servlet-api</artifactId> |
| <version>3.1.0</version> |
| <scope>provided</scope> |
| </dependency> |
| <dependency> |
| <groupId>javax.servlet.jsp</groupId> |
| <artifactId>jsp-api</artifactId> |
| <version>2.2</version> |
| <scope>provided</scope> |
| </dependency> |
| <dependency> |
| <groupId>javax.servlet</groupId> |
| <artifactId>jstl</artifactId> |
| <version>1.2</version> |
| </dependency> |
| <dependency> |
| <groupId>taglibs</groupId> |
| <artifactId>standard</artifactId> |
| <version>1.1.2</version> |
| </dependency> |
| <dependency> |
| <groupId>org.apache.tomcat.embed</groupId> |
| <artifactId>tomcat-embed-core</artifactId> |
| <version>9.0.37</version> |
| </dependency> |
| |
| <dependency> |
| <groupId>com.alibaba</groupId> |
| <artifactId>fastjson</artifactId> |
| <version>1.2.62</version> |
| </dependency> |
| </dependencies> |
| </project> |
复制
配置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.sjm.pojo"/> |
| </typeAliases> |
| |
| <environments default="development"> |
| <environment id="development"> |
| <transactionManager type="JDBC"/> |
| <dataSource type="POOLED"> |
| <property name="driver" value="com.mysql.cj.jdbc.Driver"/> |
| <property name="url" |
| value="jdbc:mysql://localhost:3306/gk2022?useUnicode=true&allowPublicKeyRetrieval=true&characterEncoding=utf-8&serverTimezone=GMT&useSSL=false"/> |
| <property name="username" value="root"/> |
| <property name="password" value="123456"/> |
| </dataSource> |
| </environment> |
| </environments> |
| <mappers> <!--加载sql映射文件--> |
| <!-- <mapper resource="com/zr/mapper/UserMapper.xml"/>--> |
| <!-- 包扫描--> |
| <package name="com.sjm.mapper"/> |
| </mappers> |
| </configuration> |
| |
| |
复制
因为使用代理的原因下面的路径要一致,否则会报错

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.sjm.mapper.BrandMapper"> |
| |
| <select id="selectAll" resultType="com.sjm.pojo.Brand"> |
| select * from brand |
| </select> |
| </mapper> |
复制
com.sjm.mapper下新建接口BrandMapper
| package com.sjm.mapper; |
| |
| import com.sjm.pojo.Brand; |
| import com.sjm.pojo.User; |
| import org.apache.ibatis.annotations.*; |
| |
| import java.util.List; |
| |
| public interface BrandMapper { |
| |
| |
| List<Brand> selectAll(); |
| |
| |
| @Insert("insert into brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})") |
| int add(Brand brand); |
| |
| |
| @Select("select * from brand where id=#{id}") |
| Brand selectById(int id); |
| |
| |
| @Update("update brand set brandName=#{brandName},companyName=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id}") |
| int update(Brand brand); |
| |
| |
| @Delete("delete from brand where id=#{id}") |
| int deleteById(int id); |
| } |
| |
复制
工具类
| 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; |
| } |
| } |
复制
BrandService类
| package com.sjm.service; |
| |
| import com.sjm.mapper.BrandMapper; |
| import com.sjm.pojo.Brand; |
| import com.sjm.pojo.User; |
| import com.sjm.utils.SqlSessionFactoryUtils; |
| import org.apache.ibatis.session.SqlSession; |
| import org.apache.ibatis.session.SqlSessionFactory; |
| |
| import java.util.List; |
| |
| public class BrandService { |
| SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); |
| |
| |
| public List<Brand> selectAll() { |
| |
| |
| SqlSession sqlSession = factory.openSession(); |
| |
| BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); |
| |
| List<Brand> usersList = mapper.selectAll(); |
| sqlSession.close(); |
| return usersList; |
| } |
| |
| |
| public int add(Brand brand) { |
| |
| SqlSession sqlSession = factory.openSession(); |
| |
| BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); |
| |
| int i = mapper.add(brand); |
| |
| sqlSession.commit(); |
| |
| sqlSession.close(); |
| return i; |
| } |
| |
| |
| |
| public Brand selectById(int id) { |
| |
| |
| SqlSession sqlSession = factory.openSession(); |
| |
| BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); |
| |
| Brand brand = mapper.selectById(id); |
| sqlSession.close(); |
| return brand; |
| } |
| |
| |
| public int update(Brand brand) { |
| |
| SqlSession sqlSession = factory.openSession(); |
| |
| BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); |
| |
| int update = mapper.update(brand); |
| |
| sqlSession.commit(); |
| |
| sqlSession.close(); |
| return update; |
| } |
| |
| |
| public int delete(int id) { |
| |
| SqlSession sqlSession = factory.openSession(); |
| |
| BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); |
| |
| int i = mapper.deleteById(id); |
| |
| sqlSession.commit(); |
| |
| sqlSession.close(); |
| |
| return i; |
| } |
| |
| } |
| |
复制
实体类
| @Data |
| public class Brand { |
| private Integer id; |
| |
| private String brandName; |
| |
| |
| private String companyName; |
| |
| private Integer ordered; |
| |
| private String description; |
| |
| private Integer status; |
| public Brand(){ |
| |
| } |
| } |
复制
配置过滤器
| package com.sjm.filter; |
| |
| import javax.servlet.*; |
| import javax.servlet.annotation.WebFilter; |
| import javax.servlet.annotation.WebServlet; |
| import javax.servlet.http.HttpServlet; |
| import javax.servlet.http.HttpServletRequest; |
| import javax.servlet.http.HttpSession; |
| |
| import java.io.IOException; |
| @WebFilter("/*") |
| public class FilterA implements Filter { |
| @Override |
| public void init(FilterConfig filterConfig) throws ServletException { |
| |
| } |
| |
| @Override |
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { |
| HttpServletRequest req = (HttpServletRequest) request; |
| HttpSession session = req.getSession(); |
| Object user_session = session.getAttribute("USER_SESSION"); |
| |
| |
| String[] urls = |
| {"/login.jsp","/register.jsp","/imgs","/css/", |
| "/login","/register","/loginOut","/AjaxTest","/index.html","/allBrand","/addBrand","/delete","/selectById","/update"}; |
| String url= req.getRequestURI(); |
| for (String u:urls |
| ) { |
| if(url.contains(u)){ |
| |
| chain.doFilter(request, response); |
| |
| return; |
| } |
| } |
| if(user_session != null){ |
| |
| chain.doFilter(request,response); |
| }else { |
| req.getRequestDispatcher("/login.jsp").forward(req, response); |
| } |
| } |
| |
| @Override |
| public void destroy() { |
| |
| } |
| } |
| |
复制
处理跨域问题
| |
| @WebFilter(filterName = "CorsFilter",value = "/*") |
| public class CorsFilter implements Filter { |
| public void init(FilterConfig config) throws ServletException { |
| } |
| |
| public void destroy() { |
| } |
| |
| @Override |
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { |
| HttpServletResponse response1= (HttpServletResponse) response; |
| response1.setHeader("Access-Control-Allow-Origin", "*"); |
| response1.setHeader("Access-Control-Allow-Headers", "*"); |
| |
| chain.doFilter(request, response); |
| } |
| } |
| |
复制
在web.xml中配置
| <welcome-file-list> |
| <welcome-file>/login.jsp</welcome-file> |
| </welcome-file-list> |
| <!--跨域过滤器--> |
| <filter> |
| <filter-name>CORS</filter-name> |
| <filter-class>com.sjm.filter.CorsFilter</filter-class> |
| <init-param> |
| <param-name>cors.allowOrigin</param-name> |
| <param-value>*</param-value> |
| </init-param> |
| <init-param> |
| <param-name>cors.supportedMethods</param-name> |
| <param-value>GET, POST, HEAD, PUT, DELETE</param-value> |
| </init-param> |
| <init-param> |
| <param-name>cors.supportedHeaders</param-name> |
| <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value> |
| </init-param> |
| <init-param> |
| <param-name>cors.exposedHeaders</param-name> |
| <param-value>Set-Cookie</param-value> |
| </init-param> |
| <init-param> |
| <param-name>cors.supportsCredentials</param-name> |
| <param-value>true</param-value> |
| </init-param> |
| </filter> |
| <filter-mapping> |
| <filter-name>CORS</filter-name> |
| <url-pattern> |
| |
| |
复制
添加接口
| @WebServlet("/addBrand") |
| public class addController extends HttpServlet { |
| private BrandService service = new BrandService(); |
| |
| @Override |
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| |
| request.setCharacterEncoding("UTF-8"); |
| response.setContentType("text/json;charset=utf-8"); |
| BufferedReader reader = request.getReader(); |
| String brand_string = reader.readLine(); |
| System.out.println(brand_string); |
| if (brand_string != null){ |
| |
| Brand brand = JSON.parseObject(brand_string, Brand.class); |
| |
| int add = service.add(brand); |
| if (add > 0) { |
| response.getWriter().write(JSON.toJSONString("success")); |
| } else { |
| response.getWriter().write(JSON.toJSONString("fail")); |
| } |
| }else { |
| response.getWriter().write(JSON.toJSONString("fail")); |
| } |
| |
| |
| } |
| |
| @Override |
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| |
| this.doGet(request, response); |
| } |
| } |
复制
删除接口
| |
| @WebServlet("/delete") |
| public class DeleteServlet extends HttpServlet { |
| |
| private BrandService service = new BrandService(); |
| |
| @Override |
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException { |
| |
| |
| request.setCharacterEncoding("utf-8"); |
| response.setContentType("text/json;charset=utf-8"); |
| |
| String id = request.getParameter("id"); |
| Map<String, Object> map = new HashMap<>(); |
| |
| int delete = service.delete(Integer.parseInt(id)); |
| if (delete > 0) { |
| map.put("status",200); |
| map.put("msg", "delete success"); |
| } else { |
| map.put("status",201); |
| map.put("msg", "delete fail"); |
| } |
| response.getWriter().write(JSON.toJSONString(map)); |
| } |
| |
| @Override |
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| this.doGet(request, response); |
| } |
| } |
复制
查询所有接口
| @WebServlet("/allBrand") |
| public class selectAllBrand extends HttpServlet { |
| private BrandService service = new BrandService(); |
| |
| @Override |
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| |
| response.setContentType("text/html;charset=utf-8"); |
| List<Brand> brandList = service.selectAll(); |
| System.out.println(brandList); |
| response.getWriter().write(JSON.toJSONString(brandList)); |
| |
| } |
| |
| @Override |
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| |
| this.doGet(request, response); |
| } |
| } |
复制
根据Id查询
| |
| @WebServlet("/selectById") |
| public class SelectByIdServlet extends HttpServlet { |
| private BrandService service = new BrandService(); |
| |
| @Override |
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException { |
| |
| String id = request.getParameter("id"); |
| response.setContentType("text/html;charset=utf-8"); |
| |
| Brand brand = service.selectById(Integer.parseInt(id)); |
| response.getWriter().write(JSON.toJSONString(brand)); |
| } |
| |
| @Override |
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| this.doGet(request, response); |
| } |
| } |
| |
复制
更新记录接口
| |
| @WebServlet("/update") |
| public class updateServlet extends HttpServlet { |
| private BrandService service = new BrandService(); |
| |
| @Override |
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| |
| request.setCharacterEncoding("UTF-8"); |
| response.setContentType("text/json;charset=utf-8"); |
| BufferedReader reader = request.getReader(); |
| String brand_string = reader.readLine(); |
| System.out.println(brand_string); |
| if (brand_string != null){ |
| |
| Brand brand = JSON.parseObject(brand_string, Brand.class); |
| |
| int up = service.update(brand); |
| if (up > 0) { |
| response.getWriter().write(JSON.toJSONString("success")); |
| } else { |
| response.getWriter().write(JSON.toJSONString("fail")); |
| } |
| }else { |
| response.getWriter().write(JSON.toJSONString("fail")); |
| } |
| |
| |
| } |
| |
| @Override |
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| |
| this.doGet(request, response); |
| } |
| } |
复制
前端页面使用了axios+jquery(自行下载)
| <!DOCTYPE html> |
| <html lang="en"> |
| |
| <head> |
| <meta charset="UTF-8"> |
| <meta http-equiv="X-UA-Compatible" content="IE=edge"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>Document</title> |
| <script src="./axios-0.18.0.js"></script> |
| <script src="./jquery.min.js"></script> |
| <style> |
| #addDiv { |
| text-align: center; |
| display: none; |
| margin: 0 auto; |
| width: 400px; |
| height: 400px; |
| background: rgb(34, 227, 179); |
| } |
| |
| .updateDiv { |
| text-align: center; |
| display: none; |
| margin: 0 auto; |
| width: 400px; |
| height: 400px; |
| background: rgb(34, 227, 179); |
| } |
| </style> |
| </head> |
| |
| <body> |
| <input type="button" onclick="switchDiv(1)" value="新增"> |
| <br> |
| <!-- 查询所有 --> |
| <table id="brandTable" border="1" cellspacing="0" width="100%"></table> |
| <div id="addDiv"> |
| <h3>添加品牌</h3> |
| <form action="" method="post"> |
| 品牌名称:<input id="brandName" name="brandName"><br> |
| 企业名称:<input id="companyName" name="companyName"><br> |
| 排序:<input id="ordered" name="ordered"><br> |
| 描述信息:<textarea rows="5" cols="20" id="description" name="description"></textarea><br> |
| 状态: |
| <input type="radio" name="status" value="0" id="status">禁用 |
| <input type="radio" name="status" value="1" id="status">启用<br> |
| <input type="button" id="addbtn" value="提交"> |
| <!-- <input type="button" onclick="switchDiv(0)" value="取消"> --> |
| </form> |
| </div> |
| <div class="updateDiv"> |
| <h3>修改品牌</h3> |
| <form action="" id="updateForm" method="post"> |
| <input type="hidden" class="id" name="id"> |
| 品牌名称:<input class="brandName" name="brandName"><br> |
| 企业名称:<input class="companyName" name="companyName"><br> |
| 排序:<input class="ordered" name="ordered"><br> |
| 描述信息:<textarea rows="5" cols="20" class="description" name="description"></textarea><br> |
| 状态: |
| <input type="radio" name="status" value="0" class="status">禁用 |
| <input type="radio" name="status" value="1" class="status">启用<br> |
| <input type="button" class="up" onclick="updateBrand()" value="提交"> |
| <input type="button" class="rem" id="rmupdate" value="取消"> |
| </form> |
| </div> |
| <script> |
| const userList = () => { |
| axios({ |
| method: "get", |
| url: "http://localhost:8080/allBrand" |
| }).then(function (msg) { |
| |
| let brands = msg.data; |
| let tableData = " <tr>\n" + |
| " <th>序号</th>\n" + |
| " <th>品牌名称</th>\n" + |
| " <th>企业名称</th>\n" + |
| " <th>排序</th>\n" + |
| " <th>品牌介绍</th>\n" + |
| " <th>状态</th>\n" + |
| " <th>操作</th>\n" + |
| " </tr>"; |
| for (let i = 0; i < brands.length; i++) { |
| let brand = brands[i]; |
| tableData += "\n" + |
| " <tr align=\"center\">\n" + |
| " <td>" + (i + 1) + "</td>\n" + |
| " <td>" + brand.brandName + "</td>\n" + |
| " <td>" + brand.companyName + "</td>\n" + |
| " <td>" + brand.ordered + "</td>\n" + |
| " <td>" + brand.description + "</td>\n" + |
| " <td>" + brand.status + "</td>\n" + |
| "\n" + |
| " <td><button οnclick=" + 'selectById(' + brand.id + ')' + " >修改</button> <button οnclick=" + 'deleteBrand(' + brand.id + ')' + ">删除</button></td>\n" + |
| " </tr>"; |
| |
| } |
| |
| document.getElementById("brandTable").innerHTML = tableData; |
| }) |
| } |
| userList() |
| |
| |
| |
| |
| $('#addbtn').click(function () { |
| |
| addBrands(); |
| $("#addDiv").hide(); |
| $("#btn").show(); |
| $("table").show(); |
| |
| userList(); |
| |
| }) |
| const addBrands = () => { |
| var formData = {}; |
| formData.brandName = $("#brandName").val(); |
| formData.companyName = $("#companyName").val(); |
| formData.ordered = $("#ordered").val(); |
| formData.description = $("#description").val(); |
| formData.status = $("#status:checked").val(); |
| axios({ |
| method: "post", |
| url: "http://localhost:8080/addBrand", |
| data: JSON.stringify(formData) |
| }).then(function (res) { |
| if (res.status == 200) { |
| alert(res.data); |
| userList(); |
| } else { |
| alert(res.data) |
| } |
| }) |
| } |
| |
| |
| const deleteBrand = (id) => { |
| |
| axios({ |
| method: "get", |
| url: "http://localhost:8080/delete?id=" + id |
| }).then(function (res) { |
| if (res.data.status == 200) { |
| alert(res.data.msg); |
| |
| userList(); |
| } else if (res.data.status == 201) { |
| alert(res.data.msg); |
| } |
| }) |
| } |
| $(".rem").click(function(){ |
| $(".updateDiv").hide(); |
| $("table").show(); |
| }) |
| |
| const updateBrand = () => { |
| $(".updateDiv").hide(); |
| $("table").show(); |
| |
| let updateForm = {}; |
| updateForm.id = $(".id").val(); |
| updateForm.brandName = $(".brandName").val(); |
| updateForm.companyName = $(".companyName").val(); |
| updateForm.ordered = $(".ordered").val(); |
| updateForm.description = $(".description").val(); |
| updateForm.status = $(".status:checked").val(); |
| axios({ |
| method: "post", |
| url: "http://localhost:8080/update", |
| data: JSON.stringify(updateForm) |
| }).then(function (res) { |
| if (res.status == 200) { |
| alert(res.data); |
| userList(); |
| } else { |
| alert(res.data) |
| } |
| }) |
| } |
| |
| |
| const selectById = (id) => { |
| switchDiv(3) |
| axios({ |
| method: "get", |
| url: "http://localhost:8080/selectById?id=" + id |
| }).then(function (res) { |
| |
| var brand = res.data |
| $('#updateForm').find('input[name="id"]').val(brand.id); |
| $('#updateForm').find('input[name="brandName"]').val(brand.brandName); |
| $('#updateForm').find('input[name="companyName"]').val(brand.companyName); |
| $('#updateForm').find('input[name="ordered"]').val(brand.ordered); |
| $('#updateForm').find('textarea[name="description"]').val(brand.description); |
| $('#updateForm').find('input[name="status"][value="' + brand.status + '"]').attr('checked', 'checked') |
| }) |
| |
| } |
| |
| |
| function switchDiv(part) { |
| |
| $('#addDiv').css("display", "none") |
| $('#brandTable').css("display", "none") |
| $('#btn').css("display", "none") |
| $('.updateDiv').css("display", "none") |
| if (1 == part) { |
| $('#addDiv').css("display", "block") |
| } else if (2 == part) { |
| $('#brandTable').css("display", "block") |
| } else if (3 == part) { |
| $('.updateDiv').css("display", "block") |
| } |
| } |
| </script> |
| </body> |
| |
| </html> |
复制
最终效果

添加

修改

删除
