实现异步请求步骤如下:
**1. 前端发起异步请求**
```html
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$.ajax({
url: '/web/async?method=message', //请求地址
method: 'post', //请求方式
dataType: 'json', //响应数据类型为json
data: {'id': 1, 'username': 'zhangsan', 'password': '123456'}, //发送到后端的数据
beforeSend: xhr => {
//在发送请求之前执行的方法
console.info("beforeSend")
},
success: (result, status, xhr) => {
//发送请求成功并获取响应后被执行的方法
console.info('success -> result', result)
//{id: 1, password: '123456', username: 'zhangsan'}
},
error: (result, status, xhr) => {
//发送请求之后后端发送异常时被执行的方法
console.info('error -> result', result)
}
})
</script>
```
**2. Servlet代码**
```java
@WebServlet("/async")
public class AsyncServlet extends BaseServlet {
/**
* 异步请求必须返回void
*/
public void message(HttpServletRequest request, HttpServletResponse response) throws IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = User.builder().id(id).username(username).password(password).build();
//将数据转换为json字符串再响应给前端
response.getWriter().print(JSON.toJSONString(user));
}
}
```