JSP skills

zhaozj2021-02-16  65

JSP skills

The first school JSP experience test environment is JDK1.2.2 JSWDK-1.0 WinNT4.0 Chinese version. 1. Java is sensitive, people who have used other programming languages ​​are the easiest to commit this mistake, especially when I just came. It is because it is because of this. 2. The Java's calling process is to be added, and it is easier to ignore at the beginning, such as title = request.getParameter (/ "title /"). Trim (); 3. The solution to the request.form () and Request.QueryString () in the JSP. The parameters in JSP do not have FORM and QueryString points, all through Request.getParameter (/ "xxxx /"). Although JSP also has a request.getQueryString () method, the test result is Test.jsp? Id = 1 & Page = 20 Get ID = 1 & Page = 20. If the URL and FORM have the same parameter name? Below is a test code:

Name is the ID, the result is the parameter of the URL is prioritized, and this processing method of JSP and the ASP have their own strengths. 4. Chinese character treatment problem with headache. In other articles, I have said that the statement output is garbled in the Chinese NT environment, <% = / "Hello /"%> and out.print (/ "Hello /"); The solution is to get the correct result as long as the string variable can be encoded, the following code can get the correct output: <% string title = / "Hello /"; Byte [] TmpByte = Title.getbytes (/ "ISO8859_1 /" ); Title = new string (TMPBYTE); out.print (title);%> or <% = title%> About SQL statement Chinese character issues, Driven DB2, whether the original sentence is still in the SQL statement, it is aligned. After changing the IBM's JDBC, the program can pass the program to the SQL statement. The generation of this problem is probably the reason for Chinese NT. In other environments, there may be no Chinese characters, it is said that IBM's Web Sphere is very good for Chinese support, which also brings a generic issue for JSP development. It is said that the string coding is a general solution, but there is not so much environment to test. 5.

