struts操作集錦



Struts2   HttpServletRequest,HttpSession
     Struts2  ,     HttpServletRequest HttpSession         ,       Struts2      HttpServletRequest HttpSession     :

1. Ioc  

          com.opensymphony.xwork2.ActionContext   ora.apache.struts2.ServletActionContext ,         。

  request  :

1).HttpServletRequest request = ServletActionContext.getRequest ();

2).ActionContext ct= ActionContext.getContext();

   HttpServletRequest request=

(HttpServletRequest)ct.get(ServletActionContext.HTTP_REQUEST);

  session  :

 Struts2    session      Map  ,     SessionMap,        session   HttpSession  ,           。

1).Map session=ActionContext.getSession();

2).Map session=(Map)ActionContext.getContext().get(ActionContext.SESSION);

    SessionMap        session     ,          HttpSession      HttpServletRequest  ,    request.getSession()      HttpSession  。     SessionMap           ,             session 。

       :

       enctype               ,    3  :

  1) application/x-www-form-urlencoded:        ,         value   ,                 

    URL    。

  2) multipart/form-data:                         ,                      

     。

  3) text/plain:                      。

       web           。   ,         enctype=”multipart/form-data”  ,          

         ,       Servlet           ,            ,         。

   Java   ,            :   Apache  Jakarta Common-FileUpload  

