Message:
Session SendmailSession; sendmailsession = session.getInstance (props, null); Transfer mail is only sent or subject to two states. JavaMail describes both different states as transmission and storage. Transfer will send a message and save the message. Transport Transport; Transport = Sendmailsession.getTransport ("SMTP"); use JavaMail to save us a lot of time. JavaMail can replace all SMTP work. Note: JavaMail does not fully support all email to send charges. It currently only supports IMAP, SMTP, and POP3, in addition to this, you only wait for new JavaMail versions or its own development protocols. Information object information object will reflect the message you sent true. Message newMessage = new mimeMailSession; this is all the four objects we need. The next step will be how to add objects to JSP. Part III: JavaMail and JSP Creating JSP Under the JSP, we will start combining them together. The most important point is to confirm that the classification is based on the page. Also remember to mark java.util.date on the email. <% @ page import = "javax.mail. *, javax.mail.internet. *, javax.activation. *, java.util. *"%> Second, create a confirmation information sent by mail. Confirm that the information can be arbitrary, generally used "Your mail has been sent out." How to create and send us in the second part I have discussed the creation of information objects. We will follow the information below. This is as simple as the properties of the setting information object. You can implement this operation by the following program. newMessage.setFrom (new InternetAddress (request.getParameter ( "from"))); newMessage.setRecipient (Message.RecipientType.TO, new InternetAddress (request.getParameter ( "to"))); newMessage.setSubject (request.getParameter ( "Subject")); newMessage.setSentDate (new time ()); newMessage.Settext (Request.getParameter ("text"))); now will start sending information. It is very simple to achieve through JavaMail. Transport.send (newMessage); all components are all fully all components now. Now put them in JSP. Pay attention to each error message and feed back it to the user.
The code is as follows, you can use them directly: sample jsp email utility using javamail <% @ page import = "javax.mail. *, Javax.mail.internet. *, Javax.activation. *, Java.util. *" %>
JSP Meets JavaMail, What a sweet combo. title> head> <% try {profmentness pROPS = New Properties (); SESSION SendmailSession; store store transport; sendMailSession = Session.getInstance (props, null); props.put ( "mail.smtp.host", "smtp.jspinsider.com"); Message newMessage = new MimeMessage (sendMailSession); newMessage.setFrom (new InternetAddress ( request.getParameter ( "from"))); newMessage.setRecipient (Message.RecipientType.TO, new InternetAddress (request.getParameter ( "to"))); newMessage.setSubject (request.getParameter ( "subject")); newMessage .SetSentDate (New Date ()); NewMessage.Settext (Request.getParameter ("text")); Transport = SendmailSession.getTransport ("SMTP"); Transport.send (newMessage);%> Your mail Has Been SENT. p> <%} catch (messagingException m) {OUT.PRINTLN (M.TOString ());}%> body> HTML> You will quickly experience the convenience of JavaMail, JSP and JavaMail will be the future hope.
File / image upload package uploadfile; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import java.io.FileOutputStream; import java.io. *; import java.util.Hashtable; import java.util *. Public class fileuploadbean {private string savePath = null; // File upload saved path private string contentType = ""; // Content Type Private string Charencode = null; // Character Coded Private String Boundary = ""; // Direction Line Private string filename = null; // Local file name Private HashTable DIC = new hashtable (); // Used to save "Element Name - Element Value" to private int totalsize = 0; // Upload file total size private string path = ""; // Path of the file private string newFileName = ""; // Deposits the randomized file name /// // Setting the file upload saved path PUBLIC VOID SetsavePath (String s) {s = path s; SavePath = S; System.out.Println ("Upload Path:" SavePath);} // // Take the file uploaded path PUBLIC STRING GETSAVEPATH () {Return SavePath;} // Settings the file name, or It is named, temporarily uses its original name public void setfilename (string s) {int pos = s.indexof ("/"; filename = / "); if (pOS> 0) {s = s.substring (POS 13, S.Length () - 3); // Go "and CRLF POS = S.lastIndexof (" // "); if (POS <0) POS = S.lastin DEXOF ("/"); if (POS <0) filename = S; filename = s.substring (POS 1);} // Get file name public string getFileName () {system.out.println ("get file Name " newfilename"; Return NewFileName;} // // Generate a new file name for seed Number PUBLIC STRING GETNewFileName () {INT POS = 0; //. LONG SEED = 0; // Random Seed Number String ext = ""; // Deposit file extension System.out.Println ("Upload File Name: filename); POS = filename.lastIndexof (". "); Ext = filename.substring (POS); / / Get the extension seed = new date (). Gettime (); random rand = new random (seed);
// Generate random numbers as file name newfilename = long.toString (math.Abs ()) ext; // generated file name system.out.println ("new file name:" "NEW FILE NAME:" newFileName); return newFileName;} // // set the character encoding public void setCharEncode (HttpServletRequest req) {charEncode = req.getCharacterEncoding ();} / // set ContentType public void setBoundary (HttpServletRequest req) {// pass The parameter value is similar "Multipart / Form-Data; Boundary = -------------------------- 7D21441A30013C" // pass the boundary ratio There are two more than two "-" bashary = req.getContentType () ("boundary"); int pos = boundary.indexof ("boundary ="); int pos = boundary.indexof ; // Plus these two "-" boundary = "-" boundary.substring (POS 9);} // gets the contentTyPE PUBLIC STRING GetBoundary (// Return value ------- ------------------------ 7D214441A30013C "Return Boundary;} // Set ContentTyPE PUBLIC VOID SETCONTENTTYPE (String s) {INT POS = S.indexof ":"); if (pOS! = - 1) ContentTyPE = S.SUBSTRING (POS 2);} // Get contentTyPE PUBLIC STRING GETCONTENTTYPE () {Return ContentType;} // Initialization Public Void Init (httpservletRequest REQ) {setCharencode REQ); setBoundary (REQ);} // Take the data in the Hash table PUBLIC STRING GETFIELDVALUE (String S) {String Temp = "; if (DIC.Containskey (s)) // Is there a S button in the table , Returns nullpointerException {temp = temp.trim (); TEMP = TEMP.TRIM ();} else temp = ""; return temp;} Generate string Public String Newline with the specified encoding method byte oneLine [], int sp, int i, String charEncode) throws java.io.UnsupportedEncodingException {sp = 0; // start position String lineStr = null;! if (charEncode = null) {return lineStr = new String (oneLine, SP, I, Charencode; // Generate Strings with the specified encoding} else {return linestr = New String (OneLine, SP, I);
}}} // // Get the size of the upload file Public INT GetTotalsize ()} // // Delete the file published by the specified path public boolean DelFiles (String Fn) // FN is the name of the file to be deleted Does not include path {Try {file file = new file (savepath fn); system.out.println (SavePath Fn); if (file.exists ()) {file.delete (); system.out.println File.getPath () "Delete File Success"); return true;} else {system.out.println ("The File is not existed!"); return true;}} catch (Exception E) {system.out .println (e.tostring ()); returnaf ()}} // File list public string [] listfiles (string fp) {string [] lf = null; try {savePath = path fp; file file = new file SavePath); lf = file.list (new dirfilter ()); for (int i = 0; i = 0) BREAK; if (LineStr.StartSwith ("Content-Disposition: Form-Data; Name = /")) {// Separation Data Because the form element is also uploaded, there are other data, the value IF corresponding to the content, form elements, and form elements of the file we are useful (LINESTR.Indexof ("/")> filename = / "")> = 0) {// is the file input domain // set file name setFileName (LINESTR); if (! Filename.equals (""
))) {// If the file name is a vacancy / / extracts the value of the form element name and the form element POS = linestr.indexof ("Name = /"); POS2 = linestr.indexof ("/"; filename = / ""); // Form element name FieldName = linestr.substring (POS 6, POS2); // Form element value FieldValue = linestr.substring (POS2 13, LINESTR.LENGTH () - 3); // Join the hash table Dic.Put (FieldName, FieldValue); Sis.Readline (OneLine, 0, OneLine.Length); // Read the data similar to "Content-Type: Text / Plain" SIS.Readline (OneLine, 0 OneLine.Length); // Space // Create file output fos = new fileoutputstream (new file (getSavePath (), getnewfilename ())); // Start reading file data i = Sis.Readline (OneLine, 0, OneLine.Length); While (I! = - 1) {Totalsize = i Totalsize; LINESTR = Newline (OneLine, 0, I, Charencode); if (Linestr.Indexof (GetBoundary ())> = 0) Break; / / Indicates that the data is read in this file, Fos.Write (OneLine, 0, I); i = Sis.Readline (OneLine, 0, OneLine.Length);} // end while fos.close ();} // END IF (! getFilename (). Equals ("))} else {// Non-file input field POS = linestr.indexof (" name = / "); // Form element name FieldName = linestr.substring (POS 6, LINESTR.LENGTH () - 3); // Reads Sis.Readline (OneLine, 0, Online.Length); // This line contains elemental values, such as empty, this line is also empty , String Temp = ""; i = " Sis.readLine (OneLine, 0, OneLine.Length); While (I! = - 1) {TEMP = Newline (OneLine, 0, I, Charencode); if (Temp.indexof (GetBoundary ())> = 0) Break FieldValue = FIELDVALUE TEMP; I = Sis.Readline (OneLine, 0, OneLine.Length);} // joined DIC.PUT (FieldName, FieldValue) in the hash table; FieldValue = "";}} i = sis. Readline (OneLine, 0, OneLine.Length);} // end while sis.close (); return true;} // end doupload //}} {DIC.CLIC (); if () {DIC.CLEAR (); IF Dic.isempty ()) {system.out.println ("empty");} else {system.out.println ("Not Empty");
}}} // // The main function of the test public static void main (string args []) {string [] filelist = null; tryuploadbean fub = new fileuploadBean (); filelist = fub.listfiles ("/ avatars /" ); for (int i = 0; I
When the file is selected, it returns false. When the file is not selected, it returns True. Prototype: public boolean ismissing () 3, getfieldname effect: Take the name of the form item corresponding to this uploaded file in the HTML form. Prototype: public string getfieldname () 4, getFileName effect: Take a file name (excluding directory information) prototype: public string getFileName () 5, getFilepathname effect: Take a full name (with directory) prototype: public string getFilePathname 6, getFileExt : Take a file extension (suffix) prototype: public string getfileext () 7, getSize effect: Take a file length (in bytes) prototype: public int gettsize () 8, getBinaryData effect: Take one of the file data indicated in the file data Bytes, used to detect files, etc. Prototype: Public Byte GetBinaryData (int index). Among them, Index represents the displacement, its value is between 0 and GetSize () - 1. (Ii) Files class This class represents the collection of all uploaded files, which can get the number, size and other information of the upload file. There are the following methods: 1. GetCount role: Number of uploaded documents. Prototype: Public int getCount () 2, getFile effect: obtain the file object file in the specified displacement (this is com.jspsmart.upload.file, not java.io.file, pay attention to distinguish). Prototype: Public File GetFile (int index). Where index is a pointing, its value is between 0 and GetCount () - 1. 3, GetSize effect: Take the total length of the upload file, which can be used to limit the amount of data amounts uploaded. Prototype: Public long getSize () 4, getCollection effect: Return all uploaded file objects in the form of Collection so that other application references, browse upload file information. Prototype: Public Collection getCollection () 5, GetEnumeration effect: Return all upload file objects in ENUMERATION (enumeration) so that other applications browse uploaded file information. Prototype: Public Enumeration GetENUMERATION () ㈢ Request class This class is equivalent to the built-in object Request with the JSP. Only, this class is provided because the value of the form item cannot be obtained through the Request object for the file upload form. It must be obtained by the Request object provided by the JSPSmartupLoad component. This class provides the following methods: 1. GetParameter effect: Get the value of the specified parameter. When the parameter does not exist, the return value is NULL. Prototype: Public String getParameter (String name). Where Name is the name of the parameter. 2, GetParameterValues effect: When a parameter can have multiple values, use this method to take the value. It returns a string array. When the parameter does not exist, the return value is NULL.
Prototype: public string [] getParameterValues. Where Name is the name of the parameter. 3. GetParameterNames effect: obtain the name of all parameters in the Request object, used to traverse all parameters. It returns an enumerated object. Prototype: public enumeration getParameterNames ()
㈣ SmartUPload class This class completes upload download work. A. Method for uploading and downloading shared: there is only one: Initialize. Role: Execute the initialization work of upload download, must be the first execution. Prototype: There are multiple, mainly using this: public final void initialize (javax.servlet.jsp.pagecontext pagecontext) where PageContext is a JSP page built-in object (page context). B. Method for Uploading files: 1, Upload effect: Upload file data. For upload operations, the first step is executed, and the second step is to perform this method. Prototype: Public Void Upload () 2, SAVE Role: Save all upload files to the specified directory and return the number of files saved. Prototype: Public int SAVE (String destPathname) and public int save (string destpathname, int option) where destPathname is a file saved directory, Option is saved, which has three values, Save_Physical, Save_Virtual and Save_Auto. (Similar to the value of the SaveAs method of the FILE class) Save_physical indicates that the component saves the file to the directory of the operating system root to the root directory, save_virtual indicates that the file saves the file to the web application root directory as the file root directory. In the directory, Save_AUTO indicates automatic selection by the component. Note: The effect of Save is equivalent to Save (Destpathname, Save_AUTO). 3, GetSize effect: Take the total length prototype of the upload file data: public int getSize () 4, getFiles effect: Take all uploaded files, return to the Files object, you can use the Files class to get the number of uploaded files, etc. . Prototype: Public Files getFiles () 5, getRequest effect: obtain the Request object so that this object obtains the value of the upload form single parameter. Prototype: Public Request getRequest () 6, SetallowedFileSlist effect: Settings Allow upload with files with specified extensions, the components will throw an exception when there is a file name in the upload. Prototype: Public Void SetAllowedFileSlist (String ALLOWEDFILSL) where allowedFileSlist is a comma-separated list of file extensions to allow uploaded file extensions. If you want to allow files that do not have extensions, you can use two comma. For example: SETALLOWEDFILSLIST ("DOC, TXT,") will allow files with DOC and TXT extensions and files without extensions. 7, SetDeniedFileSlist effect: Used to address those files with specified extensions. If there is a file extension being restricted, the upload component will throw an exception. Prototype: Public void setdeniedFilesList (String DeniedFilesList) where DeniedFileSlist is disabled from the uploaded file extension list, each extension is separated by commas. If you want to prohibit uploading files that do not have extensions, you can use two commas to represent.
For example: SetDeniedFileSlist ("EXE, BAT,") will disable files with EXE and BAT extensions and files without extensions. 8, SetMaxFileSize effect: Set the maximum length of each file to be uploaded. Prototype: Public Void SetMaxFileSize (long maxfilesize) where the maxFileSize allows uploading the maximum length for each file. When the file exceeds this length, it will not be uploaded. 9, SetTotalMaxFileSize effect: Set the total length of the file that allows uploaded files to limit the amount of data of a disposable upload. Prototype: Public void setTotalmaxFileSize (long TotalmaxFileSize) where TotalMaxFileSize is the total length of the file that allows uploaded files.
JSP upload images and generate a zoom chart or add some websites, add the picture, add the picture, add your own words (add your own words (add) How to implement it in the JSP? ? // add watermark, filePath source image path, watermark watermark image path public static boolean createMark (String filePath, String watermark) {ImageIcon imgIcon = new ImageIcon (filePath); Image theImg = imgIcon.getImage (); ImageIcon waterIcon = new ImageIcon ( watermark); Image waterImg = waterIcon.getImage (); int width = theImg.getWidth (null); int height = theImg.getHeight (null); BufferedImage bimage = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = BIMAGE.CREATEGRAPHICs (); g.setColor (Color.red); g.setBackground (color.white); g.drawImage (THEIMG, 0, 0, NULL); G.DrawImage (WaterImg, 100, 100, null); g.drawString ( "12233", 10,10); // add text g.dispose (); try {FileOutputStream out = new FileOutputStream (filePath); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam (BIMAGE); param.setquality (50f, true); encoder.encode (bimage, param); out.close ();} catch (exception e) {return false;} return true;} / example package package; import java .io. *; import javax.servlet.servletException ; Import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; public class upload {private static String newline = "/ n"; private String uploadDirectory; private String ContentType; private String CharacterEncoding; public upload () {uploadDirectory = "."; Contentty = ";} private string getFilename (string s) {INT i = s.lastindexof (" // "); if (i <0 || i> = s.ley" ) - 1) {i = s.lastIndexof ("/"); if (i <0 || i> = s.length () - 1) Return S;
} Return s.substring (i 1);} public void setUploadDirectory (String s) {uploadDirectory = s;} public void setContentType (String s) {ContentType = s; int i; if ((i = ContentType.indexOf ( " boundary = ")) = -1) {ContentType = ContentType.substring (i 9); ContentType =!" - " ContentType;}} public void setCharacterEncoding (String s) {CharacterEncoding = s;} public String uploadFile ( HttpServletRequest httpservletrequest) throws ServletException, IOException {String s = null; setCharacterEncoding (httpservletrequest.getCharacterEncoding ()); setContentType (httpservletrequest.getContentType ()); s = uploadFile (httpservletrequest.getInputStream ()); return s;} public String uploadFile ( ServletInputStream servletinputstream) throws ServletException, IOException {String s = null; String s1 = null; byte abyte0 [] = new byte [4096]; byte abyte1 [] = new byte [4096]; int ai [] = new int [1] ; intloy1 [] = new int [1]; String S2; While ((S2 = Readline (Abyte0, Ai, ServletInputStream, Characterencoding))! = null) {Int i = S2.indexof ("filename =") ; if (i> = 0) {s2 = s2.substring (i 10); if ((i = s2.indexof ("))> 0) S2 = s2.substring (0, i); BREAK }}} S1 = S2; IF (S1! = NULL &&! S1.Equals ("/")) {S1 = getFileName (S1); String S3 = Readline (Abyte0, Ai, ServletInputStream, Characterencoding); if (S3 .indexOf ( "Content-Type")> = 0) readLine (abyte0, ai, servletinputstream, CharacterEncoding); File file = new File (uploadDirectory, s1); FileOutputStream fileoutputstream = new FileOutputStream (file); while ((s3 = readLine (Abyte0, Ai, ServletInputStream, Characterencoding)! =
NULL) {IF (S3.Indexof (ContentType) == 0 && Abyte0 [0] == 45) Break; if (s! = null) {FileOutputStream.write (Abyte1, 0, Ai1 [0]); FileOutputStream.flush ();} s = readline (Abyte1, Ai1, servletinputStream, characterencoding); if (s == null || s.indexof (contentty) == 0 && abyte1 [0] == 45) Break; FileOutputStream.write (Abyte0 , 0, Ai [0]); FileOutputStream.flush ();} byte byte0; if (newline.Length () == 1) BYTE0 = 2; elsebyte0 = 1; if (s! = Null && abyte1 [0]! = 45 && ai1 [0]> newline.Length () * byte0) FileoutputStream.write (Abyte1, 0, Ai1 [0] - newline.Length () * Byte0); if (S3! = Null && abyte0 [0]! = 45 && ai [0]> Newline.Length () * byte0) FileoutputStream.write (Abyte0, 0, Ai [0] - newline.Length () * Byte0); fileoutputstream.close ();} return s1;} private String readline (byte abyte0 [], intloy [], servletinputstream servletinputstream, string s) {ai [0] = servletinputStream.readLine (Abyte0, 0, Abyte0.Length); if (Ai [0] == -1) Return NULL; BREAK MISSING_BLOCK_LABEL_27; Object Obj; Obj; Return Null; if (s == null) Return New String (Abyte0, 0, Ai [0]); Return New String (Abyte0, 0, Ai [0], S); Obj; Return Null;}} JSP Page: <% @ Page ContentType = "Text / HTML; Charset = GB2312" Import = "package.upload"%> <% string dir = "c: / dir / upload"; string fn = ""; upload upload = new upload (); UPLOAD.SETUPLOADDIRECTORY (DIR); fn = upload.uploadfile (request) %>%>
转载请注明原文地址:https://www.9cbs.com/read-13618.html