Brief introduction
Today is the third day of study Struts2, also calculate struts2 prepare prelude to end, upgrade part only in the late in-depth understanding, more see source code, more information. What you learned today. Upload and download/valuestack&ognl/struts2 tags
File Upload/download
File upload Introduction a). Enterprise commonly used file upload technology: jspsmartupload (main application JSP model1 ERA), FileUpload (one component of Apache Commons project), Servlet3.0 integration File upload Part B). STRUTS2 support for file uploads provides FileUpload interceptors for parsing multipart/form-data encoded format requests, parsing the contents of the uploaded files FileUpload interceptors default to the Defaultstack stack, 1 by default. Single File Upload (a). Page writing: Existence <input type= "file" name= "upload"/> upload entries, must provide the Name property form submission method must be post submission form encoding type enctype= "Multipart/form-data" b) . Write the action class to receive form properties by contract definition private File upload; Here the variable name and the page table cell element Name property are consistent with the private string Uploadcontenttype;private string uploadfilename;* for three objects to provide setter methods through Fileutils Provide copyFile for file copy, save upload file to server side C). Struts2 error handling during uploading of files 1). Configure the input view, as the upload error after the jump page in the file upload, if an error occurs, the FileUpload interceptor will set the error message, Workflow Interceptor jump to Input view 2). Error message prompt with:jsp:<s:actionerror/> <s:feildError/> display error message to the Chinese version: With internationalized message resource files If the error is caused by configuring the global default parameters, It is best to use the global message resource file **struts2 The default prompt resource file: Struts2-core-**.jar in the org.apache.struts2 struts-message.properties file. A value of 2 is overwritten with the key. Multiple File Upload form upload field name settings, the action class can define an array or receive for the collection, and then traverse 3 when the download operation. File download the first way: in the configuration file processing (principle:Use the result type for processing. Stream) a). In the action class, define InputStream and file name B). Associate the resource file, intercept the file name for UrlEncode encoding c). Returns the result logical view D). Configure Struts.xml files Inputname/contenttype/<param name= "Contentdisposition" >attachment;filename=${@[email Protected] (filename, ' UTF-8 ')}</param><param name= "ContentLength" >${filesize}</param> The second way: the file Download principle: The server reads the contents of the download file, writes back through the response response stream, sets the ContentType, contentdisposition header information a). Define contenttype/contentdisposition/filename in action to encode, add the appropriate Get method getInputStream () Servletactioncontext.getservletcontext (). GetMimeType (filename); encodedownloadfilename (string filename, string Agent) file name encoding problem B). Configuration result parameters in struts OGNL expressions to get
Custom result Types
1. Develop a direct or indirect implementation of the Com.opensymphony.xwork2.Result interface public class Captcharesult implements Result{public void Execute ( Actioninvocation arg0) throws Exception {//Implementation result view output code}}2. Define Struts.xml <package "Default" Name= "/" in namespace= extends= "Struts-default" ><result-types><result-type name= "Captcha" class= " Com.itheima.results.CaptchaResult "/></result-types></package>3. When you configure an action, the result type is introduced <action name = "Gencaptcha" > <result type= "Captcha" > <!-- <param name= "width" >240</param> <param name= "Height" >50</param>- </result></action>4. In the page, access the third step of the configured action< IMG src= "${pagecontext.request.contextpath}/gencaptcha.action"/>
Valuestack (value stack)
Question one: What is value stack valuestack? Valuestack is STRUTS2 provides an interface for implementing class Ognlvaluestack----Value stack objects (OGNL is fetching data from the value stack) each action instance has a Valuestack object (one request corresponds to a VALUESTAC K object) in which to save the current action object and other related objects (the value stack is an action reference), the Struts framework holds the Valuestack object in the request property named "Struts.valuestack", where the value stack object is Request a property) Valuestack vs = Request.getattribute ("Struts.valuestack"); question two: the internal structure of the value stack? The value stack consists of two parts objectstack (root): Struts presses the action and related objects into the Objectstack--listcontextmap (context): Struts has a variety of mapping relationships (some map-type objects In Contextmap, struts will press these mappings into Contextmap parameters: The map contains the request parameters for the current request? Name=xxxrequest: The map contains the There is a property session: The map contains all the properties in the current Session object application: The map contains all the properties in the current Application object attr: The map retrieves a property in the following order: request, SE Ssion, Applicationvaluestack and contextmapvaluestack have the root attribute (compoundroot), the context property (ognlcontext) * Compoundroot Is arraylist* Ognlcontext is Mapcontext map to the root object * There are also request, session, application, attr, Parameters object references in the context * OGNL expression, no # required to access data in root, access request, Session, application, attr, parameters object data must be written # * operation value stack default refers to the operation root element problem three: Value stack object creation, Valuestack and actioncontext What is the relationship? The value stack object is the Dofilter created at the time of the request Prepare.createactioncontext (request, response); * Create Actioncontext object procedure, create value Stack object Valuestack * Actioncontext object has reference to Valuestack object (get value stack object through Actioncontext in program) Dispatche The R class Serviceaction method saves the value stack object to the request range Request.setattribute (Servletactioncontext.struts_valuestack_key, Proxy.getinvocation (). Getstack ()); question four: How to get a value stack object get a value stack object There are two methods valuestack Valuestack = (valuestack) Servletactioncontext.getrequest (). getattribute (Servletactioncontext.struts_valuestack_key); Valuestack ValueStack2 = Actioncontext.getcontext (). Getvaluestack (); question five: save data to the value stack (primarily for root)//Save the data in the root index 0 location, Place the first element ArrayList Add (0,element); Valuestack.push ("Itcast");//create a parameter map on the value stack, save the data to map Valuestack.set ("Company", " Podcast "); To view the contents of a value stack in a JSP by <s:debug/> Six: Data access in a JSP that gets the value stack does not require # access to other object data plus #通过下标获取root中对象 <s:prope Rty value= "[0].top"/>//value stack top object looks up directly in rootLike attributes (top-down auto-find) Valuestack:<s:property value= "username"/> What data is put into the value stack by default? 1) Each request, access to the action object is pushed into the value stack------- Defaultactioninvocation Init method Stack.push (action); * Action if you want to pass the data to the JSP, only save the data to the member variable, and provide a Get Method 2) Modeldriven interface There is a separate interceptor <interceptor name= "Modeldriven" class= "Com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/ > In the Interceptor, the model object is pressed into the value stack Stack.push (model); * If the action implements the Modeldriven interface, the value stack default stack top object is the model object question seven: Why El can also access the data in the value stack STRUTSPR Request = Prepare.wraprequest (request) in Eparedandexecutefilter's dofilter code; * The Request object is packaged, Strutsrequestwrapper * Rewrites the request's GetAttribute object attribute = Super.getattribute (s); if (attribute = = null) {attribute = Stack.findvalue (s);} When accessing data from the request scope, if the data cannot be found, the request object has the ability to access the value stack data (find the root data) in the value stack.
OGNL
OGNL is an abbreviation for the object Graphic Navigation Language, which is an open source project. The STRUTS2 framework uses OGNL as the default expression language. * Xwork provides OGNL expression * OGNL-3.0.5.JAROGNL is a language that is much more powerful than El Ognl offers five main classes of functions 1, Support object method calls, such as xxx.dosomespecial (), 2, support class static method invocation and value visit Q 3, Access OGNL context (OGNL contexts) and Actioncontext, (focus on Valuestack value stack) 4, support assignment operation and expression concatenation 5, manipulate collection object using OGNL Access object method and static method * OGNL in JSP combined with STRUTS2 tag library, <s:property value= "OGNL expression"/> Execute OGNL Expression Call instance method: Object. Method ()----<s:property value= "' He Llo,world '. Length ()/> Call static method: @[class full name (including package path)]@[method name]---<s:property value= "@[email protected" (' Hello,%s ', ' xiaoming ') '/>* use static method calls must set Struts.ognl.allowstaticmethodaccess=true access OGNL contexts (OGNL context) and ACTIONCONTEXTOGNL context (OGNL Context) object-----value stack valuestack get data in Ognlcontext request:<s:property value= "#request. Username"/>session:<s: Property value= "#session. Username"/>application:<s:property value= "#application. Username"/>attr:<s: Property value= "#attr. Username"/>parameters:<s:property value= "#parameters. cid[0] "/> Ognl expressions common use #,%, $ sign using 1) # Use a # for Actioncontext.getcontext () context <s:property value=" #request. Name " />------------> Actioncontext (). GetContext (). Getrequest (). Get ("name"); #request #session #application #attr #parameters use two: Do not write # Default in the value stack in root to find <s:property value= "name"/> in root When you find the Name property in the query element, start looking from the top element of the root stack, if you access the element in the specified stack <s:property value= "[1].name"/> The second element in the access stack the Name property * accesses the second element object <s: Property value= "[1].top"/> Usage: Projection mapping (combined with complex object traversal) 1) The projection of the collection (output only partial properties
Struts2 Tag Library
Tag-reference.html is the STRUTS2 label Specification 1, the common tag Library learning <s:property> parsing OGNL expressions, setting default values, setting whether the content is HTML escaped <s:set> Save data to four data ranges <s:iterator> traverse the value stack for data <s:if> <s:elseif> <s:else> condition judgment--------ElseIf can have multiple <s: url> URL Rewrite (track session), combined with S:param for parameter encoding * <s:url action= "Download" namespace= "/" var= "Myurl" ><s:param nam e= "filename" value= "%{' MIME protocol introduction. txt '}" ></s:param></s:url><s:property value= "#myurl"/><s: A> parameter encoding for a link * <s:a action= "Download" namespace= "/" > Download MIME protocol introduction. Txt<s:param name= "filename" value= "%{' M Introduction to IME protocol. txt '} ' ></s:param> </s:a>ognl Understanding section: Supports assignment operations and expressions concatenation, manipulating Collection Object 1) Save an object in the value stack <s:property value= " Price=1000,name= ' refrigerator ', getprice () "/> automatically finds the value stack for which the price and the name attribute are assigned 2) OGNL Operations collection <s:property value=" Products[0].name "/& Gt Access the first element of the collection Name property <s:property value= "map[' name ']"/> Access map in the value of key name {} directly constructs a list element, #{} directly constructs a MAP element <s:iterator Value= "{' AAA ', ' BBB '}" var= "S" ><s:property ValUe= "#s"/></s:iterator><s:iterator value= "#{' CCC ': ' 111 ', ' ddd ': ' 222 '}" var= "entry" ><s:property Value= "#entry. Key"/></s:iterator> 2, UI Tag Library learning (Form label) using STRUTS2 form tag benefits: Supports data echo, layout scheduling (based on freemarker template definition ) struts2 the form label Value property. Must write%{} to set the value ******* before using the Struts2 form label, you must configure Strutsprepareandexecutefilter the Struts dispatcher cannot be found. This was usually caused by using Struts tags without the associated filter. Struts tags is only usable when the request had passed through its servlet filter, which initializes the Struts Dispatche R needed for this tag <s:form> form label <s:form action= "Regist" namespace= "/" method= "POST" theme= "XHTML >--- Theme= "XHTML" Default layout style <s:textfield> build <input type= "text" ><s:password > Generate <input type= "password" &G T;<s:submit type= "Submit" value= "register"/> Generate <input type= "submit" ><s:reset type= "reset" value= "reset"/> Build <input type= "Reset" >* Struts2 supports two template technology Velocity, in addition to JSP support (extendedName. VM), Freemarker (extension. ftl) <s:textarea> generate <textarea> multiline text box <s:checkboxlist> generate a set of checkbox* using OGNL construction M AP (see Value and commit value not at the same time) * <s:checkboxlist list= "#{' Sport ': ' Sports ', ' read ': ' reading ', ' Music ': ' Musical '} ' name= ' Hobby ' ></s: Checkboxlist><s:radio> generates a set of radio* using the OGNL construct List (see content and commit values at the same time) * <s:radio list= "{' Male ', ' female '}" name= "gender" ></s:radio><s:select> generate a <select> * <s:select list= "{' Beijing ', ' Shanghai ', ' Nanjing ', ' Guangzhou '}" name= "City" > </s:select>============= struts2 Development Password box default does not echo <s:password name= "password" id= "password" showpassword= "true" />3, page element theme settings default.properties----struts.ui.theme=xhtml Settings struts2 page elements use the default theme struts . UI.TEMPLATESUFFIX=FTL Default Template engine Freemarker Modify theme mode one: <s:textfield name= "username" label= "user name" Theme= "Simple" >< ;/s:textfield> only valid for current element two: <s:form action= "" method= "Post" namespace= "/ui" theme= "simple" > Effective way for all elements in form Three: Struts.xml <constant name= "Struts.ui.Theme "Value=" simple ></constant> modify default theme style, page all elements are valid priority: Way one > Way two > Way three
Summary
1. File Upload
Struts2 study File Upload/download &valuestack (iii)