文章目录
项目实现了哪些功能
分角色登录注册(过滤器实现),session,cookie存储信息,
多表联合查询,分页查询+条件查询,分页查询。
项目中使用的版本
后端:
- tomcat10.1.x
- mysql-connect-java 8.0.x
- MySQL8.0.42
- jdk17
- jakarta.servlet
- Fastjson2
前端
- Vue2
- axiso1.x
- ElementUI
项目的下载
Gitee:https://gitee.com/xrkhy/detective-conan-archives
请求参数只能获取一次
如果过滤器获取了请求参数,servlet就不能获取了
过滤器实现分角色登录注册,验证是否已经登录
package com.hsh.filter;
/**
* @author xrkhy
* @date 2025/6/27 10:00
* @description
*/
import com.alibaba.fastjson2.JSONObject;
import com.hsh.pojo.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "/*",urlPatterns = "/*")
public class filter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
// ,"/html/receptiondesk/index.html"
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String uri = req.getRequestURI();
String contextPath = req.getContextPath();
// 白名单路径(目录前缀)
// 登录页面发起登录请求不要拦截。
String[] whiteDirs = {
contextPath + "/css/",
contextPath + "/js/",
contextPath + "/resource/",
contextPath + "/ElementUI/",
contextPath + "/imgs/",
contextPath + "/login",
};
// 白名单路径(精确文件)
String[] whiteFiles = {
contextPath + "/login.html",
contextPath + "/register.html"
};
// 检查目录白名单
for (String dir : whiteDirs) { // 遍历白名单目录列表
if (uri.startsWith(dir)) { // 检查请求URI是否以白名单目录开头
chain.doFilter(request, response); // 匹配则放行请求
return; // 结束当前过滤器的执行
}
}
// 检查文件白名单
for (String file : whiteFiles) {
if (uri.equals(file)) {
chain.doFilter(request, response);
System.out.println("文件白名单");
return;
}
}
System.out.println("未进入白名单 进入过滤器");
// 登录检查
User user = (User) req.getSession().getAttribute("user");
if (user == null) {
// 未登录 调到首页
System.out.println("未登录");
// request.getRequestDispatcher("/login.html").forward(request, response);
httpResponse.sendRedirect(contextPath + "/login.html"); // 携带上下文路径
return;
}
// 已登录放行
// chain.doFilter(request, response);
// --- 角色权限检查 ---
Integer role = user.getRole(); // 从User对象获取角色字段
if (role == 1) { // 管理员放行所有请求
chain.doFilter(request, response);
} else{ // 普通用户
// 仅允许访问 /html/receptiondesk/ 目录
String receptionDeskPath = contextPath + "/html/receptiondesk/";
if (uri.startsWith(receptionDeskPath)) {
chain.doFilter(request, response); // 放行
} else {
// 无权限访问其他路径
httpResponse.sendRedirect(contextPath + "/login.html"); // 携带上下文路径
// request.getRequestDispatcher("/login.html").forward(request, response);
}
}
}
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
}
package com.hsh.servlet;/**
* @author xrkhy
* @date 2025/6/27 9:41
* @description
*/
import com.alibaba.fastjson2.JSONObject;
import com.hsh.pojo.User;
import com.hsh.service.UserService;
import com.hsh.service.impl.UserServiceImpl;
import com.hsh.utils.JsonResultUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "login", value = "/login")
public class login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ....逻辑判断
// 存储到 session
request.getSession().setAttribute("user", user1);
// ... 相应数据到浏览器
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
前端注册界面自定义校验失效
原因:使用了如下的方式,当使用 data: {} 对象形式时,不仅会导致所有组件实例共享同一份数据引用,而且会引发校验函数访问数据可能为 undefined。
new Vue({
el: '#app',
data: {
}
})
所以使用函数的形式
new Vue({
el: '#app',
data (){
return{
数据
}
}
})
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script src="css/base.css"></script>-->
<script src="resource/vue.js"></script>
<link rel="stylesheet" href="ElementUI/theme-chalk/index.css"/>
<script src="ElementUI/index.js" charset="utf-8"></script>
<script src="resource/axios.min.js"></script>
<style>
.box-card{
width: 400px;
margin: 100px auto;
}
</style>
</head>
<body>
<div id="app">
<!-- 注册 -->
<el-card class="box-card">
<h3>名侦探柯南档案馆</h3>
<el-form
ref="registerForm"
:model="registerForm"
:rules="rules"
label-width="80px">
<el-form-item label="用户名" prop="username"> <!-- prop需与字段名一致 -->
<el-input v-model="registerForm.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="registerForm.password" type="password"></el-input>
</el-form-item>
<el-form-item label="确认密码" prop="confirmPassword">
<el-input v-model="registerForm.confirmPassword" type="password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="register()">注册</el-button>
<el-button type="primary" @click="login()">去登录</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
registerForm: {
username: '',
password: '',
confirmPassword: ''
},
rules: { // 校验规则对象
username: [
{required: true, message: '用户名不能为空', trigger: 'blur'},
{min: 3, max: 20, message: '长度在3-20个字符', trigger: 'blur'},
{pattern: /^[a-zA-Z0-9_]+$/, message: '只允许字母、数字和下划线', trigger: 'blur'}
],
password: [
{required: true, message: '密码不能为空', trigger: 'blur'},
{min: 6, max: 20, message: '长度在6-20个字符', trigger: 'blur'},
{validator: this.validatePassword, trigger: 'blur'} // 自定义密码复杂度校验
],
confirmPassword: [
{required: true, message: '请再次输入密码', trigger: 'blur'},
{validator: this.validateConfirmPassword, trigger: 'blur'} // 自定义一致性校验
]
},
}
},
methods: {
// 自定义密码复杂度校验函数
validatePassword(rule, value, callback) {
if (!/[A-Za-z]/.test(value) || !/[0-9]/.test(value)) {
callback(new Error('需包含字母和数字'));
} else {
callback();
}
},
// 自定义确认密码校验函数
validateConfirmPassword(rule, value, callback) {
if (value !== this.registerForm.password) {
callback(new Error('两次输入密码不一致'));
} else {
callback();
}
},
// 注册提交逻辑
register() {
this.$refs.registerForm.validate(valid => { // 触发表单整体校验
if (valid) {
console.log("axios请求")
} else {
this.$message.warning('请检查表单输入');
return false; // 阻止提交
}
});
},
login(){
localStorage.setItem("registerSuccess","true")
window.location.href = "/login.html"
}
},
})
</script>
</body>
</html>
使用前端的localStorage本地存储记录用户命
使用这个可以不用纠结使用cookie还要对cookie数据进行处理了。
常用方法:
| 方法 | 作用 |
|---|---|
| localStorage.setItem(String,String) | 给localStorage设置值 |
| localStorage.getItem(String) | 通过键的形式获取localStorage的值 |
| localStorage.removeItem(String); | 通过键的形式移除localStorage |
window.location.href实现页面跳转
// 和按钮绑定点击事件
register() {
window.location.href = "/register.html";
}
Vue组件的消息提示this.$message.error
必须使用箭头函数
methods: {
login() {
axios.post('/login', {
// 参数
}).then((response) => {
// 对于相应消息必须使用 箭头函数,不要使用function函数,
// 箭头函数表示this指向Vue实例。使用箭头函数会指向windows导致获取不到值。
console.log(response.data);
if (response.data.code == 200) {
// 提示登陆成功
} else {
this.$message.error(response.data.msg);
}
}).catch( (error) => {
console.log(error);
});
}
},
Vue组件的消息提示带到另一个界面使用
问题描述:我执行window.location.href之前,应该显示登录成功在跳转this.$message.success(response.data.msg);,代码如下:
this.$message.success(response.data.msg);
window.location.href = "/html/receptiondesk/index.html";
但是情况相反,直接跳转,不执行this.$message.success(response.data.msg);。
这是因为this.$message.success(response.data.msg);需要时间。this.$message.success(response.data.msg);还没来得及执行就跳转了。
下面以登录界面跳转首页为例
// 登录界面
login() {
axios.post('/login', {
// 参数
}).then((response) => {
if (response.data.code == 200) {
// 设置本地存储
localStorage.setItem('showLoginSuccess', 'true');
// 跳转
window.location.href = "/html/receptiondesk/index.html";
} else {
this.$message.error(response.data.msg);
}
}).catch( (error) => {
console.log(error);
});
}
// 首页
// 在加载页面时
mounted() {
// 如果有showLoginSuccess
if (localStorage.getItem('showLoginSuccess') === 'true'){
// 提示
this.$message.success('登录成功!');
// 移除提示,不然会永久保存showLoginSuccess
localStorage.removeItem('showLoginSuccess');
}
}
使用Fastjosn插件的泛型类型擦除问题
axios.post(`/UserPage`,{
...this.page,
// 应对后端的泛型擦除问题 传入
// {"currentPage":1,"pageSize":5,"total":10,
// "obj":{
// "id":"1",
// "userName":"xrkhy",
// "password":null,
// "role":null,
// "age":null
// }
// }
obj:{
...this.obj
}
}).then((respones)=>{
console.log(respones.data);
}).catch((error)=>{
console.log(error);
})
// {"currentPage":1,"pageSize":5,"total":10,"condition":{"id":"1","userName":"xrkhy","password":null,"role":null,"age":null}}
// Page{pageSize=5, currentPage=1, totalCount=null, startIndex=null, resultList=null, condition={"id":"1","userName":"xrkhy"}}
//之所以是这样是因为我的page工具类使用了泛型,被擦除了。
// 导致{"id":"1","userName":"xrkhy","password":null,"role":null,"age":null}
// 无法转为condition=User(id=1, userName=xrkhy, userPassword=null, age=null, role=null)
import com.alibaba.fastjson.TypeReference;
String json = "{\"currentPage\":1,\"pageSize\":5,\"total\":10,\"obj\":[{\"id\":\"1\",\"userName\":\"xrkhy\"}]}"; // 注意obj改为数组
Page<User> page = JSON.parseObject(json, new TypeReference<Page<User>>() {});
“属性:{}” json数据问题
和上面一样可能因为泛型擦除问题,也可以使用下面的方法去除{}。
// 写一个工具类。
package com.hsh.utils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import java.util.Objects;
/**
* @author xrkhy
* @date 2025/6/29 11:09
* @description
*/
public class JsonUtils {
/**
* 处理json数据的条件
* description: 当属性全是null{..."condition": {"id":null,"userName":null} }
* 将条件属性condition改为null。
* @param jsonStr
* @return
*/
public static String processCondition(String jsonStr) {
// 解析为 JSONObject 避免定义实体类
JSONObject jsonObj = JSON.parseObject(jsonStr);
JSONObject condition = jsonObj.getJSONObject("condition");
// 检查 condition 所有值是否均为 null
if (condition != null && condition.values().stream().allMatch(Objects::isNull)) {
jsonObj.put("condition", null);
}
return jsonObj.toJSONString();
}
}
条件查询报错
Parameter index out of range (1 > number of parameters, which is 0)参数索引超出范围(1 >参数数,即 0)
说明?没有被识别。
//String sql = "select * from smbms_user where userName like '%?%'";无法被识别为占位符的原因,
// 核心在于 JDBC 的占位符 ?必须独立存在,不能与其他字符(如通配符 %或引号)直接拼接
// 如上两种解决办法都可以解决
//return MySQLConnectUtils.executeQueryForList("select * from smbms_user where userName like ?", new Object[]{"%" + "李" + "%"}, SmbmsUser.class);
return MySQLConnectUtils.executeQueryForList("select * from smbms_user where userName like CONCAT('%', ?, '%')", new Object[]{userName}, SmbmsUser.class);
2万+




被折叠的 条评论
为什么被折叠?