(http://commons.apache.org/fileupload/),    Oreilly   COS  (http://www.servlets.com/cos/)。            

        。


==================================
Struts2    


  commons-fileupload-1.2.jar commons-io-1.3.1.jar lib

=====
 jsp
=====

form   enctype     multipart/form-data

 

==============
 UploadAction
==============
private String username;
private String password;
private File file;           //      
private String fileFileName; //    File      + FileName(   )
private String fileContent;  //    File      + Content

//  setter...  getter...

String execute() throws Exception {

 InputStream is = new FileInputStream( file );

 String root = ServletActionContext.getRequest().getRealPath("/upload");

 File destFile = new File(root,this.getFileFileName());

 OutputStream os = new FileOutputStream( destFile );

 byte[] buffer = new byte[400];

 int length = 0;

 while( (length = is.read(buffer)) > 0 ) {

  os.write(buffer,0,length);
 }

 is.close();
 os.close();

 return SUCCESS;
}

=================
        
=================

      UTF-8        

struts2-core 
struts-default.xml                      ----      
org.apache.struts2.default.properties   ----       

33   strusts.i18n.encoding=UTF-8     UTF-8

   struts.xml     

<struts>
      
 <constant name="struts.i18n.encoding" value="gbk"/>

         
 <constant name="struts.multipart.saveDir" value="c:\"/> 
</struts>

    
struts.multipart.parser=jakarta   struts2        
                        pell
                        cos

struts.multipart.maxSize=2097152                2M

struts.action.extension=action       url    

 


================
        
================

     :
1.  
File[] file                  
String[] fileFileName         
String[] fileContentType       

2.  
List<File>   file   
List<String> fileFileName
List<String> fileContentType

--------
action :
--------
String execute() {

 for(int i = 0; i < file.size(); i++) {
  InputStream is = new FileInputStream(file.get(i));
  String root = ServletActionContext.getRequest().getRealPath("/upload");
  File destFile = new File(root,this.getFileFileName().get(i)); 
  ... 
 } 

 return SUCCESS;
}

------
jsp :
------
  file ,file      ,   file,    set  file    List  

<s:file name="file" />
<s:file name="file" />
<s:file name="file" />


========================
         
========================

<td id="more">
 <input type="button" value="  " onclick="addMore()" />
</td>

------
  JS:
------
funcation addMore() {

 var td = document.getElementById("more");

 //       
 var br = document.createElement("br");

 //    input  
 var input = document.createElement("input");
 var button = document.createElement("input");

 //       file      
 input.type = "file";

 //       
 input.name = "file";

 button.type = "button";
 button.value = "  ";

 //            
 button.onclick = function() {
  //alert("    ");

  //    
  td.removeChild(br);
  td.removeChild(input);
  td.removeChild(button);
 }

 //        <td> 
 td.appendChild(br);
 td.appendChild(input);
 td.appendChild(button);
}

 

=======================
           
=======================
org.apache.struts2.interceptor.FileUploadInterceptor 

Long maximumSize:      ---        ,    
String allowedTypes:     

-------------
 struts.xml
-------------
<struts>
 <action ...>
  <result name="input">/upload.jsp</result>
  <result .../>
  
                    
  <interceptor-ref name="fileUpload">


   <param name="maximumSize">409600</param>               400K
   <param name="allowedTypes">...</param>     mime  ,       


  </interceptor-ref>

  **         
  <interceptor-ref name="defaultStack" />
 </action>  
</struts>

 :     tomcat\conf\web.xml  <mime-type>     

 

--------------
  upload.jsp
--------------

    <s:fielderror />

----------------------
           
----------------------

org.apache.struts2     struts-messages.properties

-----------------------
         
struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" {2}

-----------------------
          
struts.messages.error.file.too.large=File too large: {0} "{1}" {2}

-----------------------
      
struts.messages.error.uploading=Error uploading: {0}

            /src/messages.properties

struts.messages.error.content.type.not.allowed=           
struts.messages.error.file.too.large=      ,   
struts.messages.error.uploading=         

---------
     
---------
<constant name="struts.custom.i18n.resources" value="messages"/>

messages_en_US.properties
messages_zh_CN.properties

 


==============================
              
==============================

      :org.apache.struts2.dispatcher.StreamResult

==    ==

String contentType = "text/plain";       
String contentLength;
String contentDisposition = "inline";    
String inputName = "inputStream";        
InputStream inputStream;                
int bufferSize = 1024;                   

==    == 

contentType 

    ,    MIME          ,  text/plain     ,text/xml  XML,image/gif  GIF  ,image/jpeg  JPG    

          ,                ,              :application/octet-stream;charset=ISO8859-1 ,       charset,                

inputName 

        ,   action       Inputstream    ,     inputStream       getInputStream()   

contentDisposition 

         ,    (inline)   (attachment)    ,               ,              。   :attachment;filename="struts2.txt",                struts2.txt。     filename="struts2.txt",         inline,           ,        :inline; filename="struts2.txt" 

bufferSize 

         

 # contentType   contentDisposition     HTTP     Content-Type Content-disposition 。

    :
     HTTP   : 

     HTTP/1.1 200 OK 
     Server: Apache-Coyote/1.1 
     Content-disposition: attachment;filename="struts2.txt" 
     Content-Type: text/plain 
     Transfer-Encoding: chunked 
     Date: Sun, 02 Mar 2008 02:58:25 GMT 

----------
  action
----------
Class DownloadAction extends ActionSupport {

 private String path;

 // setter... getter...

 //         ,         
 public InputStream getDownloadFile() {
 
  //         --       root upload    

  //    new FileInputStream("c:/test.text");
  return ServletActionContext.getServletContext().getResourceAsStream("/upload/struts2.ppt");
  
 }

 public String execute() throws Exception {

  return SUCCESS;
 }
}

-----------
struts.xml
-----------
 <action name="download" class="org.scorpio.jh.struts2.upload.action.DownloadAction">
  
   <!--          -->
   <param name="path">/download/xhtml.txt</param>
   
   <!--           -->
   <result name="success" type="stream">
    
    <!--        -->
    <param name="contentType">text/plain</param>
    
    <!--            attachment:    ,filename=:       -->
    <param name="contentDisposition">attachment;filename="xhtml.txt"</param>
   
    <!--                 downloadFile  DownloadAction  getDownloadFile()-->
    <param name="inputName">downloadFile</param>
   
    <!--             --> 
    <param name="bufferSize">4096</param>
   </result>
  </action>

 

==========================
             
==========================

1.   action                   

   path = new String( path.getBytes(), "ISO-8859-1" );


2.xml         path  

   <param name="contentDisposition">attachment;filename="${path}"</param>

   ${path}            action path    ,     getPath()  

-------
action
-------
private String path;
 
public String getPath() {
  
 try {               //        
  path = new String( path.getBytes(), "ISO-8859-1" );
 } catch (UnsupportedEncodingException e) {
  e.printStackTrace();
 } 
  
 return path;
}

public void setPath(String path) {
 this.path = path;
}

---------------
   struts.xml
---------------

<action name="download" class="org.scorpio.jh.struts2.upload.action.DownloadAction">
 
 <param name="path">/download/wmlscript  .txt</param>

 <result name="success" type="stream">
  <param name="contentType">text/plain</param>

  <!--       DownloadAction path   -->
  <param name="contentDisposition">attachment;filename="${path}"</param>

  <param name="inputName">downloadFile</param>
  <param name="bufferSize">4096</param>
 </result>
</action>

 

=================
        
=================

       Struts 2  ,                    :

http://localhost:8080/struts2hello/download3.action?inputPath=/WEB-INF/web.xml,                      web.xml       ,                 JSP     。             。         ,                ,   Action     inputPath       ,             : 

public void setPath(String path) { 
 this.path = path; 
} 

           download.action?fileid=1            。   ,     execute()         ,          download       ,     ,          。  ,          execute()      ,    : 

public String execute() throws Exception { 

//         
String downloadDir = ServletActionContext.getServletContext().getRealPath("/download"); 

//       
String downloadFile = ServletActionContext.getServletContext().getRealPath(inputPath); 

java.io.File file = new java.io.File(downloadFile); 

downloadFile = file.getCanonicalPath();//       ,     ..    

//          /download     ,        
if(!downloadFile.startsWith(downloadDir)) { 
 return null; 
} 

return SUCCESS; 

} 

             web.xml   ,          ,           /download