简体   繁体   English

JSP Servlet检索(显示)网页

[英]JSP Servlet to retrieve(display) web pages

I am writing a servlet in JSP page to display the requested webpage. 我在JSP页面中编写了一个servlet,以显示请求的网页。 I have done fair bit of "googling" and most of them suggested of using BufferedReader. 我做了一些“搜索”工作,其中大多数建议使用BufferedReader。 Below I have the code that gets the requested url from the JSP page and the servlet displays the page. 在下面,我有从JSP页面获取请求的url的代码,并且servlet显示该页面。

However, while running this I am getting blank from the servlet. 但是,在运行此程序时,我的servlet变得空白。 Could anyone suggest me what wrong I have been doing in this code? 有人可以建议我在这段代码中发生了什么错误吗?

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String server = request.getParameter("browsebox");

        URL url = new URL(server);
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                yc.getInputStream(), "UTF-8"));
        String inputLine;
        StringBuilder a = new StringBuilder();
        while ((inputLine = in.readLine()) != null)
            a.append(inputLine);
        in.close();

       PrintWriter out = response.getWriter();
        out.println(a);
        // String output= a.toString();
        //System.out.println(output);
    }

You are very, very close. 你非常非常亲密。 But why are you printing the target web page on console rather than sending it back to the client? 但是,为什么要在控制台上打印目标网页,而不是将其发送回客户端? Try this for starters: 尝试一下入门:

response.getWriter().println(a);

Once you overcome that problem think how can you avoid loading the whole target web page first to a String and then sending it back. 克服该问题后,请考虑如何避免首先将整个目标网页加载到String ,然后再将其发送回。 What about reading target web page line by line or byte by byte and sending it immediately? 逐行或逐字节读取目标网页并立即发送该怎么办? Not only the client will receive partial response earlier, but you will save a lot of memory. 不仅客户端会更早收到部分响应,而且还可以节省大量内存。

You need to get the PrintWriter object from the response object. 您需要从响应对象获取PrintWriter对象。

PrintWriter writer = response.getWriter();
writer.println(<value>);

After you add 添加后

PrintWriter out=response.getWriter();
out.println(a);

it should work. 它应该工作。 Still if it is not working try, 如果仍然无法解决,请尝试,

PrintWriter out=response.getWriter();
out.println(a);`
out.flush();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM