1.后端的crud
(1)在mapper.xml中写 select insert update delete
<mapper namespace="cn.itsource.crm.mapper.DepartmentMapper">
<!--查询所有数据-->
<select id="queryAll" resultType="Department">
select * from department
</select>
<!--查询一条数据-->
<select id="queryOne" parameterType="long" resultType="Department">
select * from department where id =#{id}
</select>
<!--新增-->
<insert id="save" parameterType="department">
insert into department(name) values (#{name})
</insert>
<!--修改-->
<update id="update" parameterType="department">
update department set name=#{name} where id=#{id}
</update>
<!--删除-->
<delete id="delete" parameterType="long">
delete from department where id=#{id}
</delete>
</mapper>
(2)控制层controller的实现
这里用了restfull风格,进行传输请求
http get/post/patch/put/delete 完成增删改查
@Controller
@RequestMapping("/department")
**//解决跨域问题
@CrossOrigin**
public class DepartmentController {
@Autowired
private IDepartmentService departmentService;
@RequestMapping(value = "/list",method = RequestMethod.PATCH)
@ResponseBody
//查询所有数据
public List<Department> list(){
return departmentService.queryAll();
}
//新增
//@RequestBody表示传送的是json数据
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public AjaxResult save(@RequestBody Department department){
System.out.println("新增部门:"+department);
departmentService.save(department);
return new AjaxResult();
}
//修改
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public AjaxResult update(@RequestBody Department department){
System.out.println("修改部门:"+department);
departmentService.update(department);
return new AjaxResult();
}
//删除
@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
@ResponseBody
//@PathVariable接受占位符value = "/{id}"传过来的值
public AjaxResult delete(@PathVariable Long id){
System.out.println("删除:"+id);
departmentService.delete(id);
return new AjaxResult();
}
//查询一条数据
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
@ResponseBody
public Department queryOne(@PathVariable Long id){
System.out.println("查询:"+id);
return departmentService.queryOne(id);
}
}
2.前端页面的处理
(1) 创建一个Department.vue这个页面
(2) 配置路由
path: '/',
component: Home,
name: '导航一',
iconCls: 'el-icon-message',//图标样式class
children: [
{ path: '/main', component: Main, name: '主页', hidden: true },
{ path: '/table', component: Table, name: 'Table' },
{ path: '/form', component: Form, name: 'Form' },
{ path: '/user', component: user, name: '列表' },
{ path: '/department', component: department, name: '部门管理' }
]
(3) main.js 引入axios
(4) 注释掉模拟数据
main.js中进行
/*import Mock from './mock'
Mock.bootstrap();*/
import axios from 'axios'
//配置axios的全局基本路径
axios.defaults.baseURL='http://localhost/'
//全局属性配置,在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios
(5) 修改Department.vue这里面界面
<template>
<section>
<!--工具条-->
<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
<el-form :inline="true" :model="filters">
<el-form-item>
<el-input v-model="filters.name" placeholder="姓名"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="getDepartments">查询</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleAdd">新增</el-button>
</el-form-item>
</el-form>
</el-col>
<!--列表-->
<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
<el-table-column type="selection" width="55">
</el-table-column>
<el-table-column type="index" width="60">
</el-table-column>
<el-table-column prop="name" label="部门" width="120" sortable>
</el-table-column>
<el-table-column label="操作" width="150">
<template scope="scope">
<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!--工具条-->
<el-col :span="24" class="toolbar">
<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
</el-pagination>
</el-col>
<!--编辑界面-->
<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
<el-form-item label="部门" prop="name">
<el-input v-model="editForm.name" auto-complete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click.native="editFormVisible = false">取消</el-button>
<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
</div>
</el-dialog>
<!--新增界面-->
<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
<el-form-item label="部门" prop="name">
<el-input v-model="addForm.name" auto-complete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click.native="addFormVisible = false">取消</el-button>
<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
</div>
</el-dialog>
</section>
</template>
<script>
//import util from '../../common/js/util'
//import NProgress from 'nprogress'
//import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
export default {
data() {
return {
filters: {
name: ''
},
departments: [],
total: 0,
page: 1,
listLoading: false,
sels: [],//列表选中列
editFormVisible: false,//编辑界面是否显示
editLoading: false,
editFormRules: {
name: [
{required: true, message: '请输入姓名', trigger: 'blur'}
]
},
//编辑界面数据
editForm: {
id: 0,
name: ''
},
addFormVisible: false,//新增界面是否显示
addLoading: false,
addFormRules: {
name: [
{required: true, message: '请输入姓名', trigger: 'blur'}
]
},
//新增界面数据
addForm: {
name: ''
}
}
},
methods: {
handleCurrentChange(val) {
this.page = val;
this.getDepartments();
},
getDepartments() {
this.listLoading = true;
this.$http.patch("/department/list").then(res => {
//传入的数据对象
console.debug(res);
this.departments = res.data;
this.listLoading = false;
//NProgress.done();
});
},
//显示新增界面
handleAdd: function () {
this.addFormVisible = true;
this.addForm = {
name: ''
};
},
//新增保存
addSubmit: function () {
//新增前的验证
this.$refs.addForm.validate((valid) => {
if (valid) {
this.$confirm('确认提交吗?', '提示', {}).then(() => {
this.addLoading = true;
//得到新增加的对象
let para = Object.assign({}, this.addForm);
console.log(para);
//axios传送数据
this.$http.put("/department", para).then(res => {
this.addLoading = false;
this.$message({
message: '提交成功',
type: 'success'
});
//验证重置
this.$refs['addForm'].resetFields();
this.addFormVisible = false;
this.getDepartments();
});
});
}
});
},
//显示编辑界面
handleEdit: function (index, row) {
//row表示修改这一行的数据
console.log(row);
this.editFormVisible = true;
//修改的数据放到表格中
this.editForm = Object.assign({}, row);
},
//编辑保存
editSubmit: function () {
this.$refs.editForm.validate((valid) => {
if (valid) {
this.$confirm('确认提交吗?', '提示', {}).then(() => {
this.editLoading = true;
let para = Object.assign({}, this.editForm);
//editUser(para).then((res) => {
//axios传输
this.$http.post("/department", para).then(res => {
this.editLoading = false;
this.$message({
message: '提交成功',
type: 'success'
});
//重置验证
this.$refs['editForm'].resetFields();
this.editFormVisible = false;
this.getDepartments();
});
});
}
})
},
//删除
handleDel: function (index, row) {
this.$confirm('确认删除该记录吗?', '提示', {
type: 'warning'
}).then(() => {
this.listLoading = true;
//para是是json对象,而字符串拼接是需要string的
let para = {id: row.id};
console.log(para);
//removeUser(para).then((res) => {
//删除进行拼接
this.$http.delete("/department/" + row.id).then(res => {
this.listLoading = false;
this.$message({
message: '删除成功',
type: 'success'
});
this.getDepartments();
});
}).catch(() => {
});
}
},
//获取用户列表
mounted() {
this.getDepartments();
}
}
</script>
<style scoped>
</style>
3前端访问后端
3.1 哪些情况下会存在跨域:(理解)
(1)同一个域名,不同的端口 --属于跨域 localhost:8080 --> localhost:80
(2)不同 域名 -- 属于跨域 192.168.0.1 192.168.0.2
(3) 二级域名不同 -- 属于跨域 miaosha.jd.com --> qianggou.jd.com
3.2 跨域问题:
浏览器(同源策略)针对ajax的请求, 如果访问的时候不同的域名,或者不同的端口, 存在跨域问题
同源策略:只允许 相同协议 相同域名 相同的端口
3.2跨域问题的解决
(1)jsonp–很早的
动态的构造的 标签
缺陷:
get请求/服务支持
(2)通过nginx (部署) – 解决跨域问题 – 反向代理机制
类似 中间商 ,把访问后台的请求 转换访问自己, 让那个nginx去访问后台,把结果那会,在转给前台
缺点:
部署服务,做配置
(3) CORS机制: 跨域资源共享"(Cross-origin resource sharing) "
解决 跨域问题 (浏览器有同源策略,(相同域名,相同的端口,相同协议),如果不是同源,存在跨域问题)
发送请求: 普通请求 发送一次,后台服务需要运行访问 …
特殊请求 发送二次, 第一次是预检请求, 服务器也要运行预检, 前台发现预检通过,在发送真实请求
, 真实请求也需要服务器允许
解决:都需要服务允许
方案一;
注解: 版本 spring版本 4.2.5 以后才支持注解
@CrossOrigin
方案二:
创建类
package cn.itsource.crud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
config.addAllowedOrigin("http://127.0.0.1:8080/");
config.addAllowedOrigin("http://localhost:8080/");
//2) 是否发送Cookie信息
config.setAllowCredentials(true);
//3) 允许的请求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允许的头信息
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new
UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
4.注意点
(1)后端分模块一定得配置好,包,版本号,配置文件,代码要一一对应
(2)前台访问后端发送请求restfull风格,注解尤其注意
(3)后端得crud
(4)前台访问后端跨域问题
a.使用注解(@CrossOrigin spring版本号改为4.2.5及以上)
b.配置相应得拦截类
(5)前台配置
1.去掉模拟数据
2.添加axios
3.配置路由
4.在相应界面进行crud