在我们的印象中什么是前后端交互呢?
我们一个后端程序员为什么要去学习前端知识?
前后端交互到底是靠什么而进行关联的呢?
接下来我们带着这三个问题来阅读这边文章!!!
所谓前后端交互,即前后端交互为前端和后端的互动,也可以理解为数据交互,前端需要获取(GET)的数据获取上传(POST)的数据,要通过请求来完成的,前端发送请求,后端接收到请求后,便对数据库进行操作,返回前端所需要的数据,即完成一次前后的交互.具体流程看上图
在公司中不仅有后端工程师,还有前端工程师,后端人员学习前端的知识是为了更好的和前端工程师进行业务交流以及逻辑合同.
我们在普通项目中选择vue项目(2.6.10)进行项目创建(脚手架)
npm i [email protected] //路由管理器组件
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');
在 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;
我们在项目中创建出我们所需要的vue文件,vue文件一定要在index.js中进行组件导入,并且设置该组件的路由进行访问
在app.vue中一定要
点击楼栋管理和宿舍员管理组件怎么样使得该网页在main中进行渲染呢?
第一步:在项目中创建2个目录,然后再对应的目录中创建对应的vue文件,然后在index.js中进行组件导入(导入的方法上面已经说过了,在这里就不多加解释了)
第二步:配置路由,这里的话,还是比较容易出错的,children是子组件的路由定义,在父组件的括号里进行定义
在main中添加一个
在对应的目录中创建一个关于弹窗组件的Vue,然后在element中找到弹窗组件
dialogFormVisible=true时,弹窗显示 dialogFormVisible=false时,弹窗不显示
在主组件中导入
放置组件
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);
}
}
项目的重点不是代码,而是思路,代码千篇一律,有一个清晰的思路才是最重要的,一起加油哦
//Add.vue
//course.vue
查询
新增
编辑
删除
//Update.vue
//index.js
//vue-router是一个插件包,所以我们还是需要用npm来进行安装
//打开命令行工具,进行你的项目目录,输入下面命令
//npm i [email protected]
//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
<
//Login.vue
登录
取消
//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}}
功能菜单
学生管理
课程管理
后端代码
注意: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);
}
}