English 中文(简体)
从 jsp 调用服务器, 返回 jsp 。
原标题:Calling a servlet from a jsp and return back a jsp
  • 时间:2012-05-23 05:40:21
  •  标签:
  • java

我试图从 jsp 访问一个服务器, 如果阵列列表过错为 0, 则访问网络服务的代码。 它应该显示一个图像, 如果过错为 1, 它应该显示不同的 jsp 。 我能够生成代码, 但效果不如预期。 任何人都能找出问题所在 。

包包萨尔;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Amberalerts
 */
public class Amberalerts extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        List  list = getList();
        if(list != null && list.size() != 0){
          dispatchToShowJsp(req, resp, "/ShowImage.jsp");
        }else{
            dispatchToShowJsp(req, resp, "/ShowDefaultMsg.jsp");
        }

        // writeImageTOBuffer(resp);
    }
    private List getList() {
        List<String> list = new ArrayList<String>();
        list.add("Result");
        return list;
    }
    private void dispatchToShowJsp(HttpServletRequest req,
            HttpServletResponse resp, String jsplocation) throws IOException {
        try {
            getServletConfig().getServletContext().getRequestDispatcher(
                    jsplocation).forward(req,resp);
        } catch (ServletException e) {

            e.printStackTrace();
        }
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */


    private void writeImageTOBuffer(HttpServletResponse resp)
            throws FileNotFoundException, IOException {
        // Get the absolute path of the image
        ServletContext sc = getServletContext();
        String filename = sc.getRealPath("rsc/image.gif");

        // Get the MIME type of the image
        String mimeType = sc.getMimeType(filename);
        if (mimeType == null) {
            sc.log("Could not get MIME type of "+filename);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // Set content type
        resp.setContentType(mimeType);

        // Set content size
        File file = new File(filename);
        resp.setContentLength((int)file.length());

        // Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.close();
    }


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

}
问题回答

请注意,您的代码不会起作用,因为您调用 wwriteImaageTo Buffer 的电话被评论,而您在 doGet(req,resp) 中的 if/ele 语句总是会调用 dispatchToshowJsp() 方法。

无论如何,使用""http://commons.apache.org/io/"rel="nofollow" >Apache commons IO 来帮助一些繁忙的工作, 您可以在下面调用 sendimageToResponse 方法来发送您的图像 :

package com.stackoverflow.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class ShowImageServlet extends HttpServlet {

        public void sendImageToResponse(HttpServletResponse response) throws ServletException, IOException {

        File imageFile = new File("PATH_TO_YOUR_IMAGE_FILE"); // configure this however you want

        OutputStream outStream = null;
        InputStream inStream = null;

        try {

            outStream = response.getOutputStream();

            // Open image file
            inStream = FileUtils.openInputStream(imageFile);

            response.setContentType("image/jpeg");

            System.out.println("SENDING " + imageFile);

            // Send image file
            IOUtils.copy(inStream, outStream);

            System.out.println("SENT SIZE=" + imageFile.length());

        } catch (Exception ex) {

            // Handle your exception

        } finally {

            // close image file
            IOUtils.closeQuietly(inStream);

            try {

                // flush stream
                outStream.flush();

            } catch (Exception ignore) {

                // Ignore

            } finally {

                IOUtils.closeQuietly(outStream);
            }
        }
    }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签