add<请求异步改造>

v3
liyansheng 2025-01-14 00:37:02 +08:00
parent d546287891
commit 423a8962bb
4 changed files with 119 additions and 20 deletions

21
pom.xml
View File

@ -48,6 +48,20 @@
<version>0.9.5.5</version> <!-- 最新版本请在 Maven 仓库查看 -->
</dependency>
<!-- Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- JSTL -->
@ -65,6 +79,13 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
<!-- JSP Implementation (optional, usually provided by your server) -->
<dependency>
<groupId>org.apache.tomcat</groupId>

View File

@ -1,5 +1,6 @@
package example.controller;
import example.model.Result;
import example.model.User;
import example.service.IUserService;
import example.service.impl.UserServiceImpl;
@ -18,27 +19,29 @@ public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.setContentType("application/json;charset=utf-8");
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String captcha = req.getParameter("captcha");
try {
if(!captcha.equalsIgnoreCase((String)req.getSession().getAttribute("captcha"))){
req.getSession().setAttribute("msg","验证码错误");
resp.sendRedirect("/msg.jsp");
if (!captcha.equalsIgnoreCase((String) req.getSession().getAttribute("captcha"))) {
resp.getWriter().write(toJson(Result.error("验证码错误")));
return;
}
User user = userService.login(username, password);
if(user!=null){
req.getSession().setAttribute("user",user);
resp.sendRedirect("/computer?action=list");
}else{
req.getSession().setAttribute("msg","用户名或密码错误");
resp.sendRedirect("/msg.jsp");
if (user != null) {
req.getSession().setAttribute("user", user);
resp.getWriter().write(toJson(Result.success("登录成功")));
} else {
resp.getWriter().write(toJson(Result.error("用户名或密码错误")));
}
} catch (Exception e) {
throw new RuntimeException(e);
e.printStackTrace();
resp.getWriter().write(toJson(Result.error("系统错误,请稍后重试")));
}
}
@ -46,4 +49,10 @@ public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/login.jsp");
}
private String toJson(Object object) {
// 使用简单的 JSON 序列化方式,实际可以使用 Jackson 或 Gson 库
return new com.google.gson.Gson().toJson(object);
}
}

View File

@ -0,0 +1,41 @@
package example.model;
public class Result<T> {
private String status; // "success" 或 "error"
private String message; // 消息内容
private T data; // 附加数据
public Result(String status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
public Result(String status, String message) {
this(status, message, null);
}
public String getStatus() {
return status;
}
public String getMessage() {
return message;
}
public T getData() {
return data;
}
public static <T> Result<T> success(String message, T data) {
return new Result<>("success", message, data);
}
public static <T> Result<T> success(String message) {
return success(message, null);
}
public static <T> Result<T> error(String message) {
return new Result<>("error", message, null);
}
}

View File

@ -3,31 +3,59 @@
<html>
<head>
<script src="https://www.liyansheng.top/cdn/watermark.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 定义一个函数,用于刷新验证码
function refreshCaptcha() {
const captchaImage = document.getElementById("captchaImage");
captchaImage.src = "/captcha?timestamp=" + new Date().getTime(); // 添加时间戳避免缓存
}
$(document).ready(function () {
// 绑定表单提交事件
$('#loginForm').submit(function (event) {
event.preventDefault(); // 阻止表单默认提交行为
// 获取表单数据
const formData = $(this).serialize();
// 异步请求
$.ajax({
url: '/login',
type: 'POST',
data: formData,
dataType: 'json',
success: function (response) {
if (response.status === 'success') {
alert(response.message);
window.location.href = '/computer?action=list'; // 跳转至主页
} else {
$('#message').text(response.message).css('color', 'red');
}
},
error: function () {
$('#message').text('请求失败,请稍后重试').css('color', 'red');
}
});
});
// 刷新验证码
$('#captchaImage').click(function () {
$(this).attr('src', '/captcha?timestamp=' + new Date().getTime());
});
});
</script>
</head>
<body>
<h2>-电脑商城-用户登录</h2>
<form action="login" method="post">
<form id="loginForm">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br><br>
<label for="captcha">验证码</label>
<input type="text" id="captcha" name="captcha" required>
<img id="captchaImage" src="/captcha" alt="验证码" onclick="refreshCaptcha()" style="cursor: pointer;" title="点击刷新验证码"><br><br>
<img id="captchaImage" src="/captcha" alt="验证码" style="cursor: pointer;" title="点击刷新验证码"><br><br>
<button type="submit">登录</button>
<a href="/register">没有账号?去注册</a>
</form>
<br>
${requestScope.msg}
<p id="message"></p>
</body>
</html>