我使用servlet將文檔上傳到服務器。成功上傳後,我需要向用戶顯示其他信息,例如使用哪個ID上傳哪個文檔。爲此,我將ID和文件名放入modelMap,我試圖在JSP頁面上發送它。將模型從servlet傳遞到JSP頁面
對於這個我使用此代碼: -
ModelMap model = new ModelMap();
for(FileItem item : files) {
model.put(id, fileName);
}
req.setAttribute("message", model);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/success.do");
dispatcher.forward(req, resp);
在JSP頁面
<%
if(request.getAttribute("message")!=null){
String value = request.getAttribute("message").toString();
if(value!=null)
{
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
out.println("<font color='red'>"+entry[1].trim()+"</font> indexed with id <font color='red'>"+entry[0].trim()+"</font><br/>");
}
}
System.out.println(request.getAttribute("message"));
}
%>
我的問題是在這個場景中所有的東西,不同的是一個工作。當我上傳顯示文檔消息時,但我的URL仍然是上傳的servlet URL。所以當用戶點擊它(GET請求)時,servlet會拋出上傳文件的異常。
如果我使用
resp.sendRedirect("../success.do");
然後我不能在它傳遞參數。那麼我如何才能完成這項任務?
我的文件上傳的servlet
mySite/upload/servlet
和成功頁面
mySite/success.do
要傳遞參數,你可以做類似resp.sendRedirect(「../ success.do?p1=abcd&p2=xyz」); –
假設用戶選擇要上傳的100個文件,因此文件名和上傳的網址超過256個字符限制。所以我們不能使用這個。 –
如果允許用戶上傳多個文件,那麼其他選項可能是在會話中設置地圖,然後重定向請求,並從那裏我們可以得到地圖,然後從會話中刪除該變量。 –