后端向前端传递参数问题

后端向前端传递参数问题

老师好,后端向前端传递参数默认是字符流还是字节流呢,如果更改该如何设置呢

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
好帮手慕小尤 2020-03-05 15:36:06

同学你好,1. 是的,后端通过response.getWriter.write(map)以字符流的形式返回给前端的。

2. 同学可以设置response,来指定返回的格式。

    2.1、字符输出流:PrintWriter  getWriter() 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);
    }
}

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

好帮手慕小尤 2020-03-05 11:18:50

同学你好,后端向前端传递参数是http请求中的数据传递,与字节流、字符流没有关系。

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • 提问者 qq_冷暖輪迴_0 #1
    那后端怎么传递数据到前端的呢,后端output stream.write不是可以将数据传到前端显示么
    2020-03-05 12:12:10
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码