将jar包放入项目中:
创建一个数据类User:
package com.thb;
public class User {
private String name;
private int age;
private String gender;
public User() {
}
public User(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
创建一个servlet类Demo05jQueryJsonServlet,其中转换为json字符串的代码:
类的完整代码:
package com.thb;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Servlet implementation class Demo05jQueryJsonServlet
*/
@WebServlet(urlPatterns = "/jquery_json")
public class Demo05jQueryJsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Demo05jQueryJsonServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
// response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = new User("tom", 18, "男");
ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(user);
// 把json格式的字符串响应到客户端
response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
response.getWriter().write(json);
}
}
在浏览器中访问,获得返回的json字符串: