主要功能:对学生和专业进行增删改查
在数据库中创建学生表和专业表
create table admin(
id int primary key auto_increment,
account varchar(20) unique,
password varchar(20)
)
create table student(
id int primary key auto_increment,
num int unique,#不能重复
name varchar(10),
gender char(1),
birthday date,
phone varchar(15),
address varchar(30),
majorid int,
adminid int,
oper_time datetime
)
create table major(
id int primary key auto_increment,
name varchar(10),
adminid int,
oper_time datetime
)
1.创建学生student列表组件List.vue和专业major列表组件List.vue
学生列表
2.在index.js中导入路由,点击学生菜单会重新显示一个页面。如何在右边区域显示学生列表?
路由嵌套配置
import MajorList from "../views/major/List.vue";/* 学生专业组件 */
import StudentList from "../views/student/List.vue";/* 学生列表组件 */
/* 定义组件路由 */
var rout = new router({
routes: [{
path: '/login', //映射地址
name: 'login', //可以不写
component: Login
},
{
path: '/main',
component: Main,
children:[//在main组件下嵌套子路由
{
path: '/studentList',//地址
component: StudentList
},
{
path: '/majorList',
component: MajorList
}
]
}
]
});
3.在el-menu菜单上添加router;index里放studentList和majorList路由地址
//Main.vue中
操作菜单
专业管理
学生管理
1.来到学生列表组件之后,立即向后端发送一个http请求(get),去查询学生相关的数据.
发送请求到后端(包含token),过滤器验证token
学生列表
{{studentList}}
2.在后端对查询学生列表的这次请求进行处理。
创建一个StudentServlet,配置servlet。
创建学生StudentDao,定义一个方法查询所有的学生信息,将学生信息封装到一个List中返回即可.
package dao;
public class StudentDao {
public List students() throws ClassNotFoundException, SQLException {
Connection connection=null;
PreparedStatement ps=null;
List list=new ArrayList<>();
try{
Class.forName("com.mysql.cj.jdbc.Driver");//动态加载Driver类
String url="jdbc:mysql://127.0.0.1:3306/web_db?serverTimezone=Asia/Shanghai";
String uname="root";
String psd="123456";
//出现的异常都抛出去 不处理,抛给LoginServlet,因为LoginServlet负责和用户进行交互
connection= DriverManager.getConnection(url,uname,psd);
ps=connection.prepareStatement("select \n" +
"\ts.id,\n" +
"\ts.num,\n" +
"\ts.name,\n" +
"\ts.gender,\n" +
"\ts.birthday,\n" +
"\ts.phone,\n" +
"\ts.address,\n" +
"\tm.name mname,\n" +
"\ta.account,\n" +
"\ts.oper_time\n" +
"from student s left join major m on s.majorid=m.id\n" +
"\t\tleft join admin a on s.adminid=a.id");//登录是查询语句
ResultSet rs=ps.executeQuery();
while(rs.next()){
Student student=new Student();
student.setId(rs.getInt("id"));
student.setNum(rs.getInt("num"));
student.setName(rs.getString("name"));
student.setGender(rs.getString("gender"));
student.setBirthday(rs.getDate("birthday"));
student.setPhone(rs.getString("phone"));
student.setAddress(rs.getString("address"));
student.setmName(rs.getString("mname"));
student.setAccount(rs.getString("account"));
student.setOperTime(rs.getTimestamp("oper_time"));//年月日时分秒
list.add(student);
}
}finally {
if(connection!=null){//connection==null时,本来就是关闭的状态
connection.close();
}
if(ps!=null){
ps.close();
}
}
return list;
}
}
package model;
public class Student {
private int id;
private int num;
private String name;
private String gender;
private Date birthday;
private String phone;
private String address;
private String mName;//专业名称
private String account;//操作时间
private Date operTime;//操作时间
//get和set方法...
}
package Servlet;
public class StudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");//设置响应编码,在过滤器中设置
PrintWriter printWriter= resp.getWriter();//拿到响应的输出流对象
CommonResult commonResult=null;//后端向前端响应的是CommonResult
try{
StudentDao studentDao=new StudentDao();
List studentList=studentDao.students();
commonResult=new CommonResult(200,studentList,"查询成功");
}catch (Exception e){
e.printStackTrace();//打印异常信息
commonResult=new CommonResult(500,"系统忙");
}
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(commonResult);
printWriter.print(json);
}
}
studentServlet
servlet.StudentServlet
studentServlet
/back/student
3.使用elementUI数据表格组件渲染表格
prop和后端响应的对应,Student类中的属性对应,不是数据库中的;
data记得修改
编辑
删除
注意日期的格式化,在后端使用jackson组件提供的注解解决
//Student类中
//jackson组件中进行转换时的格式化标签,可以指定日期格式和时区
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date operTime;//操作时间
有多个get请求,但是后端只有一个doGet();通过传参(mark),在后端区别操作
删除时,注意弹框提示,删除更新列表this.$router.go();//重载当前组件,刷新
新增
编辑
删除
package Servlet;
public class StudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String mark=req.getParameter("mark");
if("list".equals(mark)){
findStudentList(req,resp);
}
if("delete".equals(mark)){
deleteStudent(req,resp);
}
}
private void deleteStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html;charset=utf-8");//设置响应编码
PrintWriter printWriter= resp.getWriter();//拿到响应的输出流对象
CommonResult commonResult=null;//后端向前端响应的是CommonResult
try{
String id=req.getParameter("id");
StudentDao studentDao=new StudentDao();
studentDao.deleteStudent(id);
commonResult=new CommonResult(200,"删除成功");
}catch (Exception e){
e.printStackTrace();//打印异常信息
commonResult=new CommonResult(500,"系统忙");
}
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(commonResult);
printWriter.print(json);
}
}
//StudentDao类中添加deleteStudent方法
//删除学生
public void deleteStudent(String id) throws ClassNotFoundException, SQLException {
Connection connection=null;
PreparedStatement ps=null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");//动态加载Driver类
String url="jdbc:mysql://127.0.0.1:3306/web_db?serverTimezone=Asia/Shanghai";
String uname="root";
String psd="123456";
connection= DriverManager.getConnection(url,uname,psd);
ps=connection.prepareStatement("delete from student where id=?");
ps.setObject(1,id);
ps.executeUpdate();
}finally {
if(connection!=null){//connection==null时,本来就是关闭的状态
connection.close();
}
if(ps!=null){
ps.close();
}
}
}
点击新增,打开对话框,制作对话框,在表单中输入内容,保存,向后端发送数据,后端接收数据,dao层保存数据,更新学生列表
1.点击新增按钮 打开对话框
由于新增修改内容比较多,建议把新增和修改单独放到一个组件中
2.在List.vue组件中导入Add组件,在父组件中调用子组件
3.创建学生表单,注意日期、单选框、专业课下拉框组件(数据需要动态加载)
v-model的值是对应
向后端发送请求,查询专业信息
男
女
一个学生管理中,可能有好几个get请求,但是一个servlet只有一个doGet()
package model;
public class Major {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//StudentDao类中添加方法majorList
public List majorList() throws ClassNotFoundException, SQLException {
Connection connection=null;
PreparedStatement ps=null;
List list=new ArrayList<>();
try{
Class.forName("com.mysql.cj.jdbc.Driver");//动态加载Driver类
String url="jdbc:mysql://127.0.0.1:3306/web_db?serverTimezone=Asia/Shanghai";
String uname="root";
String psd="123456";
//出现的异常都抛出去 不处理,抛给LoginServlet,因为LoginServlet负责和用户进行交互
connection= DriverManager.getConnection(url,uname,psd);
ps=connection.prepareStatement("select id,name from major");//登录是查询语句
ResultSet rs=ps.executeQuery();
while(rs.next()){
Major major=new Major();
major.setId(rs.getInt("id"));
major.setName(rs.getString("name"));
list.add(major);
}
}finally {
if(connection!=null){//connection==null时,本来就是关闭的状态
connection.close();
}
if(ps!=null){
ps.close();
}
}
return list;
}
//StudentServlet类中添加findMajorList方法
package Servlet;
public class StudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String mark=req.getParameter("mark");
if("list".equals(mark)){
findStudentList(req,resp);
}
if("delete".equals(mark)){
deleteStudent(req,resp);
}
if("major".equals(mark)){
findMajorList(req,resp);
}
}
private void findMajorList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html;charset=utf-8");//设置响应编码,可以在过滤器中设置
PrintWriter printWriter= resp.getWriter();//拿到响应的输出流对象
CommonResult commonResult=null;//后端向前端响应的是CommonResult
try{
StudentDao studentDao=new StudentDao();
List majorList=studentDao.majorList();
commonResult=new CommonResult(200,majorList,"查询成功");
}catch (Exception e){
e.printStackTrace();//打印异常信息
commonResult=new CommonResult(500,"系统忙");
}
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(commonResult);
printWriter.print(json);
}
}
点击保存按钮,提交学生信息,在后端servlet接收学生信息并保存到数据库中
前端将生日那部分添加 value-format="yyyy-MM-dd"
java代码
public class StudentServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String mark=req.getParameter("mark");
if("save".equals(mark)){
saveStudent(req,resp);
}
}
private void saveStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter printWriter= resp.getWriter();//拿到响应的输出流对象
CommonResult commonResult=null;//后端向前端响应的是CommonResult
try{
String id=req.getParameter("id");
String num=req.getParameter("num");
String name=req.getParameter("name");
String gender=req.getParameter("gender");
String birthday=req.getParameter("birthday");
String phone=req.getParameter("phone");
String address=req.getParameter("address");
String majorid=req.getParameter("majorid");//从token中获取当前登录人的id(请求头中)
String token=req.getHeader("adminToken");
DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);//解析token
Integer adminid=tokenInfo.getClaim("id").asInt();//获取到token中的管理员id
StudentDao studentDao=new StudentDao();
studentDao.updateStudent(id,num,name,gender,birthday,phone,address,majorid,adminid);
commonResult=new CommonResult(200,"修改学生成功");
}catch (Exception e){
e.printStackTrace();//打印异常信息
commonResult=new CommonResult(500,"系统忙");
}
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(commonResult);
printWriter.print(json);
}
}
//保存学生
public void saveStudent(String num, String name, String gender, String birthday, String phone, String address, String majorid, Integer adminid) throws SQLException {
Connection connection=null;
PreparedStatement ps=null;
try{
connection = JdbcUtil.getConnection();
ps=connection.prepareStatement("insert into student(num,name,gender,birthday,phone,address,majorid,adminid,oper_time) " +
"values(?,?,?,?,?,?,?,?,?)");//登录是查询语句
ps.setObject(1,num);
ps.setObject(2,name);
ps.setObject(3,gender);
ps.setObject(4,birthday);
ps.setObject(5,phone);
ps.setObject(6,address);
ps.setObject(7,majorid);
ps.setObject(8,adminid);
ps.setObject(9,new java.util.Date());
ps.executeUpdate();
}finally {
JdbcUtil.close(connection, ps);
}
}
拿到id—>后端查询学生信息(servlet,dao)—>把学生信息填充进去—>修改学生信息,保存—>提交到后端,修改学生信息
1.创建update.vue组件
男
女
在List.vue中导入updata组件
3.点击编辑,将修改学生的组件打开;
在父组件调用子组件,将id传过去
编辑
删除
methods: {
updateStudent(id) {
this.$refs.update.dialogFormVisible = true; //在父组件中调用子组件
this.$refs.update.getStudentByid(id);
}
}
methods: {//update.vue中,发送一个请求,通过id查询学生信息
getStudentByid(id) {
this.$http.get("back/student?mark=getStudentByid&id=" + id).then((resp) => {
if (resp.data.code == 200) {
}
})
}
}
4.通过id查询数据库中学生的信息
Student类中majorId是int类型
public class Student {
private int id;
private int num;
private String name;
private String gender;
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
private Date birthday;
private String phone;
private String address;
private String mName;//专业名称
private int majorId;//专业id
private String account;//操作人
//jackson组件中进行转换时的格式化标签,可以指定日期格式和时区
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date operTime;//操作时间
....
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String mark=req.getParameter("mark");
if("getStudentByid".equals(mark)){
getStudentByid(req,resp);
}
}
private void getStudentByid(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter printWriter= resp.getWriter();//拿到响应的输出流对象
CommonResult commonResult=null;//后端向前端响应的是CommonResult
try{
String id=req.getParameter("id");
StudentDao studentDao=new StudentDao();
Student student=studentDao.getStudentByid(id);
commonResult=new CommonResult(200,student,"通过id查找学生成功");
}catch (Exception e){
e.printStackTrace();//打印异常信息
commonResult=new CommonResult(500,"系统忙");
}
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(commonResult);
printWriter.print(json);
}
//不需要查询adminid和操作时间
public Student getStudentByid(String id) throws SQLException {
Connection connection=null;
PreparedStatement ps=null;
Student student=new Student();
try{
connection = JdbcUtil.getConnection();
ps=connection.prepareStatement("select id,num,name,gender,birthday,phone,address,majorid\n" +
"from student where id=?");//专业是查询marjorid
ps.setObject(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
student.setId(rs.getInt("id"));
student.setNum(rs.getInt("num"));
student.setName(rs.getString("name"));
student.setGender(rs.getString("gender"));
student.setBirthday(rs.getDate("birthday"));
student.setPhone(rs.getString("phone"));
student.setAddress(rs.getString("address"));
student.setMajorId(rs.getInt("majorid"));
}
}finally {
JdbcUtil.close(connection, ps);
}
return student;
}
5.把学生信息填充进去(id也需要)
methods: {
getStudentByid(id) {
this.$http.get("back/student?mark=getStudentByid&id=" + id).then((resp) => {
if (resp.data.code == 200) {
this.form.id = resp.data.data.id;
this.form.num = resp.data.data.num;
this.form.name = resp.data.data.name;
this.form.gender = resp.data.data.gender;
this.form.birthday = resp.data.data.birthday;
this.form.phone = resp.data.data.phone;
this.form.address = resp.data.data.address;
this.form.majorid = resp.data.data.majorId;
}
})
}
}
6.修改学生信息,保存
save() {
this.$http.post("back/student", jsonToString(this.form)).then((resp) => {
if (resp.data.code == 200) {
//提示
this.$message({
message: resp.data.message,
type: 'success'
});
this.dialogFormVisible = false; //关闭窗口
this.$router.go(); //更新当前列表
}
})
}
private void saveStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter printWriter= resp.getWriter();//拿到响应的输出流对象
CommonResult commonResult=null;//后端向前端响应的是CommonResult
try{
String id=req.getParameter("id");
String num=req.getParameter("num");
String name=req.getParameter("name");
String gender=req.getParameter("gender");
String birthday=req.getParameter("birthday");
String phone=req.getParameter("phone");
String address=req.getParameter("address");
String majorid=req.getParameter("majorid");//从token中获取当前登录人的id(请求头中)
String token=req.getHeader("adminToken");
DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);//解析token
Integer adminid=tokenInfo.getClaim("id").asInt();//获取到token中的管理员id
StudentDao studentDao=new StudentDao();
if(id==null){
studentDao.saveStudent(num,name,gender,birthday,phone,address,majorid,adminid);
commonResult=new CommonResult(200,"新增学生成功");
}else{
studentDao.updateStudent(id,num,name,gender,birthday,phone,address,majorid,adminid);
commonResult=new CommonResult(200,"修改学生成功");
}
}catch (Exception e){
e.printStackTrace();//打印异常信息
commonResult=new CommonResult(500,"系统忙");
}
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(commonResult);
printWriter.print(json);
}
public void updateStudent(String id,String num, String name, String gender, String birthday, String phone, String address, String majorid, Integer adminid) throws SQLException {
Connection connection=null;
PreparedStatement ps=null;
try{
connection = JdbcUtil.getConnection();
ps=connection.prepareStatement("update student set num=?,name=?,gender=?,birthday=?,phone=?,\n" +
"address=?,majorid=?,adminid=?,oper_time=? where id=?");
ps.setObject(1,num);
ps.setObject(2,name);
ps.setObject(3,gender);
ps.setObject(4,birthday);
ps.setObject(5,phone);
ps.setObject(6,address);
ps.setObject(7,majorid);
ps.setObject(8,adminid);
ps.setObject(9,new java.util.Date());
ps.setObject(10,id);
ps.executeUpdate();
}finally {
JdbcUtil.close(connection, ps);
}
}
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcUtil {
static String url="jdbc:mysql://127.0.0.1:3306/web_db?serverTimezone=Asia/Shanghai";
static String uname="root";
static String psd="123456";
//静态代码块,在类加载时自动执行,只执行一次
static{
try {
Class.forName("com.mysql.cj.jdbc.Driver");//动态加载Driver类
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取数据库链接对象
public static Connection getConnection() throws SQLException {
Connection connection= DriverManager.getConnection(url,uname,psd);
return connection;
}
//关闭数据库的链接
public static void close(Connection connection, PreparedStatement ps) throws SQLException {
if(connection!=null){//connection==null时,本来就是关闭的状态
connection.close();
}
if(ps!=null){
ps.close();
}
}
}
public void updateStudent(String id, String num, String name, String gender, String birthday, String phone, String address, String majorid, Integer adminid) throws ClassNotFoundException, SQLException {
Connection connection=null;
PreparedStatement ps=null;
try{
connection= JdbcUtil.getConnection();
ps=connection.prepareStatement("update student set num=?,name=?,gender=?,birthday=?,phone=?,\n" +
"address=?,majorid=?,adminid=?,oper_time=? where id=?");
ps.setObject(1,num);
ps.setObject(2,name);
ps.setObject(3,gender);
ps.setObject(4,birthday);
ps.setObject(5,phone);
ps.setObject(6,address);
ps.setObject(7,majorid);
ps.setObject(8,adminid);
ps.setObject(9,new java.util.Date());
ps.setObject(10,id);
ps.executeUpdate();
}finally {
JdbcUtil.close(connection,ps);
}
}