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

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

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

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

1.前后端交互

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

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

2.在HTML中创建项目

我们在普通项目中选择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导入 axiosimport axios from 'axios';设置访问后台服务器地址axios.defaults.baseURL="http://127.0.0.1:9999/api/";将 axios 挂载到 vue 全局对象中,使用 this 可以直接访问Vue.prototype.$http=axios;

2.配置文件

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

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

3.网页的跳转

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

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

  • 在表单中添加一个router

  • 在main中添加一个组件

4.弹窗组件的设置

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

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

  • 在主组件中导入

  • 放置组件

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

3.在后端创建项目

1.创建一个idea项目

2.部署服务器

  • 点击Web Application,点击OK

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

  • 点击第一个Tomcat Server

  • 点击bin紧挨着的tomcat

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

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

3.导入库

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

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.一个比较完整项目的代码

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

前端代码

//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('确定要删除吗" /> {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<  /* 导出组件,并为组件定义数据,函数,生命周期函数 */ export default{ data(){ return{ } } }
//Login.vue   登录 取消  /* 导出组件,并为组件定义数据,函数,生命周期函数 */ export default { data() {return { form: {account: '',password: '' }, rules: {account: [ { required: true, message: '请输入正确的账号', trigger: 'blur' }, { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }],password: [ { required: true, message: '请输入正确的密码', trigger: 'blur' }, { min: 3, max: 6, message: '长度在 3 到 6 个字符',trigger: 'blur' }] }}; }, methods: {submitForm(form) {//引用,在此把前端登录表单中的数据向后端java发送this.form this.$refs[form].validate((valid) => { //所有的都满足规则返回True,否则返回falseif (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.jsimport 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);//导入 axiosimport 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('确定要退出吗" />{ // 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;}

后端代码

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

//CourseDaopackage 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 {@Overrideprotected 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); }​@Overrideprotected 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,新增没有idString name=req.getParameter("name");//获取请求头中的tokenString token = req.getHeader("token");//解析tokenDecodedJWT 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); }}
//CommonResultpackage 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; }}

//CourseServletpackage 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 {@Overrideprotected 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); }@Overrideprotected 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,新增没有idString name=req.getParameter("name");//获取请求头中的tokenString token = req.getHeader("token");//解析tokenDecodedJWT 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); }}

//LoginDaopackage 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");//定义驱动程序名为jdbcNamecom.mysql.cj.jdbc.Driver//获取数据库连接,使用java.sql里面的DriverManager.getConnection来完成connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/zp" />
//LoginDaopackage 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");//定义驱动程序名为jdbcNamecom.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; }​}
//LoginServletpackage 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);//// }​@Overrideprotected 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生成的tokenadmin.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); }}​