编写Servlet 代码, 处理HTTP协议的 POST, PUT, DElETE 请求 作业内容 针对每个请求, 返回一个简单的字符串即可 要保证返回的中文不乱码. 使用 ajax 构造请求进行验证
时间: 2023-12-03 19:45:46 浏览: 85
以下是一个简单的 Servlet 代码,用于处理 HTTP 协议的 POST、PUT、DELETE 请求,并返回一个简单的字符串:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/api")
public class APIServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public APIServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("GET 请求已成功处理!");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("POST 请求已成功处理!");
}
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("PUT 请求已成功处理!");
}
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("DELETE 请求已成功处理!");
}
}
```
使用 AJAX 构造请求进行验证的方式如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX 测试</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#get-btn").click(function() {
$.get("api", function(data) {
$("#result").text(data);
});
});
$("#post-btn").click(function() {
$.post("api", function(data) {
$("#result").text(data);
});
});
$("#put-btn").click(function() {
$.ajax({
url: "api",
type: "PUT",
success: function(data) {
$("#result").text(data);
}
});
});
$("#delete-btn").click(function() {
$.ajax({
url: "api",
type: "DELETE",
success: function(data) {
$("#result").text(data);
}
});
});
});
</script>
</head>
<body>
<button id="get-btn">发送 GET 请求</button>
<button id="post-btn">发送 POST 请求</button>
<button id="put-btn">发送 PUT 请求</button>
<button id="delete-btn">发送 DELETE 请求</button>
<br>
<br>
<div id="result"></div>
</body>
</html>
```
以上代码将创建四个按钮,分别用于发送 GET、POST、PUT、DELETE 请求。点击每个按钮时,将使用 AJAX 发送请求,并在页面上显示响应的字符串。由于 Servlet 中设置了字符编码为 UTF-8,因此中文输出不会乱码。
阅读全文