Vue高级+学生管理系统综合案例(页面)+Vue前后交互核心代码
这里写目录标题1、Vue 高级使用1.1、自定义组件1.2、Vue的生命周期1.3、Vue异步操作1.4、小结2、综合案例 学生管理系统2.1、效果环境的介绍2.2、登录功能的实现2.3、分页查询功能的实现2.4、添加功能的实现2.5、修改功能的实现2.6、删除功能的实现2.7 各项目代码分享1、Vue 高级使用1.1、自定义组件学完了 Element 组件后,我们会发现组件其实就是自定义的标签。
这里写目录标题
1、Vue 高级使用
1.1、自定义组件
-
学完了 Element 组件后,我们会发现组件其实就是自定义的标签。例如 就是对的封装。
-
本质上,组件是带有一个名字且可复用的 Vue 实例,我们完全可以自己定义。
-
定义格式
Vue.component(组件名称, {
props:组件的属性,
data: 组件的数据函数,
template: 组件解析的标签模板
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>自定义组件</title>
<script src="vue/vue.js"></script>
</head>
<body>
<div id="div">
<my-button>我的按钮</my-button>
</div>
</body>
<script>
Vue.component("my-button",{
// 属性
props:["style"],
// 数据函数
data: function(){
return{
msg:"我的按钮"
}
},
//解析标签模板
template:"<button style='color:red'>{{msg}}</button>"
});
new Vue({
el:"#div"
});
</script>
</html>
1.2、Vue的生命周期
生命周期
生命周期的八个阶段
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>生命周期</title>
<script src="vue/vue.js"></script>
</head>
<body>
<div id="app">
{{message}}
</div>
</body>
<script>
let vm = new Vue({
el: '#app',
data: {
message: 'Vue的生命周期'
},
beforeCreate: function() {
console.group('------beforeCreate创建前状态------');
console.log("%c%s", "color:red", "el : " + this.$el); //undefined
console.log("%c%s", "color:red", "data : " + this.$data); //undefined
console.log("%c%s", "color:red", "message: " + this.message);//undefined
},
created: function() {
console.group('------created创建完毕状态------');
console.log("%c%s", "color:red", "el : " + this.$el); //undefined
console.log("%c%s", "color:red", "data : " + this.$data); //已被初始化
console.log("%c%s", "color:red", "message: " + this.message); //已被初始化
},
beforeMount: function() {
console.group('------beforeMount挂载前状态------');
console.log("%c%s", "color:red", "el : " + (this.$el)); //已被初始化
console.log(this.$el);
console.log("%c%s", "color:red", "data : " + this.$data); //已被初始化
console.log("%c%s", "color:red", "message: " + this.message); //已被初始化
},
mounted: function() {
console.group('------mounted 挂载结束状态------');
console.log("%c%s", "color:red", "el : " + this.$el); //已被初始化
console.log(this.$el);
console.log("%c%s", "color:red", "data : " + this.$data); //已被初始化
console.log("%c%s", "color:red", "message: " + this.message); //已被初始化
},
beforeUpdate: function() {
console.group('beforeUpdate 更新前状态===============》');
let dom = document.getElementById("app").innerHTML;
console.log(dom);
console.log("%c%s", "color:red", "el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red", "data : " + this.$data);
console.log("%c%s", "color:red", "message: " + this.message);
},
updated: function() {
console.group('updated 更新完成状态===============》');
let dom = document.getElementById("app").innerHTML;
console.log(dom);
console.log("%c%s", "color:red", "el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red", "data : " + this.$data);
console.log("%c%s", "color:red", "message: " + this.message);
},
beforeDestroy: function() {
console.group('beforeDestroy 销毁前状态===============》');
console.log("%c%s", "color:red", "el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red", "data : " + this.$data);
console.log("%c%s", "color:red", "message: " + this.message);
},
destroyed: function() {
console.group('destroyed 销毁完成状态===============》');
console.log("%c%s", "color:red", "el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red", "data : " + this.$data);
console.log("%c%s", "color:red", "message: " + this.message);
}
});
// 销毁Vue对象
//vm.$destroy();
//vm.message = "hehe"; // 销毁后 Vue 实例会解绑所有内容
// 设置data中message数据值
vm.message = "good...";
</script>
</html>
挂载的时候,虚拟dom会赋值给页面
1.3、Vue异步操作
-
在Vue中发送异步请求,本质上还是AJAX。我们可以使用axios这个插件来简化操作!
-
使用步骤
1.引入axios核心js文件。
2.调用axios对象的方法来发起异步请求。
3.调用axios对象的方法来处理响应的数据。 -
axios常用方法
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>异步操作</title>
<script src="js/vue.js"></script>
<script src="js/axios-0.18.0.js"></script>
<style>
#users{
}
</style>
</head>
<body>
<div id="div">
{{name}}
<form>
姓名:<input type="text" v-model="name">
年龄:<input type="number" v-model="age">
<br><br><br>
<button type="button" @click="byGet()"> get方式发起请求</button>
<button type="button" @click="byPost()"> post方式发起请求</button>
</form>
<div id="users" v-for="user in users">
姓名:{{user.name}},年龄:{{user.age}},地址:{{user.address}}
</div>
</div>
</div>
</body>
<script>
new Vue({
el:"#div",
data:{
name:"张三",
age:0,
users:[]
},
methods:{
initUsres(){
axios.get("testServlet2").then(resp=>{
//获取所有的用户数据
this.users = resp.data;// [{"name":"",age:18,"address":""},{}]
}).catch(err =>{
alert(err);
})
},
byGet(){
/*get方式发送请求
get方式传参有两种方式
1:直接将参数拼接到请求地址路径后面 url?name1=value1&name2=value2 写法见send方法
2:见下
* */
axios.get("testServlet",{
params:{ //key:value 后台接收参数需要根据key来接收
"name":this.name,
"age":this.age
}
}).then(resp =>{ // resp是axios封装的一个响应对象,我们想要拿到后台返回的响应数据: resp.data
alert(resp.data);
}).catch(err =>{
alert(err);
});
},
byPost(){
/*post方式发送请求
第一个参数:请求的url
第二参数:传的是请求体数据
默认情况下:axios它是以application/json格式的数据传递到后台
如果第二个参数我们传的是一个对象/数组,在它的内部它会将我们传递的对象/数组转换成一个json格式的字符串
将这个json格式的字符串放入到请求体中发送到后台
后台收到的数据:"{'name':'李四','age':18}" 跟name=value这种形式是完全不一样的
这种形式在后台如何来获取对应的属性值呢?
后台应该拿到请求体数据(json字符串),将该json字符串转换成java中的对象
现在我就想发送post请求但是还是传递name=value形式的数据应该如何去做?
第二个参数我们传一个字符串就可以了,这个字符串满足name1=value1&name2=value2,我们自己需要做字符串拼接
* */
axios.post("testServlet",{
"name":this.name,
"age":this.age
}).then(resp=>{
alert(resp.data);
}).catch(err=>{
alert(err);
})
},
send(){
/*GET方式请求*/
axios.get("testServlet?name=" + this.name)
.then(resp => {
alert(resp.data);
})
.catch(error => {
alert(error);
})
// POST方式请求
axios.post("testServlet","name="+this.name+"&age="+this.age)
.then(resp => {
alert(resp.data);
})
.catch(error => {
alert(error);
})
}
},
created(){
this.initUsres();
}
});
</script>
</html>
- 后台代码
package com.itheima;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/testServlet2")
public class TestServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应的编码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//构建数据
List<User> users = new ArrayList<>();
users.add(new User("张三",19,"杭州"));
users.add(new User("李四",18,"北京"));
users.add(new User("万五",20,"上海"));
//将数据转换成json
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(users);
//将json数据写回客户端
resp.getWriter().write(json);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
User对象
package com.itheima;
/**
* Created by 传智播客*黑马程序员.
*/
public class User {
private String name;
private int age;
private String address;
public User() {
}
public User(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
1.4、小结
-
自定义组件:本质上,组件是带有一个名字且可复用的 Vue 实例,我们可以自己来定义。
Vue.component(组件名称, { props:组件的属性, data: 组件的数据函数, template: 组件解析的标签模板 })
-
生命周期:核心八个阶段
beforeCreate:创建前
created:创建后
beforeMount:载入前
mounted:载入后
beforeUpdate:更新前
updated:更新后
beforeDestroy:销毁前
destroyed:销毁后 -
异步操作:通过 axios 插件来实现。
2、综合案例 学生管理系统
2.1、效果环境的介绍
2.2、登录功能的实现
环境搭建
思路和理解:
前后端的一个交互,前端绑定一些事件,触发后执行异步函数,向后台传数据,后台接受到后通过MVC三层架构(controller service mapper),传到数据库中访问数据,进行判断,再返还给前端
接口是统一方法的格式
1.过滤器时刻监听是否登录,会判断Session域中有没有值,有就可以继续访问,没有会跳转到主页
2.登录的话,从前端传username,password 通过三层到数据库,找是否有对应的user,有就登录,同时Session域中存个值,没有就重定向到登录页面
3.查询功能,需要用到分页插件,前端给后台传指定方法名(method=selectByPage)的参数,包括当前页和每页显示条数,后台判断方法名,然后执行指定方法,通过数据库返还。然后赋值给当前页面。前端拿值通过resp.data拿到对应的值
4.增加功能:需要传拼接的参数(method=addStu)+学生参数给后台,后台拿到数据后,判断方法名,然后执行指定方法,这里参数比较多,通过BeanUtils.populate的方法把参数传入对象中,后台执行添加的sql语句,返回给Servlet,添加的时候日期需要格式转换下,在添加后需要加入一个请求去获取更新后的当前分页和每页显示的条数,这样就能看到实时更新的效果了。
5.修改功能:需要传入拼接的参数,method=updateStu 后面拼接具体参数加当前页和每页显示的条数到后台,后台拿到值后,通过方法名判断调用的方法,和上面同理,在运行后继续重新获取参数,添加
package com.itheima.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
检查登录
*/
@WebFilter(value = {"/index.html"})
public class LoginFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
try{
//1.将请求和响应对象转换为和HTTP协议相关
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//2.获取会话域对象中数据
Object username = request.getSession().getAttribute("username");
//3.判断用户名
if(username == null || "".equals(username)) {
//重定向到登录页面
response.sendRedirect(request.getContextPath() + "/login.html");
return;
}
//4.放行
filterChain.doFilter(request,response);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
}
}
登录功能实现
html
onSubmit(formName) {
// 为表单绑定验证功能
this.$refs[formName].validate((valid) => {
if (valid) {
//请求服务器完成登录功能
axios.post("userServlet","username=" + this.form.username + "&password=" + this.form.password)
.then(resp => {
if(resp.data == true) {
//登录成功,跳转到首页
location.href = "index.html";
}else {
//登录失败,跳转到登录页面
alert("登录失败,请检查用户名和密码");
location.href = "login.html";
}
})
} else {
return false;
}
});
}
java代码
- UserServlet.java
package com.itheima.controller;
import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
private UserService service = new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应编码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//1.获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//2.封装User对象
User user = new User(username,password);
//3.调用业务层的登录方法
List<User> list = service.login(user);
//4.判断是否查询出结果
if(list.size() != 0) {
//将用户名存入会话域当中
req.getSession().setAttribute("username",username);
//响应给客户端true
resp.getWriter().write("true");
}else {
//响应给客户端false
resp.getWriter().write("false");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
UserService.java
package com.itheima.service;
import com.itheima.bean.User;
import java.util.List;
/*
业务层约束接口
*/
public interface UserService {
/*
登录方法
*/
public abstract List<User> login(User user);
}
UserServiceImpl.java
package com.itheima.service.impl;
import com.itheima.bean.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserServiceImpl implements UserService {
@Override
public List<User> login(User user) {
InputStream is = null;
SqlSession sqlSession = null;
List<User> list = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过SqlSession工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//4.获取UserMapper接口的实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//5.调用实现类对象的登录方法
list = mapper.login(user);
}catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//7.返回结果到控制层
return list;
}
}
UserMapper.java
package com.itheima.mapper;
import com.itheima.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
/*
登录方法
*/
@Select("SELECT * FROM user WHERE username=#{username} AND password=#{password}")
public abstract List<User> login(User user);
}
2.3、分页查询功能的实现
html代码
<script>
new Vue({
el:"#div",
data:{
dialogTableVisible4add: false, //添加窗口显示状态
dialogTableVisible4edit: false, //编辑窗口显示状态
formData:{},//添加表单的数据
editFormData: {},//编辑表单的数据
tableData:[],//表格数据
pagination: {
currentPage: 1, //当前页
pageSize: 5, //每页显示条数
total: 0 //总条数
},
rules: {
number: [
{required: true, message: '请输入学号', trigger: 'blur'},
{min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
],
name: [
{required: true, message: '请输入姓名', trigger: 'blur'},
{min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
],
birthday: [
{required: true, message: '请选择日期', trigger: 'change'}
],
address: [
{required: true, message: '请输入地址', trigger: 'blur'},
{min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur'}
],
}
},
methods:{
//分页查询功能
selectByPage(){
axios.post("studentServlet","method=selectByPage¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize)
.then(resp => {
//将查询出的数据赋值tableData
this.tableData = resp.data.list;
//设置分页参数
//当前页
this.pagination.currentPage = resp.data.pageNum;
//总条数
this.pagination.total = resp.data.total;
})
},
//改变每页条数时执行的函数
handleSizeChange(pageSize) {
//修改分页查询的参数
this.pagination.pageSize = pageSize;
//重新执行查询
this.selectByPage();
},
//改变页码时执行的函数
handleCurrentChange(pageNum) {
//修改分页查询的参数
this.pagination.currentPage = pageNum;
//重新执行查询
this.selectByPage();
},
showAddStu() {
//弹出窗口
this.dialogTableVisible4add = true;
},
resetForm(addForm) {
//双向绑定,输入的数据都赋值给了formData, 清空formData数据
this.formData = {};
//清除表单的校验数据
this.$refs[addForm].resetFields();
},
showEditStu(row) {
//1. 弹出窗口
this.dialogTableVisible4edit = true;
//2. 显示表单数据
this.editFormData = {
number:row.number,
name:row.name,
birthday:row.birthday,
address:row.address,
}
}
},
mounted(){
//调用分页查询功能
this.selectByPage();
}
});
</script>
java代码
- 1、创建StudentServlet.java
package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.Student;
import com.itheima.service.StudentService;
import com.itheima.service.impl.StudentServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@WebServlet("/studentServlet")
public class StudentServlet extends HttpServlet {
private StudentService service = new StudentServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应编码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//1.获取方法名
String method = req.getParameter("method");
if(method.equals("selectByPage")) {
//分页查询功能
selectByPage(req,resp);
}
}
/*
分页查询功能
*/
private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
//获取请求参数
String currentPage = req.getParameter("currentPage");
String pageSize = req.getParameter("pageSize");
//调用业务层的查询方法
Page page = service.selectByPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
//封装PageInfo
PageInfo info = new PageInfo(page);
//将info转成json,响应给客户端
try {
String json = new ObjectMapper().writeValueAsString(info);
resp.getWriter().write(json);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
2、创建StudentService.java
package com.itheima.service;
import com.github.pagehelper.Page;
import com.itheima.bean.Student;
/*
学生业务层接口
*/
public interface StudentService {
/*
分页查询方法
*/
public abstract Page selectByPage(Integer currentPage, Integer pageSize);
}
3、创建StudentServiceImpl.java
package com.itheima.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.StudentService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/*
学生业务层实现类
*/
public class StudentServiceImpl implements StudentService {
/*
分页查询功能
*/
@Override
public Page selectByPage(Integer currentPage, Integer pageSize) {
InputStream is = null;
SqlSession sqlSession = null;
Page page = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过SqlSession工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//4.获取StudentMapper接口实现类对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.设置分页参数
page = PageHelper.startPage(currentPage,pageSize);
//6.调用实现类对象查询全部方法
mapper.selectAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
//7.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//8.返回结果到控制层
return page;
}
}
4、创建StudentMapper.java
package com.itheima.mapper;
import com.itheima.bean.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/*
学生持久层接口
*/
public interface StudentMapper {
/*
查询全部方法
*/
@Select("SELECT * FROM student")
public abstract List<Student> selectAll();
}
2.4、添加功能的实现
代码实现
-
html代码
在stuList.html中增加“添加功能”代码
//添加学生功能
addStu(){
let param = "method=addStu&number=" + this.formData.number + "&name=" + this.formData.name +
"&birthday=" + this.formData.birthday + "&address=" + this.formData.address +
"¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize;
axios.post("studentServlet",param)
.then(resp => {
//将查询出的数据赋值tableData
this.tableData = resp.data.list;
//设置分页参数
//当前页
this.pagination.currentPage = resp.data.pageNum;
//总条数
this.pagination.total = resp.data.total;
})
//关闭添加窗口
this.dialogTableVisible4add = false;
}
java代码
- 1、在StudentServlet.java中增加“添加功能”代码-addStu
/*
*1、直接复制会报错
*2、需要将此行代码需要添加到“doGet”方法中
*3、增加“addStu”方法名的判断
*/
else if(method.equals("addStu")) {
//添加数据功能
addStu(req,resp);
}
==================================================================================
/*
添加数据功能
*/
private void addStu(HttpServletRequest req, HttpServletResponse resp) {
//获取请求参数
Map<String, String[]> map = req.getParameterMap();
String currentPage = req.getParameter("currentPage");
String pageSize = req.getParameter("pageSize");
//封装Student对象
Student stu = new Student();
//注册日期转换器方法
dateConvert();
try {
BeanUtils.populate(stu,map);
} catch (Exception e) {
e.printStackTrace();
}
//调用业务层的添加方法
service.addStu(stu);
//重定向到分页查询功能
try {
resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage¤tPage=" + currentPage + "&pageSize=" + pageSize);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
日期转换
*/
private void dateConvert() {
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return simpleDateFormat.parse(value.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}, Date.class);
}
2、在StudentService.java中增加“添加功能”-addStu
/*
添加数据方法
*/
public abstract void addStu(Student stu);
3、StudentServiceImpl.java中增加“添加功能”-addStu
/*
添加数据方法
*/
@Override
public void addStu(Student stu) {
InputStream is = null;
SqlSession sqlSession = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过SqlSession工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//4.获取StudentMapper接口实现类对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.调用实现类对象添加方法
mapper.addStu(stu);
} catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4、StudentMapper.java中增加“添加功能”-addStu
/*
添加数据方法
*/
@Insert("INSERT INTO student VALUES (#{number},#{name},#{birthday},#{address})")
public abstract void addStu(Student stu);
2.5、修改功能的实现
代码实现
-
html代码
在stuList.html中增加“修改功能”代码
//修改数据功能
updateStu() {
let param = "method=updateStu&number=" + this.editFormData.number + "&name=" + this.editFormData.name +
"&birthday=" + this.editFormData.birthday + "&address=" + this.editFormData.address +
"¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize;
axios.post("studentServlet",param)
.then(resp => {
//将查询出的数据赋值tableData
this.tableData = resp.data.list;
//设置分页参数
//当前页
this.pagination.currentPage = resp.data.pageNum;
//总条数
this.pagination.total = resp.data.total;
})
//关闭编辑窗口
this.dialogTableVisible4edit = false;
}
java代码
- 1、在StudentServlet.java中增加“修改功能”-updateStu
/*
修改数据功能
*/
private void updateStu(HttpServletRequest req, HttpServletResponse resp) {
//获取请求参数
Map<String, String[]> map = req.getParameterMap();
String currentPage = req.getParameter("currentPage");
String pageSize = req.getParameter("pageSize");
//封装Student对象
Student stu = new Student();
//注册日期转换器方法
dateConvert();
try {
BeanUtils.populate(stu,map);
} catch (Exception e) {
e.printStackTrace();
}
//调用业务层的修改方法
service.updateStu(stu);
//重定向到分页查询功能
try {
resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage¤tPage=" + currentPage + "&pageSize=" + pageSize);
} catch (IOException e) {
e.printStackTrace();
}
}
2、在StudentService.java中增加“修改功能”-updateStu
/*
修改数据方法
*/
public abstract void updateStu(Student stu);
/*
*1、直接复制会报错
*2、需要将此行代码需要添加到“doGet”方法中
*3、增加“updateStu”方法名的判断
*/
else if(method.equals("updateStu")) {
//添加数据功能
updateStu(req,resp);
}
==================================================================================
/*
修改数据方法
*/
@Override
public void updateStu(Student stu) {
InputStream is = null;
SqlSession sqlSession = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过SqlSession工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//4.获取StudentMapper接口实现类对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.调用实现类对象修改方法
mapper.updateStu(stu);
} catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4、StudentMapper.java中增加“修改功能”-updateStu
/*
修改数据方法
*/
@Update("UPDATE student SET number=#{number},name=#{name},birthday=#{birthday},address=#{address} WHERE number=#{number}")
public abstract void updateStu(Student stu);
2.6、删除功能的实现
代码实现
-
html代码
在stuList.html中增加“删除功能”代码
//删除数据功能
deleteStu(row) {
if(confirm("确定要删除" + row.number + "数据?")) {
let param = "method=deleteStu&number=" + row.number +
"¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize;
axios.post("studentServlet",param)
.then(resp => {
//将查询出的数据赋值tableData
this.tableData = resp.data.list;
//设置分页参数
//当前页
this.pagination.currentPage = resp.data.pageNum;
//总条数
this.pagination.total = resp.data.total;
})
}
}
java代码
- 1、在StudentServlet.java中增加“删除功能”-
/*
*1、直接复制会报错
*2、需要将此行代码需要添加到“doGet”方法中
*3、增加“deleteStu”方法名的判断
*/
else if(method.equals("deleteStu")) {
//添加数据功能
deleteStu(req,resp);
}
==================================================================================
/*
删除数据功能
*/
private void deleteStu(HttpServletRequest req, HttpServletResponse resp) {
//获取请求参数
String number = req.getParameter("number");
String currentPage = req.getParameter("currentPage");
String pageSize = req.getParameter("pageSize");
//调用业务层的删除方法
service.deleteStu(number);
//重定向到分页查询功能
try {
resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage¤tPage=" + currentPage + "&pageSize=" + pageSize);
} catch (IOException e) {
e.printStackTrace();
}
}
2、在StudentService.java中增加“删除功能”-
/*
删除数据方法
*/
public abstract void deleteStu(String number);
3、StudentServiceImpl.java中增加“删除功能”-
/*
删除数据方法
*/
@Override
public void deleteStu(String number) {
InputStream is = null;
SqlSession sqlSession = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过SqlSession工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//4.获取StudentMapper接口实现类对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//5.调用实现类对象删除方法
mapper.deleteStu(number);
} catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4、StudentMapper.java中增加“删除功能”-
/*
删除数据方法
*/
@Delete("DELETE FROM student WHERE number=#{number}")
public abstract void deleteStu(String number);
2.7 各项目代码分享
StudentServlet
package com.itheima.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.Student;
import com.itheima.service.Impl.StudentServiceImpl;
import com.itheima.service.StudentService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String method = request.getParameter("method");
if (method.equals("selectByPage")){
selectByPage(request,response);
}else if (method.equals("addStu")){
addStu(request,response);
}else if (method.equals("updateStu")){
updateStu(request,response);
}else if (method.equals("deleteStu")){
deleteStu(request,response);
}
}
private void deleteStu(HttpServletRequest request, HttpServletResponse response) {
String number = request.getParameter("number");
studentService.deleteStu(number);
this.selectByPage(request,response);
}
private void updateStu(HttpServletRequest request, HttpServletResponse response) {
Map<String, String[]> parameterMap = request.getParameterMap();
Student student=new Student();
try {
BeanUtils.populate(student,parameterMap);
} catch (Exception e) {
e.printStackTrace();
};
studentService.updateStu(student);
this.selectByPage(request,response);
}
private void addStu(HttpServletRequest request, HttpServletResponse response) {
Map<String, String[]> parameterMap = request.getParameterMap();
Student student=new Student();
dateConvert();
try {
BeanUtils.populate(student,parameterMap);
} catch (Exception e) {
e.printStackTrace();
}
studentService.addStu(student);
this.selectByPage(request,response);
};
private void dateConvert() {
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return simpleDateFormat.parse(value.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}, Date.class);
}
private void selectByPage(HttpServletRequest request, HttpServletResponse response) {
String currentPage = request.getParameter("currentPage");
String pageSize = request.getParameter("pageSize");
Page page = studentService.selectByPage(Integer.parseInt(currentPage),Integer.parseInt(pageSize));
PageInfo pageInfo = new PageInfo(page);
try {
String json = new ObjectMapper().writeValueAsString(pageInfo);
response.getWriter().write(json);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
UserServlet
package com.itheima.controller;
import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.Impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User user=new User(username,password);
List<User> login = userService.login(user);
if (login.size()!=0){
request.getSession().setAttribute("username",username);
response.getWriter().write("true");
}else {
response.getWriter().write("false");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
StudentMapper
package com.itheima.mapper;
import com.itheima.bean.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface StudentMapper {
@Select("select * from student")
List<Student>selectAll();
@Insert("insert into student values (#{number},#{name},#{birthday},#{address})")
void addStu(Student stu);
// @Update("update student set number=#{number},name=#{name},birthday=#{birthday},address=#{address} where number=#{number}")
@Update("UPDATE student SET number=#{number},name=#{name},birthday=#{birthday},address=#{address} WHERE number=#{number}")
void update(Student stu);
@Delete("delete from student where number=#{number}")
void delete(String number);
}
UserMapper
package com.itheima.mapper;
import com.itheima.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("select * from user where username=#{username} and password=#{password}")
List<User>login(User user);
}
StudentServiceImpl
package com.itheima.service.Impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.bean.Student;
import com.itheima.bean.User;
import com.itheima.mapper.StudentMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.service.StudentService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class StudentServiceImpl implements StudentService {
@Override
public Page selectByPage(Integer currentPage, Integer pageSize) {
InputStream is = null;
SqlSession sqlSession = null;
Page page = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
sqlSession = build.openSession(true);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
page = PageHelper.startPage(currentPage, pageSize);
mapper.selectAll();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return page;
}
}
@Override
public void addStu(Student stu) {
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
sqlSession = build.openSession(true);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.addStu(stu);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void update(Student stu) {
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
sqlSession = build.openSession(true);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.update(stu);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void delete(String number) {
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
sqlSession = build.openSession(true);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.delete(number);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
UserServiceImpl
package com.itheima.service.Impl;
import com.itheima.bean.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserServiceImpl implements UserService {
InputStream is = null;
SqlSession sqlSession = null;
List<User> login = null;
@Override
public List<User> login(User user) {
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
sqlSession = build.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
login = mapper.login(user);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return login;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生管理系统</title>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<style>
.el-header{
background-color: #545c64;
}
.header-img{
width: 100px;
margin-top:20px;
}
</style>
</head>
<body>
<div id="div">
<el-container>
<!-- 头部-->
<el-header class="el-header">
<el-container>
<div>
<el-image src="img/export.png" class="header-img"></el-image>
</div>
<el-menu
:default-active="activeIndex2"
mode="horizontal"
@select="handleSelect"
background-color="#545c64"
text-color="white"
active-text-color="#ffd04b"
style="margin-left: auto;">
<el-menu-item index="1">处理中心</el-menu-item>
<el-submenu index="2">
<template slot="title">我的工作台</template>
<el-menu-item index="2-1">选项1</el-menu-item>
<el-menu-item index="2-2">选项2</el-menu-item>
<el-menu-item index="2-3">选项3</el-menu-item>
</el-submenu>
<el-menu-item index="3"><a href="index.html" target="_self">首页</a></el-menu-item>
</el-menu>
</el-container>
</el-header>
<!-- 中间部分 -->
<el-container style="height: 580px; border: 1px solid #eee">
<!-- 侧边栏 -->
<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
<el-menu :default-openeds="['1']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-menu"></i>学工部</template>
<el-menu-item-group>
<el-menu-item index="1-1" @click="findAll"><i class="el-icon-help"></i>在校学生管理</el-menu-item>
<el-menu-item index="1-2"><i class="el-icon-help"></i>学生升级/留级</el-menu-item>
<el-menu-item index="1-3"><i class="el-icon-help"></i>学生就业情况</el-menu-item>
</el-menu-item-group>
</el-submenu>
<el-submenu index="2">
<template slot="title"><i class="el-icon-menu"></i>咨询部</template>
<el-menu-item-group>
<el-menu-item index="2-1"><i class="el-icon-help"></i>意向学生管理</el-menu-item>
<el-menu-item index="2-2"><i class="el-icon-help"></i>未报名学生管理</el-menu-item>
<el-menu-item index="2-3"><i class="el-icon-help"></i>已报名学生管理</el-menu-item>
</el-menu-item-group>
</el-submenu>
<el-submenu index="3">
<template slot="title"><i class="el-icon-menu"></i>教研部</template>
<el-menu-item-group>
<el-menu-item index="3-1"><i class="el-icon-help"></i>已有课程管理</el-menu-item>
<el-menu-item index="3-2"><i class="el-icon-help"></i>正在研发课程管理</el-menu-item>
<el-menu-item index="3-3"><i class="el-icon-help"></i>新技术课程管理</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<!-- 主区域部分 -->
<el-main>
<iframe :src="iframeSrc" frameborder="false" style="top:80px;left: 120px; width: 100%;height:500px"></iframe>
</el-main>
</el-container>
</el-container>
</el-container>
</div>
</body>
<script>
new Vue({
el:"#div",
data: {
iframeSrc: "manager.html"
},
methods:{
findAll:function () {
this.iframeSrc = "stuList.html"
}
}
});
</script>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script src="js/vue.js" type="text/javascript"></script>
<script src="js/axios-0.18.0.js" type="text/javascript"></script>
<script src="element-ui/lib/index.js"></script>
<style lang="scss" scoped>
.login-box {
border: 1px solid #DCDFE6;
width: 350px;
margin: 120px auto;
padding: 35px 35px 15px 35px;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
box-shadow: 0 0 25px #909399;
}
.login-title {
text-align: center;
margin: 0 auto 40px auto;
color: #303133;
}
</style>
</head>
<body>
<div id="app">
<el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
<h3 class="login-title">欢迎登录</h3>
<el-form-item label="账号" prop="username">
<el-input type="text" placeholder="请输入账号" v-model="form.username"/>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input type="password" placeholder="请输入密码" v-model="form.password"/>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="onSubmit('loginForm')">登录</el-button>
</el-form-item>
</el-form>
</div>
</body>
<script>
new Vue({
el:"#app",
data: {
form: {
username: '',
password: '',
},
rules: { //校验规则
username: [
{required: true, message: '请输入用户名', trigger: 'blur'}
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'}
]
}
},
methods: {
onSubmit(formName) {
// 为表单绑定验证功能
this.$refs[formName].validate((valid) => {
if (valid) {
//请求服务器完成登录功能
axios.post("UserServlet","username="+this.form.username+"&password="+this.form.password).then(
resp=>{
if (resp.data==true){
location.href="index.html"
}else {
alert("登录失败,用户名密码错了,瘪三")
location.href="login.html"
}
}
)
} else {
return false;
}
});
}
}
});
</script>
</html>
manger.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p style="font-size: 35px">欢迎来到学生管理系统~~~</p>
</body>
</html>
stuList.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生管理系统</title>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<script src="js/axios-0.18.0.js"></script>
</head>
<body>
<div id="div">
<b style="color: red; font-size: 20px;">学生列表</b>
<div style="float: right;">
<el-button type="primary" @click="showAddStu">添加学生</el-button>
</div>
<el-table :data="tableData">
<el-table-column prop="number" label="学号" width="120">
</el-table-column>
<el-table-column prop="name" label="姓名" width="120">
</el-table-column>
<el-table-column prop="birthday" label="生日" width="140">
</el-table-column>
<el-table-column prop="address" label="地址">
</el-table-column>
<el-table-column label="操作" width="180">
<template slot-scope="props">
<el-button type="warning" @click="showEditStu(props.row)">编辑</el-button>
<el-button type="danger" @click="deleteStu(props.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!--
分页组件
@size-change: 当改变每页条数时触发的函数
@current-change:当改变页码时触发的函数
current-page :默认的页码
:page-sizes:每页条数选择框中显示的值
:page-size : 默认的每页条数
layout: 分页组件的布局
total(总条数), sizes(每页条数), prev(上一页), pager(所有的页码), next(下一页), jumper(跳转页码)
:total: 总条数
-->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pagination.currentPage"
:page-sizes="[3,5,8]"
:page-size="pagination.pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="pagination.total">
</el-pagination>
<el-dialog title="添加学生信息" :visible.sync="dialogTableVisible4add" @close="resetForm('addForm')">
<!--
:model="formData": 关联数据
:rules: 关联校验规则
ref: 在获取表单对象时使用
-->
<el-form :model="formData" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="学生学号" prop="number">
<el-input v-model="formData.number"></el-input>
</el-form-item>
<el-form-item label="学生姓名" prop="name">
<el-input v-model="formData.name"></el-input>
</el-form-item>
<el-form-item label="学生生日" prop="birthday">
<!--v-model : 双向绑定 -->
<el-input v-model="formData.birthday" type="date"></el-input>
</el-form-item>
<el-form-item label="学生地址" prop="address">
<el-input v-model="formData.address"></el-input>
</el-form-item>
<el-form-item align="right">
<el-button type="primary" @click="addStu()">添加</el-button>
<el-button @click="resetForm('addForm')">重置</el-button>
</el-form-item>
</el-form>
</el-dialog>
<el-dialog title="编辑学生信息" :visible.sync="dialogTableVisible4edit" @close="resetForm('editForm')">
<!--
:model="formData": 关联数据
:rules: 关联校验规则
ref: 在获取表单对象时使用
-->
<el-form :model="editFormData" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="学生学号" prop="number">
<el-input v-model="editFormData.number"></el-input>
</el-form-item>
<el-form-item label="学生姓名" prop="name">
<el-input v-model="editFormData.name"></el-input>
</el-form-item>
<el-form-item label="学生生日" prop="birthday">
<!--v-model : 双向绑定 -->
<el-input v-model="editFormData.birthday" type="date"></el-input>
</el-form-item>
<el-form-item label="学生地址" prop="address">
<el-input v-model="editFormData.address"></el-input>
</el-form-item>
<el-form-item align="right">
<el-button type="warning" @click="updateStu()">修改</el-button>
</el-form-item>
</el-form>
</el-dialog>
</div>
</body>
<script>
// import ro from "./element-ui/src/locale/lang/ro";
new Vue({
el: "#div",
data: {
dialogTableVisible4add: false, //添加窗口显示状态
dialogTableVisible4edit: false, //编辑窗口显示状态
formData: {},//添加表单的数据
editFormData: {},//编辑表单的数据
tableData: [],//表格数据
pagination: {
currentPage: 1, //当前页
pageSize: 5, //每页显示条数
total: 0 //总条数
},
rules: {
number: [
{required: true, message: '请输入学号', trigger: 'blur'},
{min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
],
name: [
{required: true, message: '请输入姓名', trigger: 'blur'},
{min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
],
birthday: [
{required: true, message: '请选择日期', trigger: 'change'}
],
address: [
{required: true, message: '请输入地址', trigger: 'blur'},
{min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur'}
],
}
},
methods: {
selectByPage() {
axios.post("StudentServlet", "method=selectByPage¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize).then(resp => {
this.tableData = resp.data.list;
this.pagination.currentPage = resp.data.pageNum;
this.pagination.total = resp.data.total;
});
},
addStu() {
axios.post("StudentServlet", "method=addStu&number=" + this.formData.number + "&name=" + this.formData.name +
"&birthday=" + this.formData.birthday + "&address=" + this.formData.address +
"¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize).then(resp => {
this.tableData = resp.data.list;
this.pagination.currentPage = resp.data.pageNum;
this.pagination.total = resp.data.total;
});
this.dialogTableVisible4add = false;
},
updateStu() {
axios.post("StudentServlet", "method=updateStu&number=" + this.editFormData.number + "&name=" + this.editFormData.name +
"&birthday=" + this.editFormData.birthday + "&address=" + this.editFormData.address +
"¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize).then(resp => {
this.tableData = resp.data.list;
this.pagination.currentPage = resp.data.pageNum;
this.pagination.total = resp.data.total;
});
this.dialogTableVisible4edit = false;
},
deleteStu(row) {
if (confirm("你真的要删除" + row.number + "这么可爱的数据吗?")) {
axios.post("StudentServlet", "method=deleteStu&number=" + row.number + "¤tPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize)
.then(resp => {
this.tableData = resp.data.list;
this.pagination.currentPage = resp.data.pageNum;
this.pagination.total = resp.data.total;
})
}
},
//改变每页条数时执行的函数
handleSizeChange(pageSize) {
//修改分页查询的参数
this.pagination.pageSize = pageSize;
//重新执行查询
this.selectByPage();
},
//改变页码时执行的函数
handleCurrentChange(pageNum) {
//修改分页查询的参数
this.pagination.currentPage = pageNum;
//重新执行查询
this.selectByPage();
},
showAddStu() {
//弹出窗口
this.dialogTableVisible4add = true;
},
resetForm(addForm) {
//双向绑定,输入的数据都赋值给了formData, 清空formData数据
this.formData = {};
//清除表单的校验数据
this.$refs[addForm].resetFields();
},
showEditStu(row) {
//1. 弹出窗口
this.dialogTableVisible4edit = true;
//2. 显示表单数据
this.editFormData = {
number: row.number,
name: row.name,
birthday: row.birthday,
address: row.address,
}
}
},
created() {
this.selectByPage();
}
});
</script>
</html>
Vue前后交互
新增和查询
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script src="vue/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<script src="vue/axios-0.18.0.js"></script>
</head>
<body>
<div id="app">
<el-row>
<el-button type="primary" round @click="dialogVisible = true">新增</el-button>
</el-row>
<template>
<el-table
:data="tableData"
style="width: 100%">
<el-table-column
prop="pname"
label="商品名称"
width="180">
</el-table-column>
<el-table-column
prop="market_price"
label="市场价格"
width="180">
</el-table-column>
<el-table-column
prop="shop_price"
label="活动价格">
</el-table-column>
<el-table-column
prop="pdesc"
label="描述">
</el-table-column>
</el-table>
<el-pagination
class="pagiantion"
@current-change="handleCurrentChange"
:current-page="pagination.currentPage"
:page-size="pagination.pageSize"
layout="total, prev, pager, next, jumper"
:total="pagination.total">
</el-pagination>
</template>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
<el-form ref="form" :model="product" label-width="80px">
<el-form-item label="商品名称">
<el-input v-model="product.pname"></el-input>
</el-form-item>
<el-form-item label="市场价格">
<el-input v-model="product.market_price"></el-input>
</el-form-item>
<el-form-item label="活动价格">
<el-input v-model="product.shop_price"></el-input>
</el-form-item>
<el-form-item label="商品描述">
<el-input
type="textarea"
:rows="2"
placeholder="请输入内容"
v-model="product.pdesc">
</el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="save()">确 定</el-button>
</span>
</el-dialog>
</div>
</body>
<script>
new Vue({
el:"#app",
data:{
dialogVisible:false,
tableData:[],
pagination:{
currentPage:1,
pageSize:10,
total:0
},
product:{
pname:"",
market_price:"",
shop_price:"",
pdesc:""
}
},
methods:{
findPage:function () {
axios.get("product?operation=page&pageNum="+this.pagination.currentPage+"&pageSize="+this.pagination.pageSize).then(resp =>{
// resp.data == PageInfo
this.tableData = resp.data.list;
this.pagination.total = resp.data.total;
})
},
save:function () {
let params = "operation=save&pname="+this.product.pname+"&market_price="+this.product.market_price+"&shop_price="+this.product.shop_price
+"&pdesc="+this.product.pdesc;
axios.post("product",params).then(resp =>{
//刷新页面
this.findPage();
this.dialogVisible = false;
});
}
},
created(){
this.findPage();
},
mounted(){
}
});
</script>
</html>
用户登录
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script src="vue/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<script src="vue/axios-0.18.0.js"></script>
</head>
<body>
<div id="app">
<el-form ref="form" :model="form" label-width="80px">
<el-form-item label="登陆名">
<el-input v-model="user.username"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input placeholder="请输入密码" v-model="user.password" show-password></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="login">登陆</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
</div>
</body>
<script>
new Vue({
el:"#app",
data:{
user:{
username:"",
password:""
}
},
methods:{
login:function () {
let params = "operation=login&username="+this.user.username+"&password="+this.user.password;
axios.post("user",params).then(resp =>{
if(resp.data == true){
location.href ="index.html";
}
});
}
},
created(){
}
})
</script>
</html>
更多推荐
所有评论(0)