Struts + Spring + Hibernate Upload Download - Four

xiaoxiao2021-04-08  290

Web layer implementation 1. The component and interactive flow of the web layer include the main three functions: • Upload files. · List all lists of files that have been uploaded for clicking download. ·download file. Web layer implementation components include 2 JSP pages, 1 ActionForm, and an Action: · file-upload.jsp: page of upload files. File-list.jsp: The list page that has been uploaded. · FileActionform: file-upload.jsp page form corresponding to ActionForm. · FileAction: Inherits the action of org.apache.struts.Actions.dispatchaction, so this action can be in response to different requests via a URL parameter. The interactive flow of these components of the Web layer is shown in Figure 6

Figure 6 Struts flowchart of web layer

Among them, when executing the request uploaded request, FileAction is uploaded after executing the file, forward to the loadAllFile exit, the loadAllFile loads all the uploaded records in the database, then forward to the exit called FileListPage, call file-list.jsp page Displays records that have been uploaded. 2, FileAction Features Struts 1.0 Action has a weak term: an action can only process a request, and a Dispatchction is introduced in Struts 1.1, allowing a method in calling an action through the URL parameter, such as http: // YourWebsite / FileAction .do? method = UPLOAD is called the UPLOAD method in the fileAction. In this way, we can focus some relevant requests to an action, and there is no need to write an Action class for a request operation. But the parameter name is configured in struts-config.xml:

1. 2. 3. 4. 5. 6. 8. 9. 10. 11. 12.

