關於commons-fileupload與struts2過濾器衝突的解決方法


最近做網站需要用到網頁上傳文件的問題,於是決定用commons-fileupload來實現,

首先需要引入必要的struts2必要包,這裏就不列出來了。

上傳圖片的網頁代碼如下:

<form action="test1.jsp" name="form1" method="post" enctype="multipart/form-data" >
   手機圖片:<input type="file" name="img" /><br/>
    請上傳圖片<input type="submit" value="提交圖片" /></td>
    </form>

test1.jsp網頁代碼如下:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);//檢查輸入請求是否爲multipart表單數據。
    if (isMultipart == true) {
       FileItemFactory factory = new DiskFileItemFactory();//爲該請求創建一個DiskFileItemFactory對象,通過它來解析請求。執行解析後,所有的表單項目都保存在一個List中。
       ServletFileUpload upload = new ServletFileUpload(factory);
       List items = upload.parseRequest(request);
       Iterator itr = items.iterator();
       while (itr.hasNext()) {
           FileItem item = (FileItem) itr.next();
           //檢查當前項目是普通表單項目還是上傳文件。
           if (item.isFormField()) {//如果是普通表單項目,顯示錶單內容。
       String fieldName = item.getFieldName();
       if (fieldName.equals("name")) //對應demo1.html中type="text" name="name"
           out.print("the field name is" + item.getString());//顯示錶單內容。
       out.print("<br>");
           } else {//如果是上傳文件,顯示文件名。
       out.print("the upload file name is" + item.getName());
       out.print("<br>");
           }
       }
    } else {
       out.print("the enctype must be multipart/form-data");
    }
%>
<html>
<body>
</body>
</html>

這裏上傳文件的話正常會輸出  文件的名字。

但是由於struts2會攔截所有請求,由於一些原因導致網頁沒有接受到文件。

於是上網查了一些資料,要求在struts2裏面添加一行代碼

<constant name="struts.action.excludePattern" value="/system/page/test1.jsp"  />

便好用了,但是 首先聲明,這個value裏的屬性,應該添加項目名稱後面的字符串,比如我在把鼠標移動到上傳文件的時候便會出現網頁跳轉的網頁提示,我的事

localhost:8080/phoneSales/system/page/test1.jsp

其中的phoneSales是項目名稱,你只需要在value裏添加/system/page/test1.jsp中,便能成功讓struts過濾器不過濾這個請求,這裏特別強調,因爲我就是因爲這個原因導致耗費了一下午的時間找資料,你一定要將value填加正確,否則他也會無法正常運行。如果這樣還是不行的話,我建議你將你的struts-core-x.xxx.x.jar的文件提升到struts-core-2.1.8.1.jar以上版本,網上說可能這個版本之後才支持,不過我沒測試出來,這裏只是提示一下。

希望能幫到大家,別像我一樣浪費了大量時間在這種錯誤上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章