jquery+servlet实现ajax 作者:马育民 • 2022-01-19 23:22 • 阅读:10129 # 说明 [![](https://www.malaoshi.top/upload/pic/jsp/Snipaste_2022-02-11_16-10-43.png)](https://www.malaoshi.top/upload/pic/jsp/Snipaste_2022-02-11_16-10-43.png) # 依赖 依赖 jackson jar包: - jackson-annotations-2.3.1.jar - jackson-core-2.3.1.jar - jackson-databind-2.3.1.jar # Servlet代码 ``` import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; 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.fasterxml.jackson.databind.ObjectMapper; @WebServlet( urlPatterns="/testJson" ) public class HelloLucyServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //一定是 text/json,否则浏览器不识别json resp.setContentType("text/json;charset=utf-8"); Map map=new HashMap(); map.put("name", "李雷"); map.put("age", 20); ObjectMapper om=new ObjectMapper(); String json=om.writeValueAsString(map); PrintWriter pw = resp.getWriter(); pw.write(json); pw.close();//关闭 } } ``` ### 关键代码1 必须写: ``` resp.setContentType("text/json;charset=utf-8"); ``` 这样浏览器的响应头才会显示 `json`,如下: [![](https://www.malaoshi.top/upload/pic/jsp/Snipaste_2022-01-19_23-27-23.png)](https://www.malaoshi.top/upload/pic/jsp/Snipaste_2022-01-19_23-27-23.png) 这样浏览器才能识别到 `json`格式的数据 ### 关键代码2 ``` ObjectMapper om=new ObjectMapper(); String json=om.writeValueAsString(map); ``` 其作用是将 `Map` 对象转换成 `json` 字符串 详见链接: [Jackson 处理json(ObjectMapper)](https://www.malaoshi.top/show_1EF5rdjyd8U3.html "Jackson 处理json(ObjectMapper)") [Jackson目录](https://www.malaoshi.top/show_1IX1uHcDmAUS.html "Jackson目录") # html ### 引入jquery ``` ``` ### js代码 ``` ``` 原文出处:http://malaoshi.top/show_1IX2chMedQ9h.html