• JavaWeb + Ajax + HTML 添加数据数据与查询数据,(利用axios响应与json数据传输)


    目录

    1.文件结构 

     2.BrandMaper接口

    3.Brand实体类

    4.BrandService

    5.SqlSessionFactoryUtils工具类

    6.AddServlet添加Servlet类

    7.SelectAllServlet查询Serrvlet类

    8.BrandMapper.xml映射文件

    9.mybatis-config.xml

    10.js包下axios-0.18.0.js

    11.AddBrand.html(简单方法,比较low)

    12.AddBrand2.html(稍微的复杂方法,推荐)

    13.Brand.html

    14.pom.xml(maven依赖)

    15.总结:

    1.后台代码比较简单,所以不过多进行叙述(想要了解,请看我之前发的文章)

    2.前台代码出现了一个问题,是利用json还是js的对象格式进行发送,我本来是以为直接把数据封装到一个json之中就可以了,但是后台我在获取请求行的数据的时候出现了乱码,我原以为是编码的问题,然后经过高人指点发现,发现其实我需要的是js对象,并且经过实验之后,成功了,这个问题我现在都还有写迷糊,也许要等等过些时间缓过来之后就好了。


    JavaWeb + Ajax + HTML +Vue 添加数据数据与查询数据(Vue小节 案例)_我的猴子的博客-CSDN博客

     (这篇文章是加上了Vue,用来简化原生js获取数据的麻烦问题)

    1.文件结构 

     2.BrandMaper接口

    1. package com.itheima.mapper;
    2. import com.itheima.pojo.Brand;
    3. import org.apache.ibatis.annotations.Insert;
    4. import org.apache.ibatis.annotations.ResultMap;
    5. import org.apache.ibatis.annotations.Select;
    6. import org.apache.ibatis.annotations.Update;
    7. import java.util.List;
    8. public interface BrandMapper {
    9. /**
    10. * 查询所有
    11. * @return
    12. */
    13. @Select("select * from tb_brand")
    14. @ResultMap("brandResultMap")
    15. List selectAll();
    16. @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    17. void add(Brand brand);
    18. /**
    19. * 根据id查询
    20. * @param id
    21. * @return
    22. */
    23. @Select("select * from tb_brand where id = #{id}")
    24. @ResultMap("brandResultMap")
    25. Brand selectById(int id);
    26. /**
    27. * 修改
    28. * @param brand
    29. */
    30. @Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id = #{id}")
    31. void update(Brand brand);
    32. }

    3.Brand实体类

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

    4.BrandService

    1. package com.itheima.service;
    2. import com.itheima.mapper.BrandMapper;
    3. import com.itheima.pojo.Brand;
    4. import com.itheima.util.SqlSessionFactoryUtils;
    5. import org.apache.ibatis.session.SqlSession;
    6. import org.apache.ibatis.session.SqlSessionFactory;
    7. import java.util.List;
    8. public class BrandService {
    9. SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    10. /**
    11. * 查询所有
    12. * @return
    13. */
    14. public List selectAll(){
    15. //调用BrandMapper.selectAll()
    16. //2. 获取SqlSession
    17. SqlSession sqlSession = factory.openSession();
    18. //3. 获取BrandMapper
    19. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    20. //4. 调用方法
    21. List brands = mapper.selectAll();
    22. sqlSession.close();
    23. return brands;
    24. }
    25. /**
    26. * 添加
    27. * @param brand
    28. */
    29. public void add(Brand brand){
    30. //2. 获取SqlSession
    31. SqlSession sqlSession = factory.openSession();
    32. //3. 获取BrandMapper
    33. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    34. //4. 调用方法
    35. mapper.add(brand);
    36. //提交事务
    37. sqlSession.commit();
    38. //释放资源
    39. sqlSession.close();
    40. }
    41. /**
    42. * 根据id查询
    43. * @return
    44. */
    45. public Brand selectById(int id){
    46. //调用BrandMapper.selectAll()
    47. //2. 获取SqlSession
    48. SqlSession sqlSession = factory.openSession();
    49. //3. 获取BrandMapper
    50. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    51. //4. 调用方法
    52. Brand brand = mapper.selectById(id);
    53. sqlSession.close();
    54. return brand;
    55. }
    56. /**
    57. * 修改
    58. * @param brand
    59. */
    60. public void update(Brand brand){
    61. //2. 获取SqlSession
    62. SqlSession sqlSession = factory.openSession();
    63. //3. 获取BrandMapper
    64. BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    65. //4. 调用方法
    66. mapper.update(brand);
    67. //提交事务
    68. sqlSession.commit();
    69. //释放资源
    70. sqlSession.close();
    71. }
    72. }

    5.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. }

    6.AddServlet添加Servlet类

    1. package com.itheima.web;
    2. import com.alibaba.fastjson.JSON;
    3. import com.alibaba.fastjson.JSONObject;
    4. import com.itheima.pojo.Brand;
    5. import com.itheima.service.BrandService;
    6. import javax.servlet.*;
    7. import javax.servlet.http.*;
    8. import javax.servlet.annotation.*;
    9. import java.io.BufferedReader;
    10. import java.io.IOException;
    11. import java.util.List;
    12. @WebServlet("/addServlet")
    13. public class AddServlet extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16. //1.获取请求行数据
    17. BufferedReader reader = request.getReader();
    18. //2.读取请求行数据
    19. String s = reader.readLine();
    20. //3.把json格式转为java
    21. Brand brand = JSONObject.parseObject(s,Brand.class);
    22. //4.调用service方法,并且传入数据
    23. BrandService service = new BrandService();
    24. service.add(brand);
    25. //5.相应成功后的数据
    26. response.getWriter().write("success");
    27. System.out.println(brand);
    28. System.out.println(s);
    29. }
    30. @Override
    31. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    32. this.doGet(request, response);
    33. }
    34. }

    7.SelectAllServlet查询Serrvlet类

    1. package com.itheima.web;
    2. import com.alibaba.fastjson.JSON;
    3. import com.itheima.pojo.Brand;
    4. import com.itheima.service.BrandService;
    5. import javax.servlet.*;
    6. import javax.servlet.http.*;
    7. import javax.servlet.annotation.*;
    8. import java.io.IOException;
    9. import java.util.List;
    10. @WebServlet("/selectAllServlet")
    11. public class SelectAllServlet extends HttpServlet {
    12. @Override
    13. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    14. //1.创建service对象,
    15. BrandService service = new BrandService();
    16. //2.进行调用方法查询
    17. List brands = service.selectAll();
    18. //3.将查询后的集合转为json的数据
    19. String s = JSON.toJSONString(brands);
    20. //4.相应到对应的页面上(由于此集合中的数据有中文(即从数据库查询出的数据包含有中文,所以要进行转码操作))
    21. response.setContentType("text/json;charset=utf-8");
    22. response.getWriter().write(s);
    23. }
    24. @Override
    25. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    26. this.doGet(request, response);
    27. }
    28. }

    8.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 column="brand_name" property="brandName">result>
    8. <result column="company_name" property="companyName">result>
    9. resultMap>
    10. mapper>

    9.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&useServerPrepStmts=true"/>
    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>

    10.js包下axios-0.18.0.js

    1. /* axios v0.18.0 | (c) 2018 by Matt Zabriskie */
    2. !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function r(e){var t=new s(e),n=i(s.prototype.request,t);return o.extend(n,s.prototype,t),o.extend(n,t),n}var o=n(2),i=n(3),s=n(5),u=n(6),a=r(u);a.Axios=s,a.create=function(e){return r(o.merge(u,e))},a.Cancel=n(23),a.CancelToken=n(24),a.isCancel=n(20),a.all=function(e){return Promise.all(e)},a.spread=n(25),e.exports=a,e.exports.default=a},function(e,t,n){"use strict";function r(e){return"[object Array]"===R.call(e)}function o(e){return"[object ArrayBuffer]"===R.call(e)}function i(e){return"undefined"!=typeof FormData&&e instanceof FormData}function s(e){var t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function u(e){return"string"==typeof e}function a(e){return"number"==typeof e}function c(e){return"undefined"==typeof e}function f(e){return null!==e&&"object"==typeof e}function p(e){return"[object Date]"===R.call(e)}function d(e){return"[object File]"===R.call(e)}function l(e){return"[object Blob]"===R.call(e)}function h(e){return"[object Function]"===R.call(e)}function m(e){return f(e)&&h(e.pipe)}function y(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams}function w(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function g(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function v(e,t){if(null!==e&&"undefined"!=typeof e)if("object"!=typeof e&&(e=[e]),r(e))for(var n=0,o=e.length;ncall(null,e[n],n,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}function x(){function e(e,n){"object"==typeof t[n]&&"object"==typeof e?t[n]=x(t[n],e):t[n]=e}for(var t={},n=0,r=arguments.length;nv(arguments[n],e);return t}function b(e,t,n){return v(t,function(t,r){n&&"function"==typeof t?e[r]=E(t,n):e[r]=t}),e}var E=n(3),C=n(4),R=Object.prototype.toString;e.exports={isArray:r,isArrayBuffer:o,isBuffer:C,isFormData:i,isArrayBufferView:s,isString:u,isNumber:a,isObject:f,isUndefined:c,isDate:p,isFile:d,isBlob:l,isFunction:h,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:g,forEach:v,merge:x,extend:b,trim:w}},function(e,t){"use strict";e.exports=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;rlength;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function r(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}/*!
    3. * Determine if an object is a Buffer
    4. *
    5. * @author Feross Aboukhadijeh
    6. * @license MIT
    7. */
    8. e.exports=function(e){return null!=e&&(n(e)||r(e)||!!e._isBuffer)}},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new s,response:new s}}var o=n(6),i=n(2),s=n(17),u=n(18);r.prototype.request=function(e){"string"==typeof e&&(e=i.merge({url:arguments[0]},arguments[1])),e=i.merge(o,{method:"get"},this.defaults,e),e.method=e.method.toLowerCase();var t=[u,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},i.forEach(["delete","get","head","options"],function(e){r.prototype[e]=function(t,n){return this.request(i.merge(n||{},{method:e,url:t}))}}),i.forEach(["post","put","patch"],function(e){r.prototype[e]=function(t,n,r){return this.request(i.merge(r||{},{method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){"use strict";function r(e,t){!i.isUndefined(e)&&i.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function o(){var e;return"undefined"!=typeof XMLHttpRequest?e=n(8):"undefined"!=typeof process&&(e=n(8)),e}var i=n(2),s=n(7),u={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:o(),transformRequest:[function(e,t){return s(t,"Content-Type"),i.isFormData(e)||i.isArrayBuffer(e)||i.isBuffer(e)||i.isStream(e)||i.isFile(e)||i.isBlob(e)?e:i.isArrayBufferView(e)?e.buffer:i.isURLSearchParams(e)?(r(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):i.isObject(e)?(r(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},i.forEach(["delete","get","head"],function(e){a.headers[e]={}}),i.forEach(["post","put","patch"],function(e){a.headers[e]=i.merge(u)}),e.exports=a},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){r.forEach(e,function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(2),o=n(9),i=n(12),s=n(13),u=n(14),a=n(10),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(15);e.exports=function(e){return new Promise(function(t,f){var p=e.data,d=e.headers;r.isFormData(p)&&delete d["Content-Type"];var l=new XMLHttpRequest,h="onreadystatechange",m=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in l||u(e.url)||(l=new window.XDomainRequest,h="onload",m=!0,l.onprogress=function(){},l.ontimeout=function(){}),e.auth){var y=e.auth.username||"",w=e.auth.password||"";d.Authorization="Basic "+c(y+":"+w)}if(l.open(e.method.toUpperCase(),i(e.url,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,l[h]=function(){if(l&&(4===l.readyState||m)&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in l?s(l.getAllResponseHeaders()):null,r=e.responseType&&"text"!==e.responseType?l.response:l.responseText,i={data:r,status:1223===l.status?204:l.status,statusText:1223===l.status?"No Content":l.statusText,headers:n,config:e,request:l};o(t,f,i),l=null}},l.onerror=function(){f(a("Network Error",e,null,l)),l=null},l.ontimeout=function(){f(a("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",l)),l=null},r.isStandardBrowserEnv()){var g=n(16),v=(e.withCredentials||u(e.url))&&e.xsrfCookieName?g.read(e.xsrfCookieName):void 0;v&&(d[e.xsrfHeaderName]=v)}if("setRequestHeader"in l&&r.forEach(d,function(e,t){"undefined"==typeof p&&"content-type"===t.toLowerCase()?delete d[t]:l.setRequestHeader(t,e)}),e.withCredentials&&(l.withCredentials=!0),e.responseType)try{l.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){l&&(l.abort(),f(e),l=null)}),void 0===p&&(p=null),l.send(p)})}},function(e,t,n){"use strict";var r=n(10);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";var r=n(11);e.exports=function(e,t,n,o,i){var s=new Error(e);return r(s,t,n,o,i)}},function(e,t){"use strict";e.exports=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(2);e.exports=function(e,t,n){if(!t)return e;var i;if(n)i=n(t);else if(o.isURLSearchParams(t))i=t.toString();else{var s=[];o.forEach(t,function(e,t){null!==e&&"undefined"!=typeof e&&(o.isArray(e)?t+="[]":e=[e],o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),s.push(r(t)+"="+r(e))}))}),i=s.join("&")}return i&&(e+=(e.indexOf("?")===-1?"?":"&")+i),e}},function(e,t,n){"use strict";var r=n(2),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];e.exports=function(e){var t,n,i,s={};return e?(r.forEach(e.split("\n"),function(e){if(i=e.indexOf(":"),t=r.trim(e.substr(0,i)).toLowerCase(),n=r.trim(e.substr(i+1)),t){if(s[t]&&o.indexOf(t)>=0)return;"set-cookie"===t?s[t]=(s[t]?s[t]:[]).concat([n]):s[t]=s[t]?s[t]+", "+n:n}}),s):s}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"===o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){var o=r.isString(n)?e(n):n;return o.protocol===t.protocol&&o.host===t.host}}():function(){return function(){return!0}}()},function(e,t){"use strict";function n(){this.message="String contains an invalid character"}function r(e){for(var t,r,i=String(e),s="",u=0,a=o;i.charAt(0|u)||(a="=",u%1);s+=a.charAt(63&t>>8-u%1*8)){if(r=i.charCodeAt(u+=.75),r>255)throw new n;t=t<<8|r}return s}var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";n.prototype=new Error,n.prototype.code=5,n.prototype.name="InvalidCharacterError",e.exports=r},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){return{write:function(e,t,n,o,i,s){var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(i)&&u.push("domain="+i),s===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(2);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var o=n(2),i=n(19),s=n(20),u=n(6),a=n(21),c=n(22);e.exports=function(e){r(e),e.baseURL&&!a(e.url)&&(e.url=c(e.baseURL,e.url)),e.headers=e.headers||{},e.data=i(e.data,e.headers,e.transformRequest),e.headers=o.merge(e.headers.common||{},e.headers[e.method]||{},e.headers||{}),o.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]});var t=e.adapter||u.adapter;return t(e).then(function(t){return r(e),t.data=i(t.data,t.headers,e.transformResponse),t},function(t){return s(t)||(r(e),t&&t.response&&(t.response.data=i(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t){"use strict";function n(e){this.message=e}n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new o(e),t(n.reason))})}var o=n(23);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e,t=new r(function(t){e=t});return{token:t,cancel:e}},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])});
    9. //# sourceMappingURL=axios.min.map

    11.AddBrand.html(简单方法,比较low)

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>添加品牌title>
    6. head>
    7. <body>
    8. <h3>添加品牌h3>
    9. <form id="brand" action="" method="post">
    10. 品牌名称:<input id="brandName" name="brandName"><br>
    11. 企业名称:<input id="companyName" name="companyName"><br>
    12. 排序:<input id="ordered" name="ordered"><br>
    13. 描述信息:<textarea rows="5" cols="20" id="description" name="description">textarea><br>
    14. 状态:
    15. <input type="radio" name="status" value="0">禁用
    16. <input type="radio" checked="checked" name="status" value="1">启用<br>
    17. <input type="button" id="btn" value="提交" onclick="req()">
    18. form>
    19. <script src="js/axios-0.18.0.js">script>
    20. <script>
    21. function req(){
    22. //1.设置好json
    23. var jsonData = {
    24. brandName:"",
    25. companyName:"",
    26. ordered:"",
    27. description:"",
    28. status:"",
    29. };
    30. //2.获取数据
    31. let brandName = document.getElementById("brandName").value;
    32. jsonData.brandName = brandName;
    33. let companyName = document.getElementById("companyName").value;
    34. jsonData.companyName = companyName;
    35. let ordered = document.getElementById("ordered").value;
    36. jsonData.ordered = ordered;
    37. let description = document.getElementById("description").value;
    38. jsonData.description = description;
    39. let status = document.getElementsByName("status");
    40. for (let i = 0; i < status.length; i++) {
    41. if(status[i].checked){
    42. jsonData.status = status[i].value ;
    43. }
    44. }
    45. //3.发送响应
    46. axios({
    47. method:"post",
    48. url:"http://localhost:8080/brand-demo/addServlet",
    49. data:JSON.stringify(jsonData),
    50. }).then(function (resp) {
    51. if(resp.data == "success"){
    52. window.alert("录入成功");
    53. }
    54. })
    55. }
    56. script>
    57. body>
    58. html>

    12.AddBrand2.html(稍微的复杂方法,推荐)

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>添加品牌title>
    6. head>
    7. <body>
    8. <h3>添加品牌h3>
    9. <form id="brand" action="" method="post">
    10. 品牌名称:<input id="brandName" name="brandName"><br>
    11. 企业名称:<input id="companyName" name="companyName"><br>
    12. 排序:<input id="ordered" name="ordered"><br>
    13. 描述信息:<textarea rows="5" cols="20" id="description" name="description">textarea><br>
    14. 状态:
    15. <input type="radio" name="status" value="0">禁用
    16. <input type="radio" checked="checked" name="status" value="1">启用<br>
    17. <input type="button" id="btn" value="提交" onclick="req()">
    18. form>
    19. <script src="js/axios-0.18.0.js">script>
    20. <script>
    21. let getFromDate = function () {
    22. let brandList = {}
    23. return new Promise((resolve, reject) => {
    24. let formDate = document.querySelector('#brand')
    25. if ((formDate)) {
    26. resolve(formDate.elements)
    27. }
    28. reject('没有读取到表单')
    29. }).then(date => {
    30. let arr = Array.from(date)
    31. if ((!arr.length)) throw new Error('没有读到表单数据')
    32. arr.forEach((ele, index, ar) => {
    33. const {type, value, name, checked} = ele
    34. if (value == '') throw new Error(`${name}值不能为空`)
    35. if (type != 'button') {
    36. if (type == 'radio' && !checked) return
    37. Object.defineProperty(brandList, name, {
    38. value,
    39. writable: true,
    40. enumerable: true
    41. })
    42. }
    43. })
    44. return brandList
    45. }).catch(err => {
    46. alert(err)
    47. })
    48. }
    49. async function req(e) {
    50. //获取表单数据
    51. let data = await getFromDate()
    52. data = JSON.stringify(data)
    53. console.log(data)
    54. axios({
    55. method: "post",
    56. url: "http://localhost:8080/brand-demo/addServlet",
    57. data,
    58. }).then(function (resp) {
    59. console.log(resp)
    60. }, err => {
    61. alert(err.message)
    62. })
    63. }
    64. script>
    65. body>
    66. html>

    13.Brand.html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. head>
    7. <body>
    8. <a href="addBrand.html"><input type="button" value="新增">a><br>
    9. <hr>
    10. <table id="brandTable" border="1" cellspacing="0" width="100%">
    11. <tr>
    12. <th>序号th>
    13. <th>品牌名称th>
    14. <th>企业名称th>
    15. <th>排序th>
    16. <th>品牌介绍th>
    17. <th>状态th>
    18. <th>操作th>
    19. tr>
    20. <tr align="center">
    21. <td>1td>
    22. <td>三只松鼠td>
    23. <td>三只松鼠td>
    24. <td>100td>
    25. <td>三只松鼠,好吃不上火td>
    26. <td>启用td>
    27. <td><a href="#">修改a> <a href="#">删除a>td>
    28. tr>
    29. <tr align="center">
    30. <td>2td>
    31. <td>优衣库td>
    32. <td>优衣库td>
    33. <td>10td>
    34. <td>优衣库,服适人生td>
    35. <td>禁用td>
    36. <td><a href="#">修改a> <a href="#">删除a>td>
    37. tr>
    38. <tr align="center">
    39. <td>3td>
    40. <td>小米td>
    41. <td>小米科技有限公司td>
    42. <td>1000td>
    43. <td>为发烧而生td>
    44. <td>启用td>
    45. <td><a href="#">修改a> <a href="#">删除a>td>
    46. tr>
    47. table>
    48. <script src="js/axios-0.18.0.js">script>
    49. <script>
    50. //1.当页面加载完成后,发送ajax请求
    51. window.onload = function (){
    52. //2.发送ajax请求
    53. axios({
    54. method:"get",
    55. url:"http://localhost:8080/brand-demo/selectAllServlet"
    56. }).then(function (resp) {
    57. //获取数据(servlect中获取数据之后的值返回一个集合brands,在axios中是以resp.data方式存在)
    58. let brands = resp.data;
    59. let tableData = " \n" +
    60. " 序号\n" +
    61. " 品牌名称\n" +
    62. " 企业名称\n" +
    63. " 排序\n" +
    64. " 品牌介绍\n" +
    65. " 状态\n" +
    66. " 操作\n" +
    67. " ";
    68. //遍历集合,也就是js的数组
    69. for (let i = 0; i < brands.length; i++) {
    70. let brand = brands[i];
    71. //把已经遍历出来的brand放到表格之中去
    72. tableData +=" \n" +
    73. " "+(i+1)+"\n" +
    74. " "+brand.brandName+"\n" +
    75. " "+brand.companyName+"\n" +
    76. " "+brand.ordered+"\n" +
    77. " "+brand.description+"\n" +
    78. " "+brand.status+"\n" +
    79. "\n" +
    80. " 修改 删除\n" +
    81. " ";
    82. }
    83. //设置表格的数据
    84. document.getElementById("brandTable").innerHTML = tableData;
    85. })
    86. }
    87. script>
    88. body>
    89. html>

    14.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-demoartifactId>
    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>

    15.总结:

    1.后台代码比较简单,所以不过多进行叙述(想要了解,请看我之前发的文章)

    2.前台代码出现了一个问题,是利用json还是js的对象格式进行发送,我本来是以为直接把数据封装到一个json之中就可以了,但是后台我在获取请求行的数据的时候出现了乱码,我原以为是编码的问题,然后经过高人指点发现,发现其实我需要的是js对象,并且经过实验之后,成功了,这个问题我现在都还有写迷糊,也许要等等过些时间缓过来之后就好了。

  • 相关阅读:
    web前端期末大作业——仿小米商城电商平台(6页) html+css+javascript网页设计实例 企业网站制作
    面试官:Dubbo一次RPC请求经历哪些环节?
    Vue3 中的 CSS 功能
    Uniapp小程序 时间段选择限制(开始时间 结束时间相互限制)
    类和对象(一)this指针详解
    王道并查集代码
    深入浅出Spring(24)
    django中视图函数的FBV和CBV
    torch.nn.utils.rnn下面pack_padded_sequence和pad_packed_sequence方法
    分库分表_02 Mycat入门
  • 原文地址:https://blog.csdn.net/qq_51272114/article/details/126802843