The parameter = "method" of Chain 6 specifies the parameters of the bearer method name, in line 9, we also configure an Action exit that calls FileAction different methods. FileAction has three ways to request a response, which are: • Upload (...): Processing the request for uploading the file. ListAllFile (...): Processes the request for all records in the database table. Download (...): Processes the request for download files. Here we explain these three request processing methods respectively. 2.1 Uploading file Upload request processing method is very simple, in addition, is to obtain a business layer processing class FileService from the Spring container, call its Save (FileActionform Form) method upload file, as shown below: 1. Public class fileAction2. . extends DispatchAction3 {4. // save the upload to the database 5. public ActionForward upload (ActionMapping mapping, ActionForm form, 6 HttpServletRequest request, 7 HttpServletResponse response..) 8 {9. FileActionForm fileForm = (FileActionForm) form.; 10. FILESERVICE FILESERVICE = GetFileService (); 11. FileService.save (fileForm); 12. Return mapping.forward ("loadAllFile"); 13.} 14. Obtain FileService object from the Spring container 15. Private FileService getFileService .) 16 {17. ApplicationContext appContext = WebApplicationContextUtils.18 getWebApplicationContext (this.getServlet () getServletContext ());... 19 return (FileService) appContext.getBean ( "fileService");. 20} 21 ... 22}..

Since FileAction other two request processing methods also need to get a FILESERVICE instance from the Spring container, we specially provide a getFileService () method (line 15-12). A principle of reconstruction is: "There are repetitive expressions in the discovery code, extract it as a variable; found that there are repetitive code segments in the class, extract it as a method; found that there is the same method in different classes, will It is extracted as a class. " In a real system, there are often multiple Actions and multiple Service classes. At this time, a better settings is to provide a tool class that gets all service implementations, so you can block the Spring Service configuration information. In the class, otherwise the configuration name of the service is scattered in the procedures, and maintaining maintaining is very poor. 2.2 Lists all uploaded file listAllFile methods Call the Servie layer method to load all records in the T_FILE table, and save it in the Request domain, then Forward to the list page:

..... 1. public class FileAction2 extends DispatchAction3 {4. ... 5 public ActionForward listAllFile (.. ActionMapping mapping, ActionForm form, 6 HttpServletRequest request, 7 HttpServletResponse response) 8 throws ModuleException9 {10. FileService fileService = getFileService (); 11. List fileList = fileservice.getAllFile (); 12. Request.setttribute ("filelist", filelist); 13. Return mapping.forward ("filelistpage"); 14.} 15.} File-list.jsp page Using Struts Label showcases that are saved in the Request domain:

1. <% @ Page ContentType = "Text / HTML; Charset = GBK"%> 2. <% @ Taglib Uri = "/ Web-INF / STRUTS-Logic.TLD" prefix = "logic"%> 3. <% @Taglib URI = "/ Web-inf / struts-bean.tld" prefix = "bean"%> 4. 5. 6. file-download </ title> 7. </ head > 8. <Body bgcolor = "# ffffff"> 9. <Ol> 10. <Logic: Iterate ID = "item" name = "filelist" scope = "request"> 11. <Li> 12. <A href = 'fileAction.do?method=download.do = 13. <bean: write name = "item" property = "fileID" /> "> 14. <bean: write name =" item "property =" filename "/> 15. < / a> 16. </ logic: Itereate> 18. </ ol> 19. </ body> 20. </ html></p> <p>The display of the page is attached to a link address, such as: fileAction.do? Method = download & fileid = xxx, the method parameter specifies this request by the fileAction's Download method to respond, and the fileID specifies the recorded primary key. Due to the FileActionform, we define the properties of the fileID, so in the Download response method, we will be able to get the value of FileID from the FileActionForm. Here, it is related to a design problem for processing a plurality of ActionForm corresponding to a plurality of request ACTION. Since the original action can only correspond to a request, then the original ActionForm is very simple, it only needs to use this request as its attribute, But now an action corresponds to multiple requests, and the parameter items corresponding to each request are different. At this time, the attribute of the ActionForm must be a multi-request parameter item. Therefore, in addition to the filecontent and remark properties corresponding to the file upload request, the fileID property of the file is also included in the file: Figure 7 FileActionform</p> <p>Of course, this will cause redundancy, such as in the request, only filecontent and remark properties, while the fileId property is only used when the file download request is used. But this redundancy will bring benefits - it makes an action to handle multiple requests. 2.3 Download File Click on a file to download in the list page, requesting the fileAction's Download method to respond, the Download method invoke the FileService method of the business layer to get the file data and write to the response stream of Response. By reasonably set the HTTP response header parameters, the response stream is active as a download file dialog box, and its code is as follows: Code 10 Service Interface Implementation Class Download</p> <p>1. public class FileAction2. Extends DispatchAction3. {4. ... 5. Public ActionForward download (ActionMapping mapping, ActionForm form, 6. HttpServletRequest request, 7. HttpServletResponse response) 8. Throws ModuleException9. {10. FileActionForm fileForm = (FileActionForm) form ; 11 FileService fileService = getFileService ();.. 12 String fileName = fileService.getFileName (fileForm.getFileId ());.. 13 try14 {15. response.setContentType ( "application / x-msdownload");. 16 response. SetHeader ("Content-Disposition", 17. "Attachment;" "filename =" 18. New string (filename.getbytes (), "ISO-8859-1")); 19. FILESERVICE.WRITE (Response.Getputstream (), FileForm.GetFileId ()); 20.} 21. Catch (Exception E) 22. {23. Throw new moduleException (E.getMessage ()); 24.} 25. Return NULL; 26.} 27.</p> <p>Lines 15-18, set the HTTP response head, set the response type to the Application / X-MSDownload MIME type, then the response stream will pop up a file download dialog box, as shown in Figure 4. The MIME type supported by IE is more than 26, and you can view other MIME types with this URL: http://msdn.microsoft.com/Workshop/neetworking/moniker/overview/appendix_a.asp. If the file name of the download file contains Chinese characters, if you do not hardcode it, such as the 18th line, the file name that appears in the customer file download dialog will garbled. The 19-line code obtains the output stream of Response, as a FileServie Write (OutputStream OS, String FileID), such files will be written to the RESPONSE output stream. 3, configuring the Spring container when the web.xml file is started? I can initialize the Spring container to initialize the operation of the Spring container, and Spring provides two ways to start: • Through the org.springframework.web.context .contextLoaderListener container listener, trigger the initialization Spring container when the web container is initialized, It is configured by <Listener> </ Listener> in Web.xml. • Configure the Spring container through this servlet when it is initialized by servlet org.springframework.web.context.contextload.web.context.contextload.met. Before initializing the Spring container, you must initialize the log4j engine. Spring also provides the container listener and automatic start servlet to initialize the log4j engine: · org.springframework.web.util .log4jconfiglistener · Org.springframework.Web. Util.log4jconfigServlet Let's explain how to configure web.xml Start Spring Container: Code 11 Web.xml Corresponding to Spring Configuration</p> <p>1. <web-app> 2. <Context-param> 3. <Param-name> contextconfigLocation </ param-name> 4. <Param-value> /web-inf/applicationContext.xml </ param-value> 5 </ Context-param> 6. <Context-param> 7. <Param-name> log4jconfigLocation </ param-name> 8. <Param-value> /web-inf/log4j.properties </ param-value> 9 </ Context-param> 10. <Servlet> 11. <Servlet-name> log4jinitservlet </ servlet-name> 12. <Servlet-class> org.springframework.web.util.log4jconfigservlet </ servlet-class> 13. <Load-on-startup> 1 </ load-on-startup> 14. </ Servlet> 15. <Servlet> 16. <Servlet-name> SpringinitServlet </ servlet-name> 17. <Servlet-class> ORG. Springframework.Web.Context.contextLoaderServlet </ servlet-class> 18. <load-on-startup> 2 </ loading-on-startup> 19. </ servlet> 20. ... 21. </ web-app></p> <p>When starting the Spring container, you need to get two information: Spring profiles and log4j properties files, which are specified by the ContextConfigLocationWeb and Log4jconfigLocation container parameters, if there are multiple Spring profiles, with commas, such as: /WEB-INF/applicationContext_1.xml, /WEB-INF/applicationContext_1.xm2 since the ContextLoaderServlet before starting, the engine must first initialize Log4J, it must be started before the ContextLoaderServlet Log4jConfigServlet, which are specified by <load-on-startup> The order of launched. Corrupt code is a developing web application a comparison of old jackets, because the default coding of different web application servers is different, in order to facilitate Web applications to transplant on different web application servers, the best practice is to handle itself Code conversion work. The classic method is to configure an encoded conversion filter in Web.xml. Spring provides an encoded filter class CharacterencodingFilter, below, we configure this filter: 1. <Web-app> 2. ... 3. <Filter> 4. <Filter-name> Encodingfilter </ filter-name> 5. <Filter-class> org.springframework.web.filter.characterencodingfilter </ filter-class> 6. <Init-param> 7. <Param -name> Encoding </ param-name> 8. <param-value> GBK </ param-value> 9. </ init-param> 10. </ filter> 11. <filter-maping> 12. <filter- Name> EncodingFilter </ filter-name> 13. <URL-PATTERN> / * </ url-pattern> 14. </ filter-maping> 15. ... 16. </ web-app></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-132713.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="132713" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.046</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'QBwAMNYpMDdwaNlNt0KsOAiD588i_2BMRuF20A9HWuzu0eq1mQspZjj0j3SlvgxxZmGd_2FmHq_2FKIb_2Fl4OIKx0zWfA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>