The string judgment statement is often used in the ASP, such as if state = / "True," THEN .................................................................................................................................................... a. String str1 = / "I am a fool /"; string str2 = / "I am a fool /"; (or string str2 = / "I /" / "fool /";) IF (str1 == str2) Out.print (/ "yes /"); else out.print (/ "no /"); the result is / "yes /". Probably compilation optimization, STR1, STR2 points to the same class instance; b. String str1, str2, str3; str1 = / "I am a fool /"; str2 = / "I /"; str3 = str2 / "fool /" ; if (str1 == str3) Out.print (/ "yes /"); else out.print (/ "no /"); the result is / "no /". String str1 = new string (/ I am a fool / "); string str2 = new string (/" I am a fool / "); if (str1 == str2) Out.print (/" yes / "); else Out .print (/ "no /"); result is / "no /". String str1 = new string (/ "I am a fool /"); string str2 = new string (/ "I am a fool /"); if (str1.compareto (str2) == 0) Out.print (/ "YES / "); else out.print (/" no / "); the result is /" yes / ". Therefore, in JSP to determine the string to use the Compareto method, it is true that the traditional language is really adapted, but friends who are familiar with Java should have no problem. 6. How to determine the database empty? Result = stmt.executeQuery (SQL); if (result.next ()) ... Result execution, the cursor is out of an unprecedented state, and cannot be judged, and the value cannot be taken, it must be next () Can be used. 7. Implement pagination in JSP. Page is keyword and cannot be variables.

Conn.jsp <% string sdbdriver = / "com.ibm.db2.jdbc.app.db2driver/; string sconnstr = / "jdbc: db2: faq /"; connection conn = null; statement stmt = null; ResultSet RS = Null; try {class.forname (sdbdriver);} catch (java.lang.classnotfoundexception e) {out.print (/ "FAQ (): /" E.getMessage ());} Try {conn = drivermanager.getConnection (Sconnstr, / "wsdemo /", / "wsdemo1 /"); stmt = conn.createstatement ();} catch (sqlexception e) {output (e.tostring ());}%> query.jsp <% @ Page language = / "java /" import = / "java.sql. * /"%> <% @ page contenttype = / "text / html; charSet = GB2312 /"%> <% @ include file = / "conn .jsp / "%> <% ....... int Pages = 0; int Pagesize = 10; ResultSet Result = null; ResultSet rcount = null; Pages = new integer (/" pages / ") ) .intValue (); if (pages> 0) {string SQL = / "state = 'I am not stupid' /"; int count = 0; try {rount = stmt.executeQuery (/ "select count (id) AS ID From user where / " sql); catch (sqlexception ex) {out.print (/" aq.ex EcuteQuery: / " ex.getMessage ());} if (ruit.next ()) count = rcount.getint (/" id / "); rcount.close (); if (count> 0) {SQL = / "Select * from user where /" sql; try {result = stmt.executeQuery (SQL);} catch (sqlexception ex) {out.print (/ "aq.executeQuery: /" ex.getMessage ());} INT I; String name; // result.first (); // result.absolute ((pages-1) * pageSize; // This method JDBC2.0 support. Compiled, but implementation, I don't know if it is related to the driver, I have to use the following stupid approach.

For (i = 1; i <= (PAGES-1) * Pagesize; i ) Result.next (); for (i = 1; i <= pageSize; i ) {if (result.next ()) {name = Result.getstring (/ "name /"); out.print (name);} result.close (); int N = (int); if (n * pagesize 1) {for (i = 1; i <= n; i ) Out.print (/ " /" i / " / ");}}}%> How to connect, how old is wrong? So I concentrated on this article for your reference. In fact, this kind of database logic is not necessarily good in JSP, but it is conducive to beginners to learn, so I will do this, when you learn a certain degree At the time, you can consider the development of MVC. When you practice these code, you must put the JDBC driver in the server classpath, then build a table test in the database, there are two fields such as Test1, Test2, you can build Create Table Test with the following SQL (Test1 Varchar (20), Test2 Varchar (20) Then write to this table to a test record so now start our JSP and database trip.

I. JSP connection Oracle8 / 8i / 9i database (with Thin mode) TestoCle.jsp as follows: <% @ page contenttype = "text / html; charset = GB2312"%> <% @ Page Import = "java.sql. *" %> <% class.Forname ("Oracle.jdbc.driver.Oracledriver). NewInstance (); string url =" JDBC: Oracle: Thin: @localhost: 1521: ORCL "; // orcl SID String user to your database = "scott"; String password = "tiger"; Connection conn = DriverManager.getConnection (url, user, password); Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String SQL = "Select * from test"; ResultSet RS = Stmt.executeQuery (SQL); while (rs.next ()) {%> Your first field content is: <% = rs.getstring (1)% > Your second field content is: <% = rs.getstring (2)%> <%}%> <% out.print ("Database operation success, congratulations");%> <% rs.close ); stmt.close (); conn.close ();%> 2, JSP connection SQL Server7.0 / 2000 database TestsqlServer.jsp is as follows: <% @ page contenttype = "text / html CHARSET = GB2312 "%> <% @ page import =" java.sql. * "%> <% class.forname (" com.microsoft.jdbc.sqlser.sqlserverdriver). NewInStance () String url = "JDBC: Microsoft: SQLserve R: // localhost: 1433; databasename = PUBS "; // pubs for your database String User =" SA "; string password ="; connection conn = drivermanager.getConnection (URL, User, Password); Statement Stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql = "select * from test"; ResultSet rs = stmt.executeQuery (sql); while (rs.next ()) {%> your first Field content is: <

% = rs.getstring (1)%> Your second field content is: <% = rs.getstring (2)%> <%}%> <% out.print ("Database operation is successful, congratulations") ;%> <% rs.close (); stmt.close (); conn.close ();%> 3, JSP connection DB2 database TESTDB2.JSP is as follows: <% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ page import = "java.sql. *"%> <% class.forname ("com.ibm.db2.jdbc.app.db2driver ") .newinstance (); string url =" jdbc: db2: // localhost: 5000 / sample "; // Sample for your database name string user =" admin "; string password ="; connection conn = drivermanager. getConnection (url, user, password); Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql = "select * from test"; ResultSet rs = stmt.executeQuery (sql); while (rs.next () {%> Your first field content is: <% = rs.getstring (1)%> Your second field content is: <% = rs.getstring (2)%> <%}% > <% out.print ("Database Operation, Congratulations");%> <% rs.close (); stmt.close (); Conn.Close ();%> four , JSP connection Informix database Testinformix.jsp is as follows: <% @ Page ContentType = "text / html; charset = GB2312"%> <% @ page import = "java.sql. *"%> <% Class.f orName ( "com.informix.jdbc.IfxDriver") newInstance (); String url =. "jdbc: informix-sqli: //123.45.67.89: 1533 / testDB: INFORMIXSERVER = myserver; user = testuser; password = testpassword"; // TestDb for your database name Connection Conn = DriverManager.getConnection (URL); Statement Stmt = Conn.createStatement (ResultSet.Type_Scroll_Sensitive, ResultSet.concur_updatable);

