1.前后端交互
所谓前后端交互,即前后端交互为前端和后端的互动,也可以理解为数据交互,前端需要获取(GET)的数据获取上传(POST)的数据,要通过请求来完成的,前端发送请求,后端接收到请求后,便对数据库进行操作,返回前端所需要的数据,即完成一次前后的交互.具体流程看上图
在公司中不仅有后端工程师,还有前端工程师,后端人员学习前端的知识是为了更好的和前端工程师进行业务交流以及逻辑合同.
2.在HTML中创建项目
我们在普通项目中选择vue项目(2.6.10)进行项目创建(脚手架)
1.安装项目中所需要的组件
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;
在 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.配置文件
我们在项目中创建出我们所需要的vue文件,vue文件一定要在index.js中进行组件导入,并且设置该组件的路由进行访问
在app.vue中一定要<router–view></router-view>来显示不同的组件
3.网页的跳转
点击楼栋管理和宿舍员管理组件怎么样使得该网页在main中进行渲染呢?
4.弹窗组件的设置
-
放置组件
3.在后端创建项目
3.导入库
//配置一个Servlet和filter就要在Web-xml中配置
<servlet>
<servlet-name>名字</servlet-name>
<servlet-class>文件路径</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>名字(和上面的名字一致)</servlet-name>
<url-pattern>/域名</url-pattern>//一定要/开头,不然项目启动不了
</servlet-mapping>
<filter>
<filter-name>名字</filter-name>
<filter-class>文件路径</filter-class>
</filter>
<filter-mapping>
<filter-name>名字(和上面的名字一致)</filter-name>
<url-pattern>/*</url-pattern>//过滤的类型
</filter-mapping>
//跨域过滤器 官方提供
//@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<String, Object> 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
<template>
<el-dialog title="新增专业" :visible.sync="dialogFormVisible">
<el-form :model="form">
<el-form-item label="专业名称">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogFormVisible =upAddCourseForm()">保存</el-button>
</div>
</el-dialog>
</template>
<script>
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);}
</script>
<style>
</style>
//course.vue
<template>
<el-card class="box-card" style="text-align: left;">
<el-row :gutter="20">
<el-col :span="6">
<el-input placeholder="专业"></el-input>
</el-col>
<el-col :span="6">
<el-button type="primary" icon="el-icon-search">查询</el-button>
</el-col>
</el-row>
<br />
<el-button type="primary" icon="el-icon-plus" @click="openAddCourseDialog()">新增</el-button>
<el-table :data="courseList" style="width: 100%" height="250">
<el-table-column prop="id" label="序号" width="120">
</el-table-column>
<el-table-column prop="name" label="专业名称" width="120">
</el-table-column>
<el-table-column prop="adminid" label="操作人" width="120">
</el-table-column>
<el-table-column prop="oper_time" label="操作时间" width="180">
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="openUpDateCourse(scope.row.id)">编辑</el-button>
<el-button size="mini" type="danger" @click="deleteCourse(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- </div> -->
<!-- 放置组件,ref引用名 -->
<AddCourse ref="addCourse"></Addcourse>
<UpdateCourse ref="updateCourse"></UpdateCourse>
</el-card>
</template>
<script>
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;
}
})
}}
</script>
<style>
</style>
//Update.vue
<template>
<el-dialog title="修改专业" :visible.sync="dialogFormVisible">
<el-form :model="form">
<el-form-item label="专业名称">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogFormVisible =save()">保存</el-button>
</div>
</el-dialog>
</template>
<script>
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);
}
</script>
<style>
</style>
//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
<<template>
<div id="app">
<!-- router-view就是用来显示不同组件的,就向一个画布-->
<router-view></router-view>
</div>
</template>
<script>
/* 导出组件,并为组件定义数据,函数,生命周期函数 */
export default{
data(){
return{
}
}
}
</script>
<style>
</style>
//Login.vue
<template>
<div class="login_container">
<!-- 登录盒子-->
<div class="login_box">
<!-- 头像盒子-->
<div class="img_box">
<img src="./assets/logo.png"/>
</div>
<div style="padding-top: 100px; padding-right: 30px;">
<el-form ref="form" :model="form" :rules="rules" label-width="80px" >
<el-form-item label="账号" prop="account">
<el-input v-model="form.account" placeholder="请输入账号"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-top" @click="submitForm('form')">登录</el-button>
<el-button icon="el-icon-delete-solid" @click="resetForm('form')">取消</el-button>
</el-form-item>
</el-form>
</div>
</div>
</div>
</template>
<script>
/* 导出组件,并为组件定义数据,函数,生命周期函数 */
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,否则返回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);
}
</script>
<style>
.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;
}
</style>
//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 id="app">div上面,
router,
}).$mount('#app')
//Main.vue
<!-- 后端管理界面 -->
<template>
<el-container>
顶部
<el-header>
<el-dropdown>
<i class="el-icon-setting" style="margin-right: 15px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>修改密码</el-dropdown-item>
<el-dropdown-item><span @click="logOut()">安全退出</span></el-dropdown-item>
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item><span @click="test()">测试</span></el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<span>{{account}}</span>
</el-header>
<el-container>
<!-- 左侧菜单-->
<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
<el-menu :default-openeds="['1']" router>
<el-submenu index="1">
<template slot="title"><i class="el-icon-message"></i>功能菜单</template>
<el-menu-item-group>
<el-menu-item index="/studentList">学生管理</el-menu-item>
<el-menu-item index="/course">课程管理</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
</el-aside>
<!-- 右侧操作区间 -->
<el-main>
<router-view></router-view>
</el-main>
</el-container>
</el-container>
</template>
<script>
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");
// }
}
}}
</script>
<style>
.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;
}
</style>
后端代码
注意: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<Course> 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<Course> 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);
}
}
原文地址:https://blog.csdn.net/dfdbb6b/article/details/127490718
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_23792.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。