1
我試圖從jsp訪問servlet,然後使用webservice訪問代碼(如果數組列表傳遞爲0)。它應顯示圖像,如果它傳遞1,它應該顯示不同的jsp。我能夠生成代碼,但不能按預期工作。任何人都可以找出問題所在。從jsp調用servlet並返回jsp
package sal;
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
}
}
你忘了解釋「不工作」的細節。該代碼只是做它被告知要做的事情。會發生什麼呢? – BalusC
我想從servletcontext訪問圖像,但它調用「/ShowImage.jsp」,我已經硬編碼的圖像爲src =「c:/image.jpeg」;但我希望我的圖像從servlet context.Is有任何代碼更改,我需要使其工作。 – user1046671