前后端交互(小白教学),前后端交互基础教程(小白教学版)

马肤

温馨提示:这篇文章已超过435天没有更新,请注意相关的内容是否还可用!

摘要:本文将介绍前后端交互的基础知识,适合初学者了解。前后端交互是Web开发中不可或缺的一部分,涉及到数据的传输和页面渲染等方面。本文将简单易懂地讲解前后端交互的基本概念、工作流程以及常见的技术实现方式,帮助读者快速入门并掌握前后端交互的核心知识。

  • 在我们的印象中什么是前后端交互呢?

  • 我们一个后端程序员为什么要去学习前端知识?

  • 前后端交互到底是靠什么而进行关联的呢?

    接下来我们带着这三个问题来阅读这边文章!!!

    1.前后端交互

    前后端交互(小白教学),前后端交互基础教程(小白教学版) 第1张

    所谓前后端交互,即前后端交互为前端和后端的互动,也可以理解为数据交互,前端需要获取(GET)的数据获取上传(POST)的数据,要通过请求来完成的,前端发送请求,后端接收到请求后,便对数据库进行操作,返回前端所需要的数据,即完成一次前后的交互.具体流程看上图

    在公司中不仅有后端工程师,还有前端工程师,后端人员学习前端的知识是为了更好的和前端工程师进行业务交流以及逻辑合同.

    2.在HTML中创建项目

    前后端交互(小白教学),前后端交互基础教程(小白教学版) 第2张

    我们在普通项目中选择vue项目(2.6.10)进行项目创建(脚手架)

    1.安装项目中所需要的组件

    • npm i vue-router@3.5.3 //路由管理器组件

      1. 创建 router 目录js
      创建 index.js 文件,在其中配置路由
      import Vue from 'vue';
      import router from 'vue-router';
      /* 导入路由 */
      import login from '../views/login';
      /* 导入其他组件 */
      import content from '../components/content';
      /* 导入其他组件 */
      Vue.use(router)
      /* 定义组件路由 */
      var rout = new router({
      routes: [
      {
      path: '/index',
      name: 'index',
      component: index
      },
      {
      path: '/content',
      component: content
      }
      ]
      });
      //导出路由对象
      export default rout;
      • npm i element-ui -S //桌面端组件库

        在 main.js 中写入以下内容:
        import ElementUI from 'element-ui';
        import 'element-ui/lib/theme-chalk/index.css';
        Vue.use(ElementUI);
        new Vue({
        render: h => h(App),
        }).$mount('#app');
        
        •  npm install axios    //HTTP网络端的的请求库
          在 main.js 中配置 axios
          导入 axios
          import axios from 'axios';
          设置访问后台服务器地址
          axios.defaults.baseURL="http://127.0.0.1:9999/api/";
          将 axios 挂载到 vue 全局对象中,使用 this 可以直接访问
          Vue.prototype.$http=axios;

          2.配置文件

          前后端交互(小白教学),前后端交互基础教程(小白教学版) 第3张

          我们在项目中创建出我们所需要的vue文件,vue文件一定要在index.js中进行组件导入,并且设置该组件的路由进行访问

          前后端交互(小白教学),前后端交互基础教程(小白教学版) 第4张

          在app.vue中一定要来显示不同的组件

          3.网页的跳转

          前后端交互(小白教学),前后端交互基础教程(小白教学版) 第5张

          点击楼栋管理和宿舍员管理组件怎么样使得该网页在main中进行渲染呢?

          • 第一步:在项目中创建2个目录,然后再对应的目录中创建对应的vue文件,然后在index.js中进行组件导入(导入的方法上面已经说过了,在这里就不多加解释了)

          • 第二步:配置路由,这里的话,还是比较容易出错的,children是子组件的路由定义,在父组件的括号里进行定义

            前后端交互(小白教学),前后端交互基础教程(小白教学版) 第6张

            • 在main中找到对应的标签进行路由设置

            • 前后端交互(小白教学),前后端交互基础教程(小白教学版) 第7张

            • 在表单中添加一个router

              前后端交互(小白教学),前后端交互基础教程(小白教学版) 第8张

                

              • 在main中添加一个组件

                前后端交互(小白教学),前后端交互基础教程(小白教学版) 第9张

                4.弹窗组件的设置

                前后端交互(小白教学),前后端交互基础教程(小白教学版) 第10张

                • 在对应的目录中创建一个关于弹窗组件的Vue,然后在element中找到弹窗组件

                  dialogFormVisible=true时,弹窗显示 dialogFormVisible=false时,弹窗不显示

                • 前后端交互(小白教学),前后端交互基础教程(小白教学版) 第11张

                • 在主组件中导入

                  前后端交互(小白教学),前后端交互基础教程(小白教学版) 第12张

                  • 放置组件

                    前后端交互(小白教学),前后端交互基础教程(小白教学版) 第13张

                    • 创建一个方法,使得点击后dialogFormVisible=true

                    • 前后端交互(小白教学),前后端交互基础教程(小白教学版) 第14张

                      3.在后端创建项目

                      1.创建一个idea项目

                      2.部署服务

                      前后端交互(小白教学),前后端交互基础教程(小白教学版) 第15张

                      • 点击Web Application,点击OK

                         前后端交互(小白教学),前后端交互基础教程(小白教学版) 第16张

                        • 点击这个,进行服务器的部署

                          前后端交互(小白教学),前后端交互基础教程(小白教学版) 第17张

                          • 点击第一个Tomcat Server

                            前后端交互(小白教学),前后端交互基础教程(小白教学版) 第18张

                            • 点击bin紧挨着的tomcat

                              前后端交互(小白教学),前后端交互基础教程(小白教学版) 第19张

                              • 在Deployment中进行服务器部署,在点击最底下Apply进行应用

                                前后端交互(小白教学),前后端交互基础教程(小白教学版) 第20张

                                • 布置好以后就会出现一个小狗的标记

                                  前后端交互(小白教学),前后端交互基础教程(小白教学版) 第21张

                                  3.导入库

                                  • 在WEB-INF中创建一个lib文件,导入所需要的包,选中鼠标右键有一个Add Library添加到库

                                    前后端交互(小白教学),前后端交互基础教程(小白教学版) 第22张

                                    4.配置 Servlet,filter

                                    //配置一个Servlet和filter就要在Web-xml中配置
                                    
                                            名字
                                            文件路径
                                        
                                        
                                            名字(和上面的名字一致)
                                            /域名//一定要/开头,不然项目启动不了
                                        
                                    ​
                                    ​
                                       
                                            名字
                                            文件路径
                                        
                                        
                                            名字(和上面的名字一致)
                                            /*//过滤的类型
                                        

                                    5.跨域过滤器 token过滤器

                                    //跨域过滤器  官方提供
                                    ​
                                    //@WebFilter(urlPatterns = "/*")
                                    public class CorsFilter implements Filter {//解决跨域问题的过滤器
                                        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
                                                throws IOException, ServletException {
                                            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
                                            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
                                            //允许携带Cookie时不能设置为* 否则前端报错
                                            httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("origin"));//允许所有请求跨域
                                            httpResponse.setHeader("Access-Control-Allow-Methods", "*");//允许跨域的请求方法GET, POST, HEAD 等
                                            httpResponse.setHeader("Access-Control-Allow-Headers", "*");//允许跨域的请求头
                                            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");//是否携带cookie
                                    ​
                                            filterChain.doFilter(servletRequest, servletResponse);
                                        }
                                    }
                                    ​
                                    //token过滤器  官方提供
                                    ​
                                    package feifan.com.util;
                                    ​
                                    ​
                                    import com.auth0.jwt.JWT;
                                    import com.auth0.jwt.JWTVerifier;
                                    import com.auth0.jwt.algorithms.Algorithm;
                                    import com.auth0.jwt.interfaces.DecodedJWT;
                                    ​
                                    import java.util.Date;
                                    import java.util.HashMap;
                                    import java.util.Map;
                                    ​
                                    public class JWTUtil {
                                    ​
                                        /**
                                         * jwt 生成 token
                                         *
                                         * @param id
                                         * @param account * @return
                                         */
                                        public static String token(Integer id, String account) {
                                            String token = "";
                                            try {
                                                //过期时间 为 1970.1.1 0:0:0 至 过期时间 当前的毫秒值 + 有效时间
                                                Date expireDate = new Date(new Date().getTime() + 60 * 60 * 24 * 1000);//过期时间
                                                //秘钥及加密算法  加盐
                                                Algorithm algorithm = Algorithm.HMAC256("ZCEQIUBFKSJBFJH2020BQWE");
                                                //设置头部信息
                                                Map header = new HashMap();
                                                header.put("typ", "JWT");//生成的类型
                                                header.put("alg", "HS256");//加密算法
                                                //携带 id,账号信息,生成签名
                                                token = JWT.create()
                                                        .withHeader(header)//头部
                                                        .withClaim("id", id)//用户id
                                                        .withClaim("account", account)//用户账号
                                                        .withExpiresAt(expireDate)
                                                        .sign(algorithm);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                return null;
                                            }
                                            return token;
                                        }
                                    ​
                                        public static boolean verify(String token) {
                                            try {
                                                //验签
                                                Algorithm algorithm = Algorithm.HMAC256("ZCEQIUBFKSJBFJH2020BQWE");
                                                JWTVerifier verifier = JWT.require(algorithm).build();
                                                DecodedJWT jwt = verifier.verify(token);
                                                return true;
                                            } catch (Exception e) {//当传过来的 token 如果有问题,抛出异常
                                                return false;
                                            }
                                        }
                                    ​
                                        /**
                                         * 获得 token 中 playload 部分数据,按需使用
                                         *
                                         * @param token
                                         * @return
                                         */
                                        public static DecodedJWT getTokenInfo(String token) {
                                            return JWT.require(Algorithm.HMAC256("ZCEQIUBFKSJBFJH2020BQWE")).build().verify(token);
                                        }
                                    }

                                    4.一个比较完整项目的代码

                                    项目的重点不是代码,而是思路,代码千篇一律,有一个清晰的思路才是最重要的,一起加油哦

                                    前端代码

                                    前后端交互(小白教学),前后端交互基础教程(小白教学版) 第23张

                                    //Add.vue
                                    
                                        
                                            
                                                
                                                    
                                                
                                            
                                            
                                                取 消
                                                保存
                                            
                                        
                                    
                                    
                                        export default {
                                            data() {
                                                return {
                                                    dialogFormVisible: false,
                                                    form: {
                                                        name: "",
                                                        mark:"save"
                                                    }
                                                }
                                            },
                                            methods:{
                                                upAddCourseForm(){
                                                    this.$http.post("admin/course",jsonToString(this.form)).then((resp)=>{
                                                        if(resp.data.data==true){
                                                             this.$message({
                                                                      message:resp.data.message,
                                                                      type: 'success'
                                                                    });
                                                                    this.$router.go();
                                                        }
                                                    })  
                                                }   
                                            },
                                            mounted(){
                                            }
                                            }
                                            function jsonToString(jsonobj){
                                                               console.log(jsonobj)
                                                               var str = "";
                                                               for(var s in jsonobj){
                                                                    str+=s+"="+jsonobj[s]+"&";    
                                                               }
                                                               return str.substring(0,str.length-1);}
                                    
                                    
                                    
                                    //course.vue
                                    ​
                                    
                                        
                                            
                                                
                                                    
                                                
                                                
                                                    查询
                                                
                                            
                                            
                                    新增 编辑 删除 import AddCourse from "./Add.vue"; import UpdateCourse from "./Update.vue"; export default { components:{ AddCourse, UpdateCourse }, data() { return { courseList:[{ id:"", name:"", adminid:"", oper_time:"" }] } }, methods:{ openAddCourseDialog(){ this.$refs.addCourse.dialogFormVisible =true; }, openUpDateCourse(id){ this.$refs.updateCourse.dialogFormVisible =true; this.$refs.updateCourse.findStudentById(id); }, deleteCourse(id){ this.$confirm('确定要删除吗?', '操作提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { this.$http.get("admin/course?mark=delete&id=" + id).then((resp) => { this.$router.go(); //重载当前组件,刷新 }); }) } }, mounted() { this.$http.get("/admin/course?mark=list").then((resp) => { if (resp.data.code == 200) { console.log(resp); this.courseList = resp.data.data; } }) }} ​ ​
                                    //Update.vue
                                    ​
                                    
                                        
                                            
                                                
                                                    
                                                
                                            
                                            
                                                取 消
                                                保存
                                            
                                        
                                    
                                    ​
                                    
                                        export default {
                                            data() {
                                                return {
                                                    dialogFormVisible: false,
                                                    form: {
                                                        id:"",//虽然不显示,但是需要提交的,唯一标识
                                                        name: "",
                                                        mark:"save"
                                                    }
                                                }
                                            },
                                            methods:{
                                                findStudentById(id){
                                                    //向后端发送请求,根据学生id,查询学生信息
                                                    this.$http.get("admin/course?mark=findCourseById&id="+id).then((resp) => {
                                                                       if(resp.data.code==200){
                                                                           this.form.id=resp.data.data.id;
                                                                           this.form.name=resp.data.data.name;
                                                                       }
                                                        })
                                                },
                                                save(){
                                                        this.$confirm('确定要保存吗?', '操作提示', {
                                                            confirmButtonText: '确定',
                                                            cancelButtonText: '取消',
                                                            type: 'warning'
                                                        }).then(() => {
                                                            this.$http.post("admin/course",jsonToString(this.form)).then((resp)=>{
                                                            this.$router.go(); //重载当前组件,刷新
                                                        });
                                                    })
                                                }
                                            },  
                                            mounted(){
                                                
                                            }
                                    }
                                        function jsonToString(jsonobj){
                                                               console.log(jsonobj)
                                                               var str = "";
                                                               for(var s in jsonobj){
                                                                    str+=s+"="+jsonobj[s]+"&";    
                                                               }
                                                               return str.substring(0,str.length-1);
                                            }
                                    
                                    
                                    
                                    //index.js
                                    ​
                                    //vue-router是一个插件包,所以我们还是需要用npm来进行安装
                                    //打开命令行工具,进行你的项目目录,输入下面命令
                                    //npm i vue-router@3.5.3
                                    //vue router是一个路由管理器
                                    import Vue from 'vue';
                                    import router from 'vue-router';/* 导入路由 */
                                    import Login from '../Login.vue';/* 导入其他组件 */
                                    import Reg from "../Reg.vue";/* 导入其他组件 */
                                    import Main from "../Main.vue";/* 导入其他组件 */
                                    import StudentList from "../views/student/List.vue";
                                    import Course from "../views/course/course.vue";
                                    ​
                                    Vue.use(router);
                                    ​
                                    /* 定义组件路由 */
                                    var rout = new router({
                                    routes: [
                                    {
                                    path: '/login',//路由地址
                                    name: 'Login',
                                    component: Login//组件名
                                    },
                                    {
                                    path: '/main',
                                    component: Main,
                                    children:[//子组件的路由定义
                                        {
                                            path:"/studentList",
                                            component:StudentList
                                        },
                                        {
                                            path:"/course",
                                            component:Course
                                        }
                                    ]
                                    },
                                    {
                                        path:'/reg',
                                        component:Reg
                                    }
                                    ​
                                    ]
                                    });
                                    //添加路由导航守卫,每次发生路由时触发,to.path你要去的页面
                                    rout.beforeEach((to,from,next)=>{
                                    if(to.path=="/login"){//如果用户访问的登录页,直接放行
                                    return next();
                                    }else{
                                    var account =sessionStorage.getItem("account");
                                    if(account==null){
                                    return next("/login");
                                    }else{
                                     return next();//已经登录
                                    }
                                    }
                                    })
                                    ​
                                    //导出路由对象
                                    export default rout;
                                    //App.vue
                                    
                                          
                                                 
                                                      
                                                      
                                                            前后端交互(小白教学),前后端交互基础教程(小白教学版) 第24张 {
                                                 //所有的都满足规则返回True,否则返回false
                                               if (valid) {
                                                   this.$http.post("login",jsonToString(this.form)).then((resp)=>{
                                                       // console.log(resp);
                                                       console.log(resp.data.code);
                                                       if(resp.data.code==200){
                                                           //sessionStorage浏览器提供的一个会话级别的存储空间,浏览器关闭后立刻消失
                                                          sessionStorage.setItem("account",resp.data.data.account);//浏览器关闭即清除
                                                          sessionStorage.setItem("token",resp.data.data.token);
                                                          // localStorage.setItem("key","value");//长久保存
                                                           this.$router.push("/main");
                                                       }else if(resp.data.code==201){
                                                            this.$message({
                                                                     message:resp.data.message,type: 'warning' });;
                                                       }else{
                                                           this.$message.error(resp.data.message);
                                                       }
                                                   })
                                                  
                                               } 
                                             });
                                           },
                                           resetForm(form) {
                                             this.$refs[form].resetFields();
                                           }
                                         }
                                       }
                                         //将json对象序列化为键=值&键=值
                                                   function jsonToString(jsonobj){
                                                       console.log(jsonobj)
                                                       var str = "";
                                                       for(var s in jsonobj){
                                                            str+=s+"="+jsonobj[s]+"&";    
                                                       }
                                                       return str.substring(0,str.length-1);
                                                   }
                                     
                                     
                                       .login_container{
                                         height: 100vh;
                                         margin: 0px;
                                         padding: 0px;
                                        background-image:url(../v2-1853f9575237e195e823f6f2c73138ac_r.jpg);
                                       }
                                         .login_box{
                                           width: 450px;
                                           height: 350px;
                                           background-color: #fff;
                                           border-radius: 10px;
                                           position: absolute;
                                           left: 50%;
                                           top: 50%;
                                           transform: translate(-50%,-50%);  
                                         }
                                         .img_box{
                                            width: 130px;
                                            height: 130px;
                                            position: absolute;
                                            left: 50%;
                                            transform: translate(-50%,-50%);
                                            background-color: #fff;
                                            border-radius: 50%;
                                            padding: 5px;
                                            border: 1px solid #eee;
                                         }
                                         .img_box img{
                                              width: 100%;
                                              height: 100%;
                                              border-radius: 50%;
                                              background-color: #eee;
                                          }
                                     
                                    //main.js
                                    //main.js是项目核心配置文件
                                    //导入vue.js
                                    import Vue from 'vue'
                                    //导入一个默认的组件
                                    import App from './App.vue'
                                    Vue.config.productionTip = false
                                     //导入路由组件   ./表示当前目录
                                    import router from "./router/index.js";
                                    Vue.use(router);
                                    //导入ElementUI框架, 会导入ElementUI中所有的组件
                                    import ElementUI from 'element-ui';
                                    import 'element-ui/lib/theme-chalk/index.css';
                                    Vue.use(ElementUI);
                                    //导入 axios
                                    import axios from 'axios';
                                    //设置访问后台服务器地址
                                    axios.defaults.baseURL="http://localhost:8080/webBack/";
                                    //将 axios 挂载到 vue 全局对象中,使用 this 可以直接访问
                                    Vue.prototype.$http=axios;
                                    //axios 请求拦截
                                    axios.interceptors.request.use(config =>{
                                    //为请求头对象,添加 Token 验证的 token 字段
                                    config.headers.token =sessionStorage.getItem('token');
                                    return config;
                                    })
                                    // 添加响应拦截器
                                    axios.interceptors.response.use((resp) =>{//正常响应拦截
                                    if(resp.data.code==500){
                                    ElementUI.Message({message:resp.data.message,type:"error"})
                                    }
                                    if(resp.data.code==202){
                                    sessionStorage.clear();
                                    router.replace("/login");
                                    }
                                    return resp;
                                    });
                                    //创建项目中唯一的一个vue对象
                                    new Vue({
                                      render: h => h(App),  //默认将app.vue组件加载到唯一的index.html中的div上面,
                                      router,
                                    }).$mount('#app')
                                    ​
                                    //Main.vue
                                    
                                    
                                        
                                            顶部
                                          
                                              
                                                      
                                                      
                                                        修改密码
                                                        安全退出
                                                        个人信息
                                                        测试
                                                      
                                              
                                              {{account}}
                                          
                                          
                                              
                                            
                                                 
                                                      
                                                        功能菜单
                                                        
                                                          学生管理
                                                          课程管理
                                                        
                                                      
                                                    
                                            
                                            
                                            
                                                
                                            
                                          
                                        
                                    
                                    
                                      export default{
                                          data(){
                                              return{
                                                  account:""
                                              }
                                          },
                                          methods:{
                                              //安全退出
                                              logOut(){
                                                  this.$confirm('确定要退出吗?', '操作提示', {
                                                            confirmButtonText: '确定',
                                                            cancelButtonText: '取消',
                                                            type: 'warning'
                                                          }).then(() => {
                                                              sessionStorage.clear();
                                                             this.$router.push("/login")
                                                          });
                                              }  , 
                                          test(){
                                              //将后端携带token,每次请求都需要发送一个token比较麻烦
                                              this.$http.get("admin/test").then((resp)=>{
                                              // sessionStorage.setItem("token",resp.data.data.token);
                                              if(resp.data.code==200){
                                                  alert("测试成功");
                                              }
                                              }
                                          );
                                          },  
                                          mounted(){
                                            this.account=sessionStorage.getItem("account");
                                            // if(this.account==null){判断浏览器中用户信息是否为空,如果为空,说明登录失败,应该跳转到登录界面
                                            //  this.$router.push("/login");
                                            // }    
                                          }
                                      }}
                                    
                                    
                                         .el-header{
                                            background-color: #0c81ff;
                                            color: #333;
                                            text-align: right;
                                            line-height: 60px;
                                          } 
                                          .el-aside {
                                            background-color: #D3DCE6;
                                            color: #333;
                                            text-align: center;
                                            height: 100vh;
                                          }
                                          .el-main {
                                            background-color: #E9EEF3;
                                            color: #333;
                                            text-align: center;
                                            height: 100vh;
                                          }
                                    

                                    后端代码

                                    前后端交互(小白教学),前后端交互基础教程(小白教学版) 第25张

                                    注意:Servlet和过滤器都需要在web-xml中进行配置.

                                    //CourseDao
                                    package feifan.com.servlet;
                                    ​
                                    import com.auth0.jwt.interfaces.DecodedJWT;
                                    import com.fasterxml.jackson.databind.ObjectMapper;
                                    import feifan.com.dao.CourseDao;
                                    import feifan.com.dao.StudentDao;
                                    import feifan.com.util.CommonResult;
                                    import feifan.com.util.JWTUtil;
                                    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.io.PrintWriter;
                                    import java.util.List;
                                    public class CourseServlet extends HttpServlet {
                                        @Override
                                        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                          String mark=req.getParameter("mark");
                                            System.out.println(mark);
                                           if("list".equals(mark)){
                                               findCourseList(req,resp);
                                           }
                                           if("delete".equals(mark)){
                                               deleteCourse(req,resp);
                                           }
                                           if("findCourseById".equals(mark)){
                                               findCourseById(req,resp);
                                           }
                                        }
                                        private void findCourseById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                String id=req.getParameter("id");
                                                CourseDao courseDao=new CourseDao();
                                                Course course=courseDao.findCourseById(id);
                                                commonResult=new CommonResult(200,course,"查询成功");
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                    ​
                                        }
                                        private void deleteCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                String id=req.getParameter("id");
                                                CourseDao courseDao=new CourseDao();
                                                courseDao.deleteCourse(id);
                                                commonResult=new CommonResult(200,null,"删除成功");
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                        private void findCourseList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                CourseDao courseDao=new CourseDao();
                                                List courseList= courseDao.courses();
                                                commonResult=new CommonResult(200,courseList,"查询成功");
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                    ​
                                        @Override
                                        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                           String mark=req.getParameter("mark");
                                            if("save".equals(mark)){
                                                addCourse(req,resp);
                                            }
                                        }
                                        private void addCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                String id=req.getParameter("id");//修改有id,新增没有id
                                                String name=req.getParameter("name");
                                                //获取请求头中的token
                                                String token = req.getHeader("token");
                                                //解析token
                                                DecodedJWT tokenInfo= JWTUtil.getTokenInfo(token);
                                                //获取到token中的管理员信息
                                                Integer adminid=tokenInfo.getClaim("id").asInt();
                                                if(id==null){
                                                    CourseDao studentDao=new CourseDao();
                                                    boolean flag= studentDao.addCourse(name,adminid);
                                                    commonResult=new CommonResult(200,flag,"添加成功");
                                                }else{
                                                    CourseDao studentDao=new CourseDao();
                                                    boolean flag= studentDao.upDateCourse(id,name,adminid);
                                                    commonResult=new CommonResult(200,flag,"修改成功");
                                                }
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                    }
                                    //CommonResult
                                    package feifan.com.util;
                                    ​
                                    public class CommonResult {
                                        int code;
                                        Object data;
                                        String message;
                                    ​
                                        public CommonResult(int code, Object data, String message) {
                                            this.code = code;
                                            this.data = data;
                                            this.message = message;
                                        }
                                        public int getCode() {
                                            return code;
                                        }
                                        public void setCode(int code) {
                                            this.code = code;
                                        }
                                        public Object getData() {
                                            return data;
                                        }
                                        public void setData(Object data) {
                                            this.data = data;
                                        }
                                        public String getMessage() {
                                            return message;
                                        }
                                        public void setMessage(String message) {
                                            this.message = message;
                                        }
                                    }
                                    //CourseServlet
                                    package feifan.com.servlet;
                                    ​
                                    import com.auth0.jwt.interfaces.DecodedJWT;
                                    import com.fasterxml.jackson.databind.ObjectMapper;
                                    import feifan.com.dao.CourseDao;
                                    import feifan.com.dao.StudentDao;
                                    import feifan.com.util.CommonResult;
                                    import feifan.com.util.JWTUtil;
                                    ​
                                    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.io.PrintWriter;
                                    import java.util.List;
                                    public class CourseServlet extends HttpServlet {
                                        @Override
                                        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                          String mark=req.getParameter("mark");
                                            System.out.println(mark);
                                           if("list".equals(mark)){
                                               findCourseList(req,resp);
                                           }
                                           if("delete".equals(mark)){
                                               deleteCourse(req,resp);
                                           }
                                           if("findCourseById".equals(mark)){
                                               findCourseById(req,resp);
                                           }
                                        }
                                        private void findCourseById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                String id=req.getParameter("id");
                                                CourseDao courseDao=new CourseDao();
                                                Course course=courseDao.findCourseById(id);
                                                commonResult=new CommonResult(200,course,"查询成功");
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                        private void deleteCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                String id=req.getParameter("id");
                                                CourseDao courseDao=new CourseDao();
                                                courseDao.deleteCourse(id);
                                                commonResult=new CommonResult(200,null,"删除成功");
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                    ​
                                        private void findCourseList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                CourseDao courseDao=new CourseDao();
                                                List courseList= courseDao.courses();
                                                commonResult=new CommonResult(200,courseList,"查询成功");
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                        @Override
                                        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                           String mark=req.getParameter("mark");
                                            if("save".equals(mark)){
                                                addCourse(req,resp);
                                            }
                                        }
                                        private void addCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                                            resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应内容的编码
                                            PrintWriter pt=resp.getWriter();
                                            CommonResult commonResult=null;
                                            try{
                                                String id=req.getParameter("id");//修改有id,新增没有id
                                                String name=req.getParameter("name");
                                                //获取请求头中的token
                                                String token = req.getHeader("token");
                                                //解析token
                                                DecodedJWT tokenInfo= JWTUtil.getTokenInfo(token);
                                                //获取到token中的管理员信息
                                                Integer adminid=tokenInfo.getClaim("id").asInt();
                                                if(id==null){
                                                    CourseDao studentDao=new CourseDao();
                                                    boolean flag= studentDao.addCourse(name,adminid);
                                                    commonResult=new CommonResult(200,flag,"添加成功");
                                                }else{
                                                    CourseDao studentDao=new CourseDao();
                                                    boolean flag= studentDao.upDateCourse(id,name,adminid);
                                                    commonResult=new CommonResult(200,flag,"修改成功");
                                                }
                                            }catch(Exception e){
                                                e.printStackTrace();
                                                commonResult=new CommonResult(500,null,"系统忙"+e.getMessage());
                                            }
                                            ObjectMapper objectMapper=new ObjectMapper();
                                            String json= objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                    }
                                    //LoginDao
                                    package feifan.com.dao;
                                    import feifan.com.servlet.Admin;
                                    import java.sql.*;
                                    public class LoginDao {
                                    ​
                                        public Admin work(String account, String password) throws SQLException {
                                            Admin admin=null;
                                            Connection connection = null;
                                            Statement st = null;
                                            PreparedStatement ps = null;
                                            Boolean df = false;
                                            try {
                                                Class.forName("com.mysql.cj.jdbc.Driver");//定义驱动程序名为jdbcName  com.mysql.cj.jdbc.Driver
                                                //获取数据库连接,使用java.sql里面的DriverManager.getConnection来完成
                                                connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/zp?serverTimezone=Asia/Shanghai", "root", "root");
                                                //构造一个Statement 对象来执行SQL语句
                                                st = connection.createStatement();
                                                ps = connection.prepareStatement("select id,account from admin where account=? and pass=? ");//执行SQL语句
                                                ps.setObject(1, account);
                                                ps.setObject(2, password);
                                                ResultSet resultSet = ps.executeQuery();//执行sql并返回结果结束.返回一个结果集(ResultSet)对象
                                                while (resultSet.next()) {//遍历结果集
                                                    admin=new Admin();
                                                    admin.setId(resultSet.getInt("id"));
                                                    admin.setAccount(resultSet.getString("account"));
                                                }
                                                System.out.println("数据库连接成功");
                                            } catch (ClassNotFoundException | SQLException e) {
                                                e.printStackTrace();
                                            } finally {//关闭记录集
                                                if (connection != null) {
                                                    connection.close();
                                                }
                                                if(st!=null){
                                                    st.close();
                                                }
                                                if(ps!=null){
                                                    ps.close();
                                                }
                                            }
                                            return admin;
                                        }
                                    ​
                                    }
                                    //LoginDao
                                    package feifan.com.dao;
                                    import feifan.com.servlet.Admin;
                                    import java.sql.*;
                                    public class LoginDao {
                                    ​
                                        public Admin work(String account, String password) throws SQLException {
                                            Admin admin=null;
                                            Connection connection = null;
                                            Statement st = null;
                                            PreparedStatement ps = null;
                                            Boolean df = false;
                                            try {
                                                Class.forName("com.mysql.cj.jdbc.Driver");//定义驱动程序名为jdbcName  com.mysql.cj.jdbc.Driver
                                                //获取数据库连接,使用java.sql里面的DriverManager.getConnection来完成
                                                connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/zp?serverTimezone=Asia/Shanghai", "root", "root");
                                                //构造一个Statement 对象来执行SQL语句
                                                st = connection.createStatement();
                                                ps = connection.prepareStatement("select id,account from admin where account=? and pass=? ");//执行SQL语句
                                                ps.setObject(1, account);
                                                ps.setObject(2, password);
                                                ResultSet resultSet = ps.executeQuery();//执行sql并返回结果结束.返回一个结果集(ResultSet)对象
                                                while (resultSet.next()) {//遍历结果集
                                                    admin=new Admin();
                                                    admin.setId(resultSet.getInt("id"));
                                                    admin.setAccount(resultSet.getString("account"));
                                                }
                                                System.out.println("数据库连接成功");
                                            } catch (ClassNotFoundException | SQLException e) {
                                                e.printStackTrace();
                                            } finally {//关闭记录集
                                                if (connection != null) {
                                                    connection.close();
                                                }
                                                if(st!=null){
                                                    st.close();
                                                }
                                                if(ps!=null){
                                                    ps.close();
                                                }
                                            }
                                            return admin;
                                        }
                                    ​
                                    }
                                     
                                    //LoginServlet
                                    package feifan.com.servlet;
                                    ​
                                    import com.fasterxml.jackson.databind.ObjectMapper;
                                    import feifan.com.dao.LoginDao;
                                    import feifan.com.util.CommonResult;
                                    import feifan.com.util.JWTUtil;
                                    ​
                                    ​
                                    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.io.PrintWriter;
                                    import java.sql.SQLException;
                                    ​
                                    public class LoginServlet_one extends HttpServlet {
                                    ​
                                    //    @Override
                                    //    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                    //        resp.setHeader("Content-type", "text/html;charset=utf-8");//设置响应内容的编码
                                    //        PrintWriter pt = resp.getWriter();
                                    //
                                    //        System.out.println("测试成功");
                                    //        CommonResult commonResult = new CommonResult(200,null, "验证token");
                                    //        ObjectMapper objectMapper = new ObjectMapper();
                                    //        String json = objectMapper.writeValueAsString(commonResult);
                                    //        pt.print(json);
                                    //
                                    //    }
                                    ​
                                        @Override
                                        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                                            //req.setCharacterEncoding("utf-8");//设置的是请求数据的解析编码
                                            //接收请求中自己的数据
                                            //req是前端往后端发送的信息,resp是后端向前端发送的信息
                                            String account = req.getParameter("account");//将前端发送过来的账号进行接收
                                            String password = req.getParameter("password");//将前端发送过来的密码进行接收
                                    ​
                                            CommonResult commonResult = null;
                                    ​
                                            System.out.println(account);
                                            resp.setHeader("Content-type", "text/html;charset=utf-8");//设置响应内容的编码
                                    ​
                                            PrintWriter pt = resp.getWriter();
                                            //处理访问dao与数据库交互,根据返回的结果向客户端响应内容
                                    ​
                                            LoginDao loginDao = new LoginDao();//创建一个与数据库连接的对象
                                            try {
                                                Admin admin = loginDao.work(account, password);//调用对象中的work()方法
                                                if (admin != null) {//如果判断数据库中有admin对象的数据,则进入此循环
                                                    //登录成功,生成token,携带用户信息
                                                    String token = JWTUtil.token(admin.getId(), admin.getAccount());//将后端通过账号&id生成的token
                                                    admin.setToken(token);//在后端将token字符串添加到admin中
                                                    commonResult = new CommonResult(200, admin, "登录成功");
                                    ​
                                                } else {
                                                    commonResult = new CommonResult(201, admin, "账号或者密码错误");
                                                }
                                            } catch (Exception throwables) {
                                                throwables.printStackTrace();
                                                commonResult = new CommonResult(500, null, "系统忙" + throwables.getLocalizedMessage());
                                            }
                                            //向前端发送信息
                                            ObjectMapper objectMapper = new ObjectMapper();
                                            String json = objectMapper.writeValueAsString(commonResult);
                                            pt.print(json);
                                        }
                                    }
                                    ​

