正在回答 回答被采纳积分+1
2回答
好帮手慕小尤
2020-03-05 15:36:06
同学你好,1. 是的,后端通过response.getWriter.write(map)以字符流的形式返回给前端的。
2. 同学可以设置response,来指定返回的格式。
2.1、字符输出流:PrintWriter getWriter() 代码如下:
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 字节流输出数据 * @author wym * */ public class ResponseDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test1(response); } private void test1(HttpServletResponse response) throws IOException{ String data = "不见了远处的青山"; response.setContentType("text/html;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); out.write(data.getBytes("UTF-8"));//默认情况下:浏览器是乱码的(他默认查GBK) } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2.2、 字节输出流ServletOutputStream getOutputStream()
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 字符流输出中文数据 * @author wym * */ public class ResponseDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test1(response); } private void test1(HttpServletResponse response) throws IOException { String data = "幸福是什么?"; //改变字符流查的码表 response.setCharacterEncoding("UTF-8"); //告知客户端用UTF-8进行解码 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();//HttpServletResponse的实例由Tomcat服务器提供,Tomcat6.x默认查ISO-8859-1编码;Tomcat8.x默认编码为UTF-8 out.write(data); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
2. 从网页搭建入门JavaWeb
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星