如何向jsp页面显示Servlet响应?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何向jsp页面显示Servlet响应?相关的知识,希望对你有一定的参考价值。

我刚刚创建了一个从我的ssrs服务器获取报告的Servlet。这是我的参考https://www.javaworld.com/article/2071830/build-ci-sdlc/a-java-proxy-for-ms-sql-server-reporting-services.html

现在我想让servlet响应显示在我的jsp页面上。我怎样才能做到这一点。

这是我的servlet代码:

@WebServlet(name = "ReportRequest", urlPatterns = {"/ReportRequest"})
public class ReportRequest extends HttpServlet
{
    private final static boolean DEBUG = true;
    private final static String REPORT_SERVER_URL = "http://localhost/ReportServer_SQL2012";
    private final static String REPORT_PATH = "%2fClients%2f";
    private final static String REPORT_ITEM_SERVLET_URL = "http://localhost:8080/ssrsClient/GetReportItem";
    private final static int BUFFER_SIZE = 2048;

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            if(DEBUG)
            {
                System.out.println("
Initializing Report Request");
                System.out.println("---------------------------");
            }

            Authenticator.setDefault(new ReportAuthenticator());

            // Generate parameter string from request
            String parameterString = "rs:Command=Render";

            // Get the list of parameters that can be defined by the user.
            ArrayList availableParams = GetAvailableParameters.getParameters();

            Enumeration paramEnum = request.getParameterNames();

            String currentParam;
            while(paramEnum.hasMoreElements())
            {
                currentParam = (String)paramEnum.nextElement();
                if(availableParams.contains(currentParam))
                {
                    // If parameter is available, add it to the string.
                    parameterString += "&" + currentParam + "=" + request.getParameter(currentParam);
                }
            }

            String reportName = request.getParameter("reportName");

            if(DEBUG)
            {
                System.out.println("ReportRequest - Parameter String: " + parameterString);
                System.out.println("ReportRequest - Report retrieved: " + reportName);
                String path = request.getServletPath();
                System.out.println("path: "+path);
            }

            if (reportName == null)
            {
                // Bail out if no report name is found.
                ServletOutputStream responseErrorStream = response.getOutputStream();
                responseErrorStream.println("ERROR: No report name specified");
                responseErrorStream.close();
                return;
            }

            // Establish HTTP POST connection to report server
            String urlString = REPORT_SERVER_URL + "?" + REPORT_PATH + reportName;
            URL url = new URL(urlString);
            System.out.println("url: " + urlString);
            HttpURLConnection repCon = (HttpURLConnection)url.openConnection();

            repCon.setRequestMethod("POST");
            repCon.setDoOutput(true);
            repCon.setUseCaches(false);
            repCon.setFollowRedirects(false);
            repCon.setRequestProperty("User-Agent", "Mozilla/5.0");
            repCon.setRequestProperty("Content-type", "application/x-www-form-urlencoded" );
            repCon.setRequestProperty("Content-length", Integer.toString(parameterString.length()));

            // Send parameter string to report server
            PrintWriter repOutStream = new PrintWriter(repCon.getOutputStream());

            repOutStream.println(parameterString);
            repOutStream.close();

            // Pipe Report Server's Output to the client
            forwardResponse(repCon, response);

        }
        catch (Exception e)
        {
            e.printStackTrace();

            // Alert the client there has been an error.
            ServletOutputStream responseErrorStream = response.getOutputStream();
            responseErrorStream.println("There has been an error.  Please check the system log for details.");
            responseErrorStream.close();
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // Redirect HTTP GET requests to doPost.

        doPost(request, response);
    }

    private void forwardResponse(HttpURLConnection reportCon, HttpServletResponse clientResponse) throws ServletException, IOException
    {
        // Take the report server's response and forward it to the client.

        String cookie = reportCon.getHeaderField("Set-Cookie");

        if(cookie == null)
        {
            System.out.println("ReportRequest - ERROR: No cookie provided by report server.  Aborting.");
            return;
        }

        if(cookie.indexOf(";") != -1)
        {
            cookie = cookie.substring(0,cookie.indexOf(";"));
        }
        if(DEBUG)
        {
            System.out.println("ReportRequest - Cookie: " + cookie);
        }

        String contentType = reportCon.getContentType();

        clientResponse.setContentType(contentType);
        clientResponse.setHeader("Content-disposition", reportCon.getHeaderField("Content-disposition"));

        InputStream repInStream = reportCon.getInputStream();
        ServletOutputStream clientOutStream = clientResponse.getOutputStream();

        if(!contentType.equals("text/html"))
        {
            // Use a buffered stream to send all binary formats.
            BufferedInputStream bis = new BufferedInputStream(repInStream);
            BufferedOutputStream bos = new BufferedOutputStream(clientOutStream);

            byte[] buff = new byte[BUFFER_SIZE];
            int bytesRead;

            while(-1 != (bytesRead = bis.read(buff, 0, BUFFER_SIZE)))
            {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        }
        else
        {
            /*
             * Use a character stream to send HTML to the client, replacing
             * references to the reporting server with the GetReportItem
             * servlet.
             */

            String currentWindow = "";
            int itemsFound = 0;

            for(int ch;(ch = repInStream.read()) != -1;)
            {
                if(currentWindow.length() < REPORT_SERVER_URL.length())
                {
                    currentWindow += (char)ch;
                }
                else if(currentWindow.equalsIgnoreCase(REPORT_SERVER_URL) && (char)ch == '?')
                {
                    itemsFound++;

                    clientOutStream.print(REPORT_ITEM_SERVLET_URL + "?cookie=" + cookie + "&");
                    currentWindow = "";
                }
                else
                {
                    clientOutStream.print(currentWindow.charAt(0));
                    currentWindow = currentWindow.substring(1) + (char)ch;
                }
            }
            clientOutStream.print(currentWindow);

            if(DEBUG)
            {
                System.out.println("ReportRequest - " + itemsFound + " references to the report server found.");
            }

        }

        repInStream.close();
        clientOutStream.close();
    }
答案

如果你想在servlet中显示没有任何set参数的页面:

@WebServlet("/error")
public class Error extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
       if(req.getMethod() == "POST")
       resp.sendRedirect("error.jsp");
    }
}

但是如果想要添加一个或多个参数集来请求:

@WebServlet("/showLicensesPage")
public class BuyLicense extends HttpServlet {

@Override
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     try {
          String name =  "ali";
          req.setAttribute("name",name);
          req.getRequestDispatcher("index.jsp").forward(req,resp);
        } catch (Exception e) {
          e.printStackTrace();
        }
   }
}

以上是关于如何向jsp页面显示Servlet响应?的主要内容,如果未能解决你的问题,请参考以下文章

JSP ---[什么是JSP,JSP 与 Servlet 有什么区别]

如何将servlet中的数据显示在jsp页面中

在servlet 中如何向客户端输出页面内容?

如何在 page.redirect 从 servlet 到 jsp 上显示成功消息

jsp初识servlet转发转发与重定向的比较

jsp中如何实现把一个jsp页面中表单的信息通过servlet处理在,另一个jsp页面中显示??