0
收藏0
文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。

相关阅读

  • 【研发日记】Matlab/Simulink自动生成代码(二)——五种选择结构实现方法,Matlab/Simulink自动生成代码的五种选择结构实现方法(二),Matlab/Simulink自动生成代码的五种选择结构实现方法详解(二)
  • 超级好用的C++实用库之跨平台实用方法,跨平台实用方法的C++实用库超好用指南,C++跨平台实用库使用指南,超好用实用方法集合,C++跨平台实用库超好用指南,方法与技巧集合
  • 【动态规划】斐波那契数列模型(C++),斐波那契数列模型(C++实现与动态规划解析),斐波那契数列模型解析与C++实现(动态规划)
  • 【C++】,string类底层的模拟实现,C++中string类的模拟底层实现探究
  • uniapp 小程序实现微信授权登录(前端和后端),Uniapp小程序实现微信授权登录全流程(前端后端全攻略),Uniapp小程序微信授权登录全流程攻略,前端后端全指南
  • Vue脚手架的安装(保姆级教程),Vue脚手架保姆级安装教程,Vue脚手架保姆级安装指南,Vue脚手架保姆级安装指南,从零开始教你如何安装Vue脚手架
  • 如何在树莓派 Raspberry Pi中本地部署一个web站点并实现无公网IP远程访问,树莓派上本地部署Web站点及无公网IP远程访问指南,树莓派部署Web站点及无公网IP远程访问指南,本地部署与远程访问实践,树莓派部署Web站点及无公网IP远程访问实践指南,树莓派部署Web站点及无公网IP远程访问实践指南,本地部署与远程访问详解,树莓派部署Web站点及无公网IP远程访问实践详解,本地部署与远程访问指南,树莓派部署Web站点及无公网IP远程访问实践详解,本地部署与远程访问指南。
  • vue2技术栈实现AI问答机器人功能(流式与非流式两种接口方法),Vue2技术栈实现AI问答机器人功能,流式与非流式接口方法探究,Vue2技术栈实现AI问答机器人功能,流式与非流式接口方法详解
  • 发表评论

    快捷回复:表情:
    评论列表 (暂无评论,0人围观)

    还没有评论,来说两句吧...

    目录[+]

    取消
    微信二维码
    微信二维码
    支付宝二维码