11月26日
任务三:
因为JFinal主要的功能作用还是体现在网站的后端搭建上以及对数据库的CRUD操作上面,所以因为个人编写web网页的习惯,选择了vue+element-ui+JFinal+mysql的技术架构去完成这个任务。
首先一个简单的学生信息管理系统,我们主要涉及到两个表,一个是登录表,一个是学生信息表,所以在JFinal架构中创建Model文件夹创建两个java文件,分别是login和student对应mysql中的login和student表(mysql建表这块这里不再详细赘述)。
代码如下:
package models;
import com.jfinal.plugin.activerecord.Model;
public class login extends Model<login> {
public static final login dao = new
login().dao();
public login getUserById(String
username) {
return
login.dao.findFirst("select * from login where username = ?",
username);
}
public String getPassword(login
login)
{
return
login.getStr("password");
}
}
package
models;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
public class student extends Model<student> {
public static final student dao = new
student().dao();
public Page<student>
paginate(int pageNumber, int pageSize) {
return super.paginate(pageNumber,
pageSize, "select *", "from student");
}
}
然后在DemoConfig中完成JFinal所需要的一些基本约定配置。代码如下:
package config;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import controller.HelloController;
import controller.LoginController;
import controller.StudentController;
import controller.TranslateController;
import models.login;
import models.student;
public class DemoConfig extends JFinalConfig {
@Override
public void configConstant(Constants
constants) {
//开启开发模式
constants.setDevMode(true);
PropKit.use("config.properties");
}
@Override
public void configRoute(Routes
routes) {
routes.add("/hello",
HelloController.class);
routes.add("/login",
LoginController.class);
routes.add("/student",
StudentController.class);
routes.add("/add",
StudentController.class,"/student");
routes.add("/query",
StudentController.class,"/student");
routes.add("/list",
StudentController.class, "/student");
routes.add("/drop",
StudentController.class, "/student");
routes.add("/update",
StudentController.class, "/student");
routes.add("/translate", TranslateController.class);
}
@Override
public void configEngine(Engine
engine) {
}
@Override
public void configPlugin(Plugins
plugins) {
// 使用配置文件中的属性来配置DruidPlugin
DruidPlugin dp = new
DruidPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"),
PropKit.get("password").trim());
plugins.add(dp);
// 配置ActiveRecordPlugin
ActiveRecordPlugin arp = new
ActiveRecordPlugin(dp);
plugins.add(arp);
// 映射数据库表到Model
arp.addMapping("login",
login.class);
arp.addMapping("student",
student.class);
}
@Override
public void
configInterceptor(Interceptors interceptors) {
interceptors.add(new
Interceptor() {
@Override
public void
intercept(Invocation inv) {
Controller controller =
inv.getController();
controller.getResponse().addHeader("Access-Control-Allow-Origin",
"http://localhost:8080");
controller.getResponse().addHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS");
controller.getResponse().addHeader("Access-Control-Allow-Headers",
"Content-Type, x-requested-with");
controller.getResponse().addHeader("Access-Control-Allow-Credentials",
"true");
if
("OPTIONS".equals(controller.getRequest().getMethod())) {
controller.renderNull(); // 对于OPTIONS请求,直接返回null
} else {
inv.invoke();
}
}
});
}
@Override
public void configHandler(Handlers
handlers) {
}
}
然后编写两个控制类,分别是loginController和studentController,在其中编写相关的后端处理逻辑。代码如下:
package controller;
import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import models.login;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
public class LoginController extends Controller {
public void index() {
boolean result = false;
// 获取HttpServletRequest对象
HttpServletRequest request =
getRequest();
// 从请求中获取JSON字符串
StringBuilder jsonStringBuilder =
new StringBuilder();
String line;
try {
BufferedReader reader =
request.getReader();
while ((line =
reader.readLine()) != null) {
jsonStringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String json =
jsonStringBuilder.toString();
// 使用Fastjson解析JSON字符串
JSONObject jsonObject =
JSON.parseObject(json);
// 从JSONObject对象中获取username和password
String username =
jsonObject.getString("username");
String password =
jsonObject.getString("password");
login login = new
login().getUserById(username);
if(login!=null){
if
(password.equals(login.getPassword(login))){
result = true;
}
}
renderJson(result);
}
}
package controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import models.student;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
public class StudentController extends Controller {
public JSONObject getPara1() {
// 获取HttpServletRequest对象
HttpServletRequest request =
getRequest();
// 从请求中获取JSON字符串
StringBuilder jsonStringBuilder =
new StringBuilder();
String line;
try {
BufferedReader reader =
request.getReader();
while ((line =
reader.readLine()) != null) {
jsonStringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String json =
jsonStringBuilder.toString();
// 使用Fastjson解析JSON字符串
JSONObject jsonObject =
JSON.parseObject(json);
return jsonObject;
}
public void add()
{
boolean result=false;
JSONObject jsonObject=
getPara1();
// 从JSONObject对象中获取username和password
String stuid =
jsonObject.getString("stuid");
String stuname =
jsonObject.getString("stuname");
String stusex =
jsonObject.getString("stusex");
String stuclass =
jsonObject.getString("stuclass");
String stuage =
jsonObject.getString("stuage");
// 查询条件
String sql = "SELECT * FROM
student WHERE stuid = ?";
// 执行查询
student existingStudent =
student.dao.findFirst(sql, stuid);
if (existingStudent == null) {
student student=new
student();
student.set("stuid",stuid);
student.set("stuname",stuname);
student.set("stusex",stusex);
student.set("stuclass",stuclass);
student.set("stuage",stuage);
// 如果学生不存在,则保存新的学生信息
result = student.save();
}
renderJson(result);
}
public void query()
{
StringBuilder sql = new
StringBuilder("SELECT * FROM student");
List<student> students =
null;
JSONObject jsonObject=
getPara1();
// 从JSONObject对象中获取username和password
String stuid =
jsonObject.getString("stuid");
String stuname =
jsonObject.getString("stuname");
String stuclass =
jsonObject.getString("stuclass");
if (stuid != null &&
!stuid.isEmpty()) {
sql.append(" WHERE stuid
LIKE '%").append(stuid).append("%'");
}
if (stuname != null &&
!stuname.isEmpty()) {
if
(sql.indexOf("WHERE") != -1) {
sql.append(" AND
stuname LIKE '%").append(stuname).append("%'");
} else {
sql.append(" WHERE
stuname LIKE '%").append(stuname).append("%'");
}
}
if (stuclass != null &&
!stuclass.isEmpty()) {
if
(sql.indexOf("WHERE") != -1) {
sql.append(" AND
stuclass LIKE '%").append(stuclass).append("%'");
} else {
sql.append(" WHERE
stuclass LIKE '%").append(stuclass).append("%'");
}
}
students =
student.dao.find(sql.toString());
renderJson(students);
}
public void list()
{
JSONObject jsonObject=
getPara1();
Integer pageNumber =
jsonObject.getInteger("page");
Integer pageSize =
jsonObject.getInteger("size");
System.out.println(pageNumber);
System.out.println(pageSize);
student student = new student();
System.out.println(student.paginate(pageNumber, pageSize));
renderJson(student.paginate(pageNumber, pageSize));
}
public void drop()
{
boolean result=false;
JSONObject jsonObject=
getPara1();
String stuid =
jsonObject.getString("stuid");
if (stuid != null &&
!stuid.isEmpty()) {
// 构建删除条件
String sql = "DELETE
FROM student WHERE stuid = ?";
// 执行删除操作
int rowsAffected = Db.update(sql,
stuid);
if (rowsAffected > 0) {
result=true;
renderJson(result);
} else {
renderJson(result);
}
} else {
renderJson(result);
}
}
public void update()
{
JSONObject jsonObject=
getPara1();
String stuid =
jsonObject.getString("stuid");
String stuname =
jsonObject.getString("stuname");
String stusex =
jsonObject.getString("stusex");
String stuclass =
jsonObject.getString("stuclass");
String stuage =
jsonObject.getString("stuage");
String updateSql = "UPDATE
student SET stuname = ?, stusex = ?, stuclass = ?, stuage = ? WHERE stuid =
?";
int updated1 =
Db.update(updateSql, stuname, stusex, stuclass, stuage, stuid);
boolean updated = updated1 >
0;
renderJson(updated);
}
}
到这一步所有有关后端的工作结束。接下来是前端代码有关vue的部分。
Vue部分相关编写就是两个页面,一个登录页面,一个是信息管理页面。代码如下:
<script>
export default {
data() {
return {
stuf:
{
username: '',
password: '',
},
};
},
methods: {
submitForm() {
this.$axios.post('http://localhost:8090/login',this.stuf).then(res=>res.data).then(res=>
{
console.log(res)
if(res)
{
alert("登录成功");
this.$router.replace({ name: 'student'
});
}else {
alert("登录失败");
}
}).catch(error=> {
console.log(error)
alert("登录失败")
});
}
},
}
</script>
<template>
<body>
<div class="Box">
<div class="left">
<div
class="centerBox">
<img src="../assets/logo1.png"
alt="">
<h4>学生信息管理系统</h4>
<p>Student Information
Management System</p>
</div>
</div>
<div class="right">
<el-form>
<h3>欢迎登录</h3>
<input type="text"
placeholder="学号"
required v-model="stuf.username">
<input
type="password" placeholder="密码" required v-model="stuf.password">
<el-button
type="primary" class="loginBtn"
@click="submitForm">登录</el-button>
</el-form>
</div>
</div>
</body>
</template>
<style scoped>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background: aquamarine
url("../assets/back.png") no-repeat;
background-size: cover;
}
.Box {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 550px;
height: 330px;
display: flex;
}
.left {
position: relative;
width: 50%;
height: 100%;
background-color: rgba(57, 99, 134,
0.75);
}
.right {
position: relative;
width: 50%;
height: 100%;
background-color: rgba(255, 255, 255,
1);
}
.centerBox {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80%;
text-align: center;
}
.left img {
width: 50px;
height: 50px;
margin-bottom: 5px;
}
.left p {
font-size: 14px;
color: #fff;
}
.left h4 {
font-size: 18px;
color: #fff;
margin-bottom: 10px;
}
.right form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80%;
text-align: center;
}
h3 {
margin-bottom: 20px;
}
input {
width: 100%;
height: 30px;
border: 1px solid #767676;
background-color: transparent;
padding-left: 10px;
font-size: 12px;
color: #000000;
margin-bottom: 15px;
outline: none;
}
.loginBtn {
width: 100%;
height: 35px;
line-height: 32px;
text-align: center;
font-size: 15px;
color: #fff;
border-radius: 6px;
background: rgb(57, 99, 134);
outline: none;
border: none;
margin-top: 10px;
}
.no {
cursor: pointer;
margin-top: 30px;
text-align: center;
font-size: 12px;
color: #828282;
}
</style>
<script>
export default {
name:"studentManager",
data()
{
return{
queryData:
{
stuid:'',
stuname:'',
stuclass:'',
},
tableData:[],
pagination: {
totalRow: 0,
totalPage: 0,
currentPage: 1, // 当前页码
pageSize: 10 // 每页显示的条目数
},
centerDialogVisible:false,
centerDialogVisible1:false,
form:
{
stuid:'',
stuname:'',
stuclass:'',
stusex:'',
stuage:'',
stupassword: ''
}
}
},
methods:{
query0()
{
this.$axios.post('http://localhost:8090/student/query',this.queryData).then(res=>res.data).then(res=>
{
this.tableData=res;
}).catch(error=>
{
console.error(error);
alert("查询失败");
})
},
add()
{
this.centerDialogVisible1=true;
},
update(row)
{
this.centerDialogVisible=true;
this.form.stuid=row.stuid;
this.form.stuname=row.stuname;
this.form.stusex=row.stusex;
this.form.stuclass=row.stuclass;
this.form.stuage=row.stuage;
},
drop(row)
{
this.$axios.post('http://localhost:8090/student/drop',row).then(res=>res.data).then(res=>
{
if(res===true)
{
alert("删除成功");
location.reload();
}
else alert("删除失败");
}).catch(error=>
{
console.error(error);
alert("删除失败");
})
},
false1()
{
this.centerDialogVisible=false;
this.centerDialogVisible1=false;
this.form=
{
stuid:'',
stuname:'',
stuclass:'',
stusex:'',
stuage:'',
}
},
save()
{
this.$axios.post('http://localhost:8090/student/add',
this.form).then(res=>res.data).then(res=>
{
if(res===true)
{
alert("添加成功");
location.reload();
}
else alert("添加失败");
this.false1();
}).catch(error=>
{
console.error(error);
alert("添加失败");
this.false1();
})
},
save1()
{
this.$axios.post('http://localhost:8090/student/update',
this.form).then(res=>res.data).then(res=>
{
if(res===true) {
alert("修改成功");
location.reload();
}
else alert("修改失败")
this.false1();
}).catch(error=>
{
console.error(error);
alert("修改失败");
this.false1();
})
},
handleSizeChange(val) {
this.pagination.pageSize = val;
this.pagination.currentPage = 1; //
重置为第一页
this.beforeMount(); // 重新发起请求
},
handleCurrentChange(val) {
this.pagination.currentPage = val;
this.beforeMount(); // 重新发起请求
},
},
beforeMount() {
this.queryData.page =
this.pagination.currentPage;
this.queryData.size =
this.pagination.pageSize;
this.$axios.post('http://localhost:8090/student/list',this.queryData).then(res
=> res.data).then(res => {
console.log(res);
this.tableData = res.list;
this.pagination.pageNumber =
res.pageNumber; // 更新当前页码
this.pagination.pageSize =
res.pageSize; // 更新每页条目数
this.pagination.totalRow =
res.totalRow; // 更新总条目数
this.pagination.totalPage =
res.totalPage; // 更新总页数
}).catch(err => {
console.error(err);
});
}
}
</script>
<template>
<div>
<el-form
:model="queryData" ref="form"
label-width="80px">
<el-row>
<el-col :span="4">
<el-form-item label="学号" prop="stuid">
<el-input
v-model="queryData.stuid" placeholder="学号"></el-input>
</el-form-item>
</el-col>
<el-col
:span="4">
<el-form-item label="姓名" prop="stuname">
<el-input
v-model="queryData.stuname" placeholder="姓名"></el-input>
</el-form-item>
</el-col>
<el-col
:span="4">
<el-form-item label="班级" prop="stuclass">
<el-input
v-model="queryData.stuclass" placeholder="班级"></el-input>
</el-form-item>
</el-col>
<el-col
:span="4">
<el-form-item>
<el-button
type="primary" @click="query0()">查询</el-button>
</el-form-item>
</el-col>
</el-row>
</el-form>
<el-dialog
title="修改学生信息"
:visible.sync="centerDialogVisible"
width="30%"
center>
<el-form ref="form"
:model="form" label-width="80px">
<el-form-item label="学号">
<el-input
v-model="form.stuid"></el-input>
</el-form-item>
<el-form-item label="姓名">
<el-input
v-model="form.stuname"></el-input>
</el-form-item>
<el-form-item label="班级">
<el-input
v-model="form.stuclass"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-input
v-model="form.stusex"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input
v-model="form.stuage"></el-input>
</el-form-item>
</el-form>
<span slot="footer"
class="dialog-footer">
<el-button
@click="false1()">取 消</el-button>
<el-button
@click="save1()">确认</el-button>
</span>
</el-dialog>
<el-dialog
title="增加学生信息"
:visible.sync="centerDialogVisible1"
width="30%"
center>
<el-form ref="form"
:model="form" label-width="80px">
<el-form-item label="学号">
<el-input
v-model="form.stuid"></el-input>
</el-form-item>
<el-form-item label="姓名">
<el-input
v-model="form.stuname"></el-input>
</el-form-item>
<el-form-item label="班级">
<el-input
v-model="form.stuclass"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-input
v-model="form.stusex"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input
v-model="form.stuage"></el-input>
</el-form-item>
</el-form>
<span slot="footer"
class="dialog-footer">
<el-button
@click="false1()">取 消</el-button>
<el-button
@click="save()">确认</el-button>
</span>
</el-dialog>
<el-button size="small"
type="success" @click="add()">添加</el-button>
<el-table
:data="tableData"
style="width: 100%">
<el-table-column
prop="stuid"
label="学号">
</el-table-column>
<el-table-column
prop="stuname"
label="姓名">
</el-table-column>
<el-table-column
prop="stusex"
label="性别">
</el-table-column>
<el-table-column
prop="stuclass"
label="班级">
</el-table-column>
<el-table-column
prop="stuage"
label="年龄">
</el-table-column>
<el-table-column prop="operate"
label="操作">
<template
slot-scope="scope">
<el-button
size="small" type="success"
@click="update(scope.row)">修改</el-button>
<el-button
size="small" type="success"
@click="drop(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pagination.currentPage"
:page-sizes="[10, 20, 50,
100]"
:page-size="pagination.pageSize"
layout="total, sizes, prev,
pager, next, jumper"
:total="pagination.totalRow">
</el-pagination>
</div>
</template>
<style scoped>
</style>
系统运行截图: