EL表示式之requestScope
阿新 • • 發佈:2018-11-05
平時寫專案很多的在後臺遇見request.getAttribute(),偶然在看一個專案的時候,看到了這個EL表示式(jsp註釋處是我自己改寫的試了試)
<div><spring:message code="Message"></spring:message><font color="purple" size="12">${requestScope.okok}<%--此處這麼寫為先加載出NULL=request.getAttribute("okok")--%></font></div>
後臺相關程式碼如下
@RequestMapping("/Upload") public void Upload(HttpServletRequest request, HttpServletResponse response)throws Exception { InputStream is = null; String tempDir = null; request.setCharacterEncoding("utf-8"); //String filename=request.getParameter("pdf"); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //3 解析request List<FileItem> list = null; try { list = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); throw new RuntimeException("您操作有誤!"); } //4 遍歷FileItem if(list!=null){ for(FileItem item : list){ if(!item.isFormField()){ //是檔案上傳 // 將檔案儲存到 專案根目錄下的upload資料夾中 // 獲得upload資料夾路徑 String uploadPath ="D:\\SSM上傳下載\\Upload\\"; // 生成名稱 String filename=new File(item.getName()).getName(); int f=filename.lastIndexOf('.'); filename=filename.substring(0, f); System.out.println(filename); is = item.getInputStream(); FileOutputStream os = new FileOutputStream(uploadPath+filename+".pdf",true); IOUtils.copy(is, os); tempDir = uploadPath+filename+".pdf"; System.out.println(filename); System.out.println(tempDir); //InputStreamToString ists = new InputStreamToString(); //checkSexImgb64 = ists.GetImageStrI(is); //System.out.println("is" + is); //System.out.println("checkSexImgb64" + checkSexImgb64); //5 儲存訪問路徑到Product物件中 //p.setImgurl("/uploadImgSex"+datePath+filename); // /upload/2015/08/25/xxxxxxxxx //刪除臨時檔案 is.close(); os.close(); item.delete(); } else{ //是普通表單項 String idid = item.getString(); if("pdf_name".equals(item.getFieldName())) { idid = item.getString();} System.out.println(idid); System.out.println(tempDir); try { teachService.Upload(idid,tempDir); request.setAttribute("okok", "上傳成功"); } catch (Exception e) { request.setAttribute("okok", "上傳失敗"); e.printStackTrace(); } } } }
後來發現,改成<%=request.getAttribute("okok")%>在未執行後臺方法的時候會顯示一個NULL(也很好理解,頁面載入的時候JSP程式碼就已經執行,“okok”還沒有內容)。
當然這只是我所見識到的一種差異。
關於它們用法的區別,也找了一些比較優秀的理解:
在我們平常開發中經常會碰到需要把後臺資料庫中查詢到的資料來源展現到介面上,這時候我們就會用到EL表示式中的requestScope標籤。首先關於requestscope的定義是:是EL表示式的隱藏物件,包含request作用域內變數的Map。
例如:使用<jsp:useBean id="person" class="bean.Person"/>聲明瞭person物件後,使用${requestScope.person.age}將輸出person的age屬性。
關於requestscope和request.getParameter()
requestscope主要用於資料的展示,從request隱藏物件中取出物件或者變數來顯示。而request中的物件或變數是通過request.setAttribute方法放入request物件中的。
request.getParameter則更多的應用於後臺方法中,它的引數是由表單接受使用者輸入的之後提交請求時被放入到request物件中。