package com.gitcode.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.Printwriter;/ @version 1.0.0 @Date: 2024/2/10 20:20 @Author ZhuYouBin @Description: /public class HtmlResponseServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 相应HTML内容 response.setContentType(34;text/html;charset=UTF-8"); // 获取输出流 PrintWriter writer = response.getWriter(); // 输出HTML内容 writer.println("<!DOCTYPE html>"); writer.println("<html lang=\"en\">"); writer.println("<head>"); writer.println(" <meta charset=\"UTF-8\">"); writer.println(" <title>相应HTML内容</title>"); writer.println("</head>"); writer.println("<body>"); writer.println(" <h3>Hello World!
你好,天下!
</h3>"); writer.println("</body>"); writer.println("</html>"); // 关闭流 writer.close(); }}
运行结果如下所示:
1.2、返回JSON内容
JSON格式在实际的Web开拓中,可以说是最常用的数据交互格式啦,在一些前后端分离的项目中,都是采取JSON来进行数据交互的,以是这里给出一个相应JSON内容的案例代码:
package com.gitcode.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;/ @version 1.0.0 @Date: 2024/2/10 20:20 @Author ZhuYouBin @Description: /public class JsonResponseServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 相应JSON内容 response.setContentType("application/json;charset=UTF-8"); // 获取输出流 PrintWriter writer = response.getWriter(); // 输出JSON内容 writer.println("{"); writer.println(" \"username\":\"名字是Tom-2024\","); writer.println(" \"password\":\"123456\""); writer.println("}"); // 关闭流 writer.close(); }}
运行结果如下所示:
以上,便是利用HttpServletResponse工具返回HTML和JSON数据格式。
本日就到这里,未完待续~~