String SQL = "Select * from test"; ResultSet RS = Stmt.executeQuery (SQL); while (rs.next ()) {%> Your first field content is: <% = rs.getstring (1)% > Your second field content is: <% = rs.getstring (2)%> <%}%> <% out.print ("Database operation success, congratulations");%> <% rs.close ); stmt.close (); conn.close ();%> 5, JSP connection Sybase database TestMysql.jsp is as follows: <% @ Page ContentType = "text / html; charset = GB2312" %> <% @ page import = "java.sql. *"%> <% class.forname ("com.sybase.jdbc.sysybdriver). NewInstance (); string url =" JDBC: Sybase: TDS: Localhost: 5007 / TSData "; // Tsdata For your database name Properties System.getProperties (); sysprops.put (" user "," userid "); sysprops.put (" password "," user_password "); Connection conn = DriverManager.getConnection (url, SysProps); Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql =" select * from test "; ResultSet rs = stmt.executeQuery (sql ); while (rs.next ()) {%> Your first field content is: <% = rs.getstring (1)%> Your second field content is: <% = rs.getstring (2 )%> <%}%> <% out.print ("Database operation success, congratulations");%> <% rs.close (); stmt.cl OSE (); conn.close ();%> six, JSP connection mysql database TestMysql.jsp is as follows: <% @ Page ContentType = "text / html; charSet = GB2312"%> <% @Page import = "java.sql. *"%> <% class.forname ("org.gjt.mm.mysql.driver). NewInstance (); string url =" jdbc: mysql: // localhost / Softforum? User = Soft & Password = SOFT1234 & UseUnicode =

true & characterEncoding = 8859_1 "// testDB name for your database Connection conn = DriverManager.getConnection (url); Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql =" select * from test "; ResultSet rs = Stmt.executeQuery (SQL); while (rs.next ()) {%> Your first field content is: <% = rs.getstring (1)%> Your second field content is: <% = rs.getstring (2)%> <%}%> <% out.print ("Database operation success, congratulations");%> <% rs.close (); stmt.close (); conn.close ( );%> seven, JSP connection PostgreSQL database TestMysql.jsp is as follows: <% @ Page ContentType = "text / html; charset = GB2312"%> <% @ page import = "java.sql . * "%> <% class.forname (" org.postgreSql.driver). Newinstance (); string url = "jdbc: postgreSQL: // localhost / soft" // Soft for you database name String user = "myuser"; String password = "mypassword"; Connection conn = DriverManager.getConnection (url, user, password); Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql = " Select * from test "; ResultSet RS = stmt.executequery (SQL); while (rs.next ()) {% > Your first field content is: <% = rs.getstring (1)%> Your second field content is: <% = rs.getstring (2)%> <%}%> <% OUT. Print ("Database Operation, Congratulations");%> <% rs.close (); stmt.close (); conn.close ();%>

Using the SmartUPload component upload file JSP in JSP JSP's support for upload files is not as good as PHP, directly forms a function, nor is it possible to implement it in the ASP. JSP can be implemented through JavaBean. But we don't have to write an uploaded bean yourself, there is a lot of forming techniques on the Internet, and smartupload is one of them. However, smartupload is in the memory of the server first, so the upload too large file (more than 100 trillion) may have problems, it is a beautiful lack of beauty :) Let's talk about the page, SmartUPload component requires bytes The way to submit .

Here is an example upload.htm: < / Head>

file:
File: file:
Take a look at the received page, we put the file After uploading to the server, then store it directly into the database: upload.jsp <% @ Page ContentType = "text / html; charset = GB2312"%> <% @ page import = "JAV A.sql. * "%> <% @ page import =" com.jspsmart.upload. * "%> <% @ page import =" dbstep.idbmanager2000. * "%> <% // instantiation to upload beancom.jspsmart .UPLOAD.SMARTUPLOAD MYSMARTUPLOAD =

New com.jspsmart.upload.smartupload (); // Initialization MySmartupload.initialize (PageContext); // Set the maximum maximum mysmartupload.setmaxFileSize (500 * 1024 * 1024); // Upload file mysmartupload.upload (); / / Loop acquire all uploaded files for (int i = 0; i

DBAOBJ.CONN.COMmit (); Out.Println ("" uploaded success !!! "). TOSTRING ());} else {out.println (" upload failed !!! "). Tostring ());} } // correspondence with the previous IF> Let's talk, download, download two cases 1. Download directly from the database 2.

Downloading from the server first says directly from the database directly downloaded the input stream from the input stream from the database, then transfer to file <% @ page contenttype = "text / html; charset = GB2312"%> <% @ Page Import = "java.sql. *"%> <% @ page import = "java.io. *"%> <% @ page import = "dbstep.idbManager2000. *"%> <% int Bytesum = 0; int Byteread = 0; // open the database ResultSet result = null; String Sql = null; PreparedStatement prestmt = null; DBstep.iDBManager2000 DbaObj = new DBstep.iDBManager2000 (); DbaObj.OpenConnection (); // acquired data database Sql = "select * from t_local_zhongzhuan "; result = DbaObj.ExecuteQuery (Sql); result.next (); // read the data in the database stream InputStream inStream = result.getBinaryStream (" content "); FileOutputStream fs = new FileOutputStream (" C: /dffdsafd.doc "); Byte [] buffer = new byte [1444]; int = - 1) {Out.println ("

< B> " Byteread " "); bytesum = byteread; system.out.println (bytesum); fs.write (buffer, 0, byteread);}%> Saying from the server download Something: <% @ page contenttype = "text / html; charset = GB2312"%> <% @ page import = "java.io. *"%> <% string filename = "zsc104.swf" .tostring (); f // Read the infutstream instream = new fileinpu TSTREAM ("C: /ZSC104.SWF"); // Set the format of the output response.reset (); response.SetContentType ("bin"); response.addheader ("Content-Disposition", "Attachment; filename = /" " filename " / ""); // cycle to remove data in the stream Byte [] b = new byte [100]; int Len; while ((len = instream.read (b))> 0) Response.getOutputStream () .write (b, 0, len); instream.close ();%> Ok, you can do it as long as it is not too big to upload the downloaded operation.

Thumbnail implementation, the actual change of the image (JPG, GIF, BMP, etc.) into the desired size import java.io. *; Import java.util. *; Import com.sun.Image.codec.jpeg. *; Import java.awt.image. *; import java.awt. *; import java.net. *; import java.applet. *; import java.sql. *; // thumbnail class, // This Java class can JPG image file, aliquot or non-equivalent size conversion.

// Specific use method // s_pic (large image path, generate small picture path, big picture file name, generate small picture name, generate small picture width, generate small picture height, wait for comparison (default to true) PUBLIC Class Small_Pic {String InputDir; // Input Diagram Path String Outputdir; // Output Diagram Path String InputFileName; // Input Diagram File Name String OutputFileName; // Output Diagram File Name INT OUTPUTWIDTH = 80; // Default Output Image Wide Int OutputHeight = 80; // Default output image high int Rate = 0; boolean proportion = true; // Whether to equal than zoom tag (default as an equal comparison) public small_pic () {// initialization variable inputdir = "" "; outdir =" "; InputFileName =" "; OutputFileName =" "; OutputWidth = 80; OutputHeight = 80; rate = 0;} public void setInputDir (String InputDir) {this.InputDir = InputDir;} public void setOutputDir (String OutputDir) {this. OutputDir = OutputDir;} public void setInputFileName (String InputFileName) {this.InputFileName = InputFileName;} public void setOutputFileName (String OutputFileName) {this.OutputFileName = OutputFileName;} public void setOutputWidth (int OutputWidth) {this.OutputWidth = OutputWidth;} public void setOutputHeight (int OutputHeight) {this.OutputHeight = OutputHeight;} public void setW_H (int width, int height) {this.OutputWidth = width; this.OutputHeight = height;} p ublic String s_pic () {BufferedImage image; String NewFileName; // create output file object File file = new File (OutputDir OutputFileName); FileOutputStream tempout = null; try {tempout = new FileOutputStream (file);} catch (Exception ex) {System.out.println (ex. tos = null; Toolkit TK = Toolkit.getDefaultToolkit (); applet app = new applet (); MediaTracker MT = New Mediatracker (app); try {img = Tk.getimage (Inputdir InputFileName); Mt.Addimage (IMG, 0); Mt.WaitforID (0);} catch (exception e) {E.PrintStackTrace ();} if (img.getwidth (null) == - 1) {System.out.println ("Can't Read, Retry!" "
");

Return "no";} elw {int new_w; int new_h; if (this.proportion == true) // determined if it is equal to zoom. {// is the image width and height double rate 1 = for equal than zoom calculation output. (Double) Img.Getwidth (NULL) / (Double) OutputWidth 0.1; Double Rate2 = ((Double) Img.getHeight (NULL)) / (Double) OutputHeight 0.1; Double Rate = Rate1> Rate2? Rate1: rate2 NEW_W = (INT) ((Double) img.getwidth (null) / rate); new_h = (int) ((Double) img.getHeight (null) / rate);} else {new_w = OutputWidth; // output image width new_h = OutputHeight; // output image height} BufferedImage buffImg = new BufferedImage (new_w, new_h, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.createGraphics (); g.setColor (Color.white); G.fillRect (0, 0, new_w, new_h); g.drawImage (IMG, 0, 0, New_W, New_H, NULL); g.dispose (); JPEGIMAGEENCODER Encoder = JPEGCODEC.CREATEJPEGENCODER (TEMPOUT); try {eNCoder. Encode (buffimg); Tempout.close ();} catch (ioException ex) {system.out.println (ex. tt ";}} returno" ok ";} public string s_pic (String Inputdir); String Outputdir, String INPUTFILENAME, STRING OUTPUTFILENAME) {// Input Diagram path this.inputdir = inputdir; // output diagram path this.outputdir = OutputDir; // input diagram file name this. InputFileName = InputFileName; // output filename FIG this.OutputFileName = OutputFileName; return s_pic ();} public String s_pic (String InputDir, String OutputDir, String InputFileName, String OutputFileName, int width, int height, boolean gp) {// Input diagram path this.inputdir = inputdir; // output diagram path this.outputdir = outputdir; // input diagram file name this.inputFileName = inputFileName; // output diagram file name this.outputFileName = OutputFileName; // Set picture length SETW_H (Width, Height); // Whether it is equal to zoom tag this.Proportion = gp; return s_pic ();} public static void main (String [] a) {// s_pic (large image path, generate small picture path , Big picture file name, generate small picture name, generate small picture width, generate small picture height) Small_PIC mypic = new small_pic (); system.out.println (mypic.s_pic)

E: // java // j2eedatum // Wang Liang JSP data // zoom example // personal ////////// java // jtatum // 酒 剑 仙 JSP data // 例 / // Personal //"1.jpg", "new1.jpg ", 80, 80 ,true);} Using JAVAMAILJAVA Chinese Station in JSP Do you want to create a mail sending a collection tool in JSP? The following will be introduced Create a mail sending a tip in JSP. In this article you can learn some of the JavaMail APIs and how to use it in JSP. This article also includes instances of Javamail in JSP. JavaMail is a JSP application Among the powerful API. Read this article Need a certain initial understanding of JSP, JavaBeans and Javamail. Of course, knowledge about JavaMail can be obtained by reading this article. If you don't know about the above three items But the server you use supports JSP and JavaMail, you can use them only by copy / paste. What is JavaMail JavaMail is the SUN released to process the Email's API. It can easily perform some common mail transfer. Although JavaMail is one of Sun's API, it has not yet been added to the standard Java Development Kit, which means you need to download the javamail file before use. In addition, you still It is necessary to have Sun's JavaBeans Activation Framework (JAF). JavaBeans Activation Framework is very complicated. It is simple to say that JavaMail's run must depend on its support. Use the path to specify these files in Windows 2000, in other It is also similar to the operating system. This guide is the most difficult part of this guide. This guide includes three parts: HTML form, combination of JavaMail, Javamail and JSP. Part 1: HTML form The first part of the HTML form provides An example of the most basic HTML-based Email sending charger. The second part tells the working principle of JavaMail. Part III describes javamail joining JSP, creating a basic Email send charger. Division component JSP is the most important Features can divide the entire web page into some small components. The components used here include: ● One HTML table used to send Email's information to JSP; ● A JSP page To process and send letters. The first step is to create an HTML table to send information to the JSP page.

You can copy the following HTML code to your computer: use to send email html source code

to:
From:
< Input name = "from" size = "25">
Subject:
< / TD>

Message: