First, Session
1. Introduction
HttpSession is a purely interface, the session itself belongs to the scope of the HTTP protocol.
The session function is to identify a session, or to confirm a user, and to share data during a session (a user requests multiple times).
2. Creating object and property operations
3, the session Jsessionid
Whenever a request arrives at the server, if the session is accessed, the server first checks to see if a cookie named Jsession is returned from the client, and if not, it is a new session, creating a new Sessions object. and use a unique jsessionid for this session to make a flag, if there is that it is a previously marked session, return the object, to achieve data sharing
4. Session Scope
As with the request domain, you can add data to the domain object by using the SetAttribute (Name,value) method, get the data from the domain object by getattribute (name), and pass the RemoveAttribute (name) Removes data from the domain object.
5, the session of the destruction
Because the session underlying is dependent on the cookie implementation and the cookie is valid for closing the browser, closing the browser session fails
The session is destroyed when the server is not properly shut down, and when the server is shut down gracefully, the session is serialized to disk and the next boot service is automatically loaded into memory.
Serialization: Saving an object and its state to a local disk
1) Default time expires
The session in Tomcat has a default survival time of 30min, which will be re-timed once a session is in operation.
2) Set the expiry time yourself
• Can be modified in the Web. xml file in Tomcat
session.setmaxinactiveinterval (int); In units of seconds
3) Immediate failure
Session.invalidate ();
The destruction or invalidation of the session means that the conversation technology, data sharing end.
Second, ServletContext object
1. Introduction
Each web app has and has only one ServletContext object, also known as an Application object, which is application-related and creates a corresponding ServletContext object for each Web application when the Web container starts.
2, the role of ServletContext objects
1) used as domain objects to share data, where data is shared throughout the application
2) This object holds information about the current application, which can be obtained by means of a method.
3. Four methods of obtaining ServletContext objects
4. As a domain object
By accessing data into ServletContext, you can allow the entire application to share some data, and it is not recommended to store too much data, because once the data in ServletContext is stored, no manual removal is saved
Third, file upload download
1. File Upload
Front page:
The enctype for the Post,form form must be set to "Multipart/form-data".
Backstage: Requires Commos-io and commons-fileupload two jar packages (2.5 version of Dynamic Web project)
protected voidService (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//set the encoding, you can get the Chinese file nameRequest.setcharacterencoding ("UTF-8"); //get the path to the upload directory under TomcatString path = Getservletcontext (). Getrealpath ("/upload"); //Temp file directoryString TempPath = Getservletcontext (). Getrealpath ("/temp"); //Check if we have a file upload request//Boolean ismultipart = Servletfileupload.ismultipartcontent (req); //1. Declare the Diskfileitemfactory factory class for setting up a temporary directory on the specified diskDiskfileitemfactory disk =NewDiskfileitemfactory (1024 * 10,NewFile (TempPath)); //2, declare servletfileupload, receive the above temporary file. can also be the default valueServletfileupload up =Newservletfileupload (disk); //3. Parsing request Try{List<FileItem> list =up.parserequest (Request); if(List.size () > 0) { for(Fileitem file:list)//determine if it is a normal form item if(File.isformfield ()) {String FieldName=File.getfieldname (); //Chinese garbled, at this time also need to specify how to encode the data obtained//String value = file.getstring ();String value = file.getstring ("UTF-8"); System.out.println (FieldName+ "=" +value); } Else{//description is a file//get the name of the file itselfString FileName =File.getname (); System.out.println (File.getfieldname ()); //working with file namesFileName = filename.substring (filename.lastindexof ("\ \") + 1); System.out.println ("Old Name:" +fileName); //Modify NameString extname = filename.substring (Filename.lastindexof ("."))); String NewName= Uuid.randomuuid (). toString (). Replace ("-", "") +Extname; //Save the new name and write it out to the new fileFile.write (NewFile (path + "/" +newName)); System.out.println ("File name is:" +fileName); System.out.println ("File size is:" +file.getsize ()); File.delete (); } } } Catch(fileuploadexception e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } }Upload
2. File download
Front desk:
Setting the Download property
Background implementation Download:
Public classDownloadservletextendsHttpServlet {@Overrideprotected voidService (HttpServletRequest req, HttpServletResponse resp)throwsservletexception, IOException {//Set Request response encodingReq.setcharacterencoding ("UTF-8"); Resp.setcontenttype ("Text/html;charset=utf-8"); //Get file nameString filename = req.getparameter ("filename"); //determine if the file name is empty if(FileName = =NULL|| Filename.length () < 1) {PrintWriter out=Resp.getwriter (); Out.write ("); Out.close (); return; } //get the directory where the files are storedString path = Getservletcontext (). Getrealpath ("/upload/"); //get the path to the fileString FilePath = path +FileName; //obtaining a file object from a pathFile File =NewFile (FilePath); //determine if the file object is not present and is a document if(File.exists () &&File.isfile ()) { //Download//1. Set the response typeResp.setcontenttype ("Application/x-msdownload"); //2, set the download popup informationResp.setheader ("Content-disposition", "attachment;filename=" +fileName); //3. Get byte input streamInputStream is=NewFileInputStream (FilePath); //3. Get byte output streamServletoutputstream out=Resp.getoutputstream (); byte[] bs=New byte[1024]; intLen=0; while((Len=is.read (BS))!=-1) {out.write (BS,0, Len); } out.close (); Is.close (); } Else{PrintWriter out=Resp.getwriter (); Out.write ("); Out.close (); } }}
Web Common Objects (2)