简体   繁体   English

通过JSP中的servlet检索网页

[英]Retrieving web page through servlet in JSP

How do I retrieve a webpage by a Servlet passed as a form parameter from a JSP page? 如何通过Servlet从JSP页面获取作为表单参数传递的网页?

The JSP page has a form with textbox to enter the url as a string and a submit button. JSP页面具有一个带有文本框的表单,用于以字符串形式输入URL和一个提交按钮。 The action is performed by a servlet which fetches the webpage from the url passed and displays the retrieved webpage. 该动作由Servlet执行,该Servlet从传递的URL中获取网页并显示检索到的网页。

Here i have my servlet code ` 这是我的servlet代码`

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    * Servlet implementation class Search
    */
    @WebServlet("/Search")
    public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;

    /**
    * @see HttpServlet#HttpServlet()
    */
     public Search() {
    super();
    // TODO Auto-generated constructor stub
    }

/**
 * @param  
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {
    String html = null;

    String server = request.getParameter("browsebox");
    if(server != null && server !="")
        {

            response.sendRedirect("browse.jsp");

        }

        try {
            html = getWebPageFromUrl(server);

        }catch(Exception e) {
            System.err.println(e.toString());
            return;

        }
        response.setHeader("serchbox", server);
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        if(html == null) {
            out.println("<html>");
            out.println("<head><title>Refresher</title></head>");
            out.println("<body bgcolor=\"#ffffff\">");
            out.println("<p>The servlet has received a POST. This is the reply.    </p>");
            out.println("</body></html>");
        } else {



            out.print(html);
        }
    }








/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request,response);
}


private String getWebPageFromUrl(String urlString) throws Exception {

    // Create a URL object from urlString
    URL stockURL;

    try {
        stockURL = new URL(urlString);
        } catch (MalformedURLException e) {

            String msg = "Invalid url: " + urlString;
            throw new Exception(msg);
            }

    // Open a connection to the URL
    URLConnection stockConnection;

    try {
        stockConnection = stockURL.openConnection();
        } catch (IOException e) {

            String msg = "Can't open connection to " + urlString;
            throw new Exception(msg);
            }

    // Get the InputStream from the URL connection
    InputStream webPageInputStream;

    try {
        webPageInputStream = stockConnection.getInputStream();
        } catch (IOException e) {

            // Could be any server error, but the most likely is 404
            String msg = "404 File Not Found: " + urlString;
            //throw new WebPageGrabberException(msg);
            throw new Exception(e.toString());
            }

    // Read the web page via the InputStream

    StringBuffer webPageData = new StringBuffer(32000);
    int totalBytesRead = 0;
    boolean moreToRead = true;
    byte[] readBuf = new byte[4096]; // Read the web page in 4K chunks

    while (moreToRead) {

        int numBytesRead = 0;

        try {
            numBytesRead = webPageInputStream.read(readBuf);
            } catch (IOException e) {

                moreToRead = false;
                numBytesRead = -1;
                }

        if (numBytesRead > 0) {

            totalBytesRead += numBytesRead;
            webPageData.append(new String(readBuf, 0, numBytesRead));
            } else {
                moreToRead = false;
                }

        }

    try {
        webPageInputStream.close();

        } catch (IOException e) {

        // Ignore any exception that might occur
            }

    webPageData.setLength(totalBytesRead);
     webPageData.toString();
}
}

I am getting blank from the servlet, when the form is submitted. 提交表单后,我从servlet变得空白。

If you need to display the site in its entirety, just redirect to it. 如果您需要显示整个网站,只需重定向到它。

response.sendRedirect(request.getParameter("url"));

If you need to display the site embedded in your JSP page, use an iframe. 如果需要显示JSP页面中嵌入的网站,请使用iframe。

<iframe src="${fn:escapeXml(param.url)}"></iframe>

(the JSTL fn:escapeXml() is just there to prevent possible XSS attacks) JSTL fn:escapeXml()仅用于防止可能的XSS攻击)

Either case, you may only want to validate beforehand if the URL starts with http:// or https:// and so on. 无论哪种情况,如果URL以http://或https://开头,等等,您可能只需要事先进行验证。

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

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