JSP learning experience
Xu Chunjin
Application and development
Below is some experience when I study JSP, I would like to give up for everyone to share.
First, JSP works
When a JSP file is first requested, the JSP engine converts the JSP file into a servlet. And this engine itself is also a servlet, in JSWDK or WebLogic, it is JSPServlet. The JSP engine first converts the JSP file into a Java source file. If the JSP file is found when the JSP file is discovered, the conversion process will be interrupted, and an error message is output to the server and the client; if the conversion is successful, the JSP engine uses Javac Compile the Java source file into the corresponding Class file. Then create an instance of the servlet, which is executed, and the jspinit () method is only executed once in the life cycle of the servlet. Then the JspService () method is called to process the client's request. For each request, the JSP engine creates a new thread to process the request. If there are multiple clients to request the JSP file at the same time, the JSP engine creates multiple threads. Each client requests a thread. Performing a multi-threaded manner can greatly reduce resource requirements for the system, improve the system's concurrency and response time. But you should pay attention to multi-thread programming limitations, because the servlet is always in memory, so the response is very fast. If the .jsp file is modified, the server will decide whether to recompile the file according to the settings. If you need to recompile, you need to replace the result in the memory, and continue the above processing. Although the JSP efficiency is high, there is a slight delay in the first call. Also, if at any time, if the system is insufficient, the JSP engine will remove the servlet from the memory in a certain uncertain manner. When this occurs, the jspdestroy () method is first called, and the servlet instance is marked to join the "garbage collection" process. The jspinit () and jspdestory () format are as follows: Some initialization works in JSPinit (), such as establishing a connection with the database, or establishing a network connection, taking some parameters from the configuration file, release the corresponding one in jspdestory () Resource.
<%!
Public void jspinit ()
{
System.out.println ("jspinit");
}
%>
<%!
Public void jspdestory ()
{
System.out.println ("JSPDestory");
}
%>
Second, the output buffer of the server
By default: The server is output to the client's content, not directly written to the client, but first writes to an output buffer. Only in the case of the following three, the content of the buffer is output to On the client:
1. The JSP page has completed the output of information
2. Output buffer is full
3. jSP calls out.flush () or response.flushbuffer ()
The size of the output buffer can be used: <% @ page buffer = "none" | "NKB"%> or response.setbuffersize () settings, as follows:
1. Set the size of the output buffer to 1kB. <% @ page buffer = "1kb"%> or response.setbuffersize (1);
2. Set the size of the output buffer to 0, that is, it is not buffered. <% @ page buffer = "none"%> or response.setBuffersize (0);
With Response.getBuffersize () or OUT.GetBuffersize (), the size of the output buffer is byte.
Use response.iscommitted () to check if the server has output to the client. If the return value is True, the data has been output to the client, and it is not yet.
Third, the server output redirection
There are three ways to do the output redirection:
(1) Response.setRedect ("URL")
This method is to redirect the browser to the browser to redirect the web page by modifying the HTTP protocol's HEADER section.
Response.sendredirect ("http: // localhost: 7001 / index.html);
(2) The following method can also change the HTTP header attribute, which is the same as (1).
<%
Response.setstatus (httpservletResponse.sc_moved_persponse.sc_moved_persmanently);
String newlocn = "/ index.html";
Response.setHeader ("Location", Newlocn;
%>
(3) Use
This method is to use the server side to output the data to the buffer. Before sending the contents of the buffer to the client, the original does not send, change the content of the page, if there is
The following example (1) will output the contents of index.html, (2) the contents of index.html not output, but the output out.println ( "@@@@@@@@@@@@@@ @@@ ");
The contents, and the server will throw: java.lang.illegalStateException: Response Already Committed exception, but the client does not have any error output.
(1)
<% @ Page Buffer = "1KB"%>
<%
LONG i = 0;
For (i = 0; i <10; i )
{
Out.println ("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@00
}
%>
(2)
<% @ Page Buffer = "1KB"%>
<%
LONG i = 0;
For (i = 0; i <600; i )
{
Out.println ("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@00
}
%>
Description:
1. Method (1), (2) can use variables to indicate the redirected address; the method (3) cannot use the variable to represent the redirected address.
String add = "./ index.html";
Unable to redirect to index.html
String add = http: // localhost: 7001 / index.html
Response.sendRedirect (add);
You can redirect to http: // localhost: 7001 / index.html.
2. Using the method (1), (2) REQUEST (by request.setttribute () is used to save the value in the Request), the method (3) can be adopted in the new page. In summary, we should use (1), (2) The redirection is better.
Fourth, the correct application class in JSP
You should use the class as a Java Bean, do not use it directly in <%>> The following code (1) will turn to code after the JSP engine is transformed (2):
It can be seen from it. If a class is used as a JSP as a Java bean, the JSP saves it to the corresponding internal object based on its scope.
If the scope is REQUEST, save it into the Request object. And only in the first call (the value of the object is null), instantiates.
If an object of such an object is created directly in <%>>, each time you call JSP, you will re-create the object, which will affect performance.
Code (1)
jsp: usebean>
<%
Test.Print ("this is use java bean";
TestDemo TD = New TestDemo ();
TD.Print ("this is use new");
%>
Code (2)
Demo.com.testdemo test = (demo.com.testdemo) Request.GetaTRibute ("test");
IF (test == null)
{
Try
{
Test = (demo.com.testdemo) java.beans.beans.instantiate (GetClass (). getClassLoader (), "demo.com.testdemo");
}
Catch (Exception _beanexception)
{
Throw new weblogic.utils.nestedRuntimeException ("cannot instantiate 'demo.com.testdemo'", _ beanexception;
}
Request.setttribute ("Test", Test);
OUT.PRINT ("/ r / n");
}
Out.print ("/ r / n / r / n / r / n");
Test.Print ("this is use java bean";
TestDemo TD = New TestDemo ();
TD.Print ("this is use new");
Five, JSP debugging
JSP debugging is more troublesome, especially when Bean is in a session, it is more difficult. Ghey from a few pages to the inside. It is usually to check the problem with out.println () or system.out.print () to check the problem. If it is developed with JBuilder, it can debug JSP directly. But more important is the cause and solution to the error. Some JSP programming common errors are analyzed.
(1) .java.lang.NullPointered Exception
It is generally caused for a variable of a NULL value. If the following operation, Java.Lang.NullPointerException is thrown
String a = null;
A.SUBSTRING (0, 1);
To avoid this exception, it is best to check if it is NULL value before the variable operation is performed. Such as:
<%
String ss = session.getattribute ("Name")
IF Isnull (SS)
{
}
Else
{
}
%>
(2) .jsp is written in Java, so it is sensitive, and people who have used other programming languages are the most likely to make this mistake. In addition, the address of the JSP entered in the address bar of the browser is also
It is case-sensitive. Such as http: // localhost: 7001 / demo / t.jsp and http: // localhost: 7001 / demo / t.jsp is different.
(3). Judging the string in JSP Use the CompareTo method, do not use ==, because String variables in Java are not a simple variable but a class instance, different methods will get different results, as shown below:
1.
String str1 = "abcd";
String str2 = "abcd"; (or string str2 = "ab" "cd";)
IF (str1 == STR2)
Out.print ("yes");
Else
OUT.PRINT ("NO");
The result is "yes".
2.
String STR1, STR2, STR3;
Str1 = "abcd";
STR2 = "ab";
STR3 = STR2 "CD";
IF (str1 == STR3)
Out.print ("yes");
Else
OUT.PRINT ("NO");
The result is "NO".
3.
String str1 = new string ("abcd");
String str2 = new string ("abcd");
IF (str1 == STR2)
Out.print ("yes");
Else
OUT.PRINT ("NO");
The result is "NO".
4.
String str1 = new string ("abcd");
String str2 = new string ("abcd");
IF (str1.compareto (str2) == 0)
Out.print ("yes");
Else
OUT.PRINT ("NO");
The result is "yes".
(4) Preventing the output from the JSP or Servlet is saved by the browser in the buffer:
The browser will save the browsed webpage in the buffer by default. When debugging, do not want this. Add the following script to the program,
Preventing the output from the JSP or Servlet is saved in the buffer by the browser
<%
Response.setHeader ("Cache-Control", "NO-Store"); // http 1.1
Response.setHeader ("Pragma", "NO-Cache"); // http 1.0
Response.setdateHeader ("Expires", 0); // prevents Caching At the Proxy Server
%>
In IE, you can check the updated versions of the page / tool / Internet option / regular / set / setup / setup page, set to each access.
Sixth, cookie
HTTP cookie is essentially a normal HTTP header that is transmitted between the client and saves or saved on the customer's hard drive. If saved, each file size does not exceed 4K text files. Multiple cookies can be saved to the same In a file. If you look from a programming point, cookie in JSP is a class provided by Java. The common method is as follows, because the client may not accept cookies, so it is recommended to use it, change the session. Public Class Cookie, PUBLIC COLOKIE
{
Public string getDomain () // Returns the valid domain of this cookie
Public int getMaxage () // Returns the validity period of this cookie, unit is second
Public string getName () // Returns the name of the cookie
Public string getpath () // Returns the valid path of this cookie
Public Boolean getsecure () // Returns the security settings of this cookie
Public string getValue () // Returns the value of this cookie
Public void setdomain (java.lang.string pattern) // Setting the valid domain for this cookie
Public void setMaxage (int expiry) // Sets the validity period of the cookie, unit is second
Public void setpath (java.lang.string URI) // Sets the valid path for this cookie
Public void setSecure (Boolean Flag) // Setting the cookie security settings
Public void setvalue (java.lang.string newvalue) // Set the value of this cookie
}
A cookie contains the following five parts:
1. Name / Value pair, set the name of the cookie and the value it saved
2. Cookie is usually related to the server. If the domain is set to java.sun.com, then the cookie is related to this domain, only the URL works, when browsing the URL, the browser will send the cookie content Give the server, cookies are sent as part of the HTTP header, if there is no setting domain, then cookies are only related to the server created the cookie.
3. The path is used to specify the path where the file can be used on the server, which only works on the application under this path under this URL. "/" Indicates that all directories on the server can use the cookie.
4. Cookies have a validity period, the validity default value is -1, which means that the cookie is not saved when the browser exits, the cookie expands.
5. Security Option True / false, if set to TRUE, use the HTTPS protocol when the server is transmitted between the Cookie between the server.
How to check if a client supports cookie:
Write a cookie to the client with the following method and confirm success
Try
{
Cookie C = New Cookie ("MyCookie", "Cookie Test");
Response.addcookie (c);
}
Catch (Exception E)
{
System.out.println (e);
}
Then in a new JSP file: take the following method to take the client's cookie to cookies,
If cookies.length == 0, explains that the client's browser does not support cookie
Try
{
Cookie [] cookies = Request.getCookies ();
IF (cookies.length == 0)
{
System.out.Println ("Not Support Cookie");
}
}
Catch (Exception E)
{
System.out.println (e);
}
Eight, the difference between JSP and Servlet