写一个Javaweb服务端servlet以及js异步请求传送json对象的代码
时间: 2023-06-10 15:02:44 浏览: 63
好的,我可以帮你回答这个问题。
首先,我们需要编写一个Java servlet处理请求。以下是一个基本的示例:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Create a Gson object to convert objects to JSON
Gson gson = new Gson();
// Create an example object to send as JSON
ExampleObject example = new ExampleObject();
example.setName("John");
example.setAge(30);
// Convert the object to JSON
String json = gson.toJson(example);
// Set the response type to JSON
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// Send the JSON as a response
response.getWriter().write(json);
}
}
```
在这个示例中,我们创建了一个名为 "ExampleServlet" 的 servlet,并使用 `@WebServlet` 注解告诉容器该 servlet 映射到 `/example` 路径。我们定义了一个 `doGet` 方法以处理 GET 请求。在此方法中,我们创建了一个示例对象(`ExampleObject`) 并将其转换为 JSON 字符串。然后,我们将响应类型设置为 JSON,并将 JSON 字符串发送回客户端。
接下来,我们将使用 JavaScript 发出异步 POST 请求并发送 JSON 对象。以下是一个示例 JavaScript 代码:
```javascript
function sendRequest() {
// Create the JSON object
var obj = {
name: "Jane",
age: 25
}
// Convert the JSON object to a string
var json = JSON.stringify(obj);
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set up the request
xhr.open("POST", "/example");
xhr.setRequestHeader("Content-Type", "application/json");
// Handle the response
xhr.onload = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
// Send the request
xhr.send(json);
}
```
在此示例中,我们首先创建了一个名为 "obj" 的 JavaScript 对象,并将其值设置为我们要发送的数据。然后,我们将此对象转换为 JSON 格式的字符串。接下来,我们创建了一个新的 XMLHttpRequest 对象,并使用 `xhr.open()` 方法设置请求的类型和 URL。要在请求中发送 JSON 数据,我们需要设置 `Content-Type` 标头以指示数据类型为 JSON。最后,我们发送请求并处理响应。
希望这个回答能帮助到你!