When a JSP file is first requested, the JSP engine converts the JSP file into a servlet. And the engine itself is a servlet, in JSWDK or WebLogic, it's jspservlet. The JSP engine first converts the JSP file into a Java source file, and if any syntax errors are found in the JSP file at the time of conversion, the conversion process is interrupted and the error message is exported to the server and the client; if the conversion succeeds, The JSP engine compiles the Java source file into the corresponding class file using Javac. Then create an instance of the servlet, the Jspinit () method of the servlet is executed, and the Jspinit () method is executed only once in the lifecycle of the servlet. The Jspservice () method is then called to process the client's request. For each request, the JSP engine creates a new thread to process the request. If more than one client requests the JSP file at the same time, the JSP engine creates multiple threads. Each client request corresponds to a thread. Multi-threaded implementation can greatly reduce the resource requirements of the system, improve the system's concurrent volume and response time. However, you should pay attention to the programming limitations of multithreading, 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 based on the settings, and if recompilation is required, replace the compiled result with the in-memory servlet and continue with the process. Although JSP is highly efficient, there are some minor delays in the first invocation due to the need for conversion and compilation. Also, if, at any time, the JSP engine removes the servlet from memory in some uncertain fashion due to insufficient system resources. When this occurs, the Jspdestroy () method is invoked first, and then the servlet instance is tagged to the garbage collection process. The Jspinit () and jspdestory () formats are as follows: You can perform some initialization work in Jspinit (), such as establishing a connection to a database, establishing a network connection, taking some parameters from a configuration file, and releasing the appropriate resources in Jspdestory ().
<%!
public void Jspinit ()
{
System.out.println ("Jspinit");
}
%>
<%!
public void Jspdestory ()
{
System.out.println ("Jspdestory");
}
%>
Second, the output buffer of the service end
By default: The content of the server to be output to the client, not directly to the client, but first written to an output buffer. The contents of the buffer are exported to the client only in the following three cases:
The JSP page has completed the output of the information
The output buffer is full
Out.flush () or Response.flushbuffer () is called in the JSP.
The size of the output buffer can be set by: or Response.setbuffersize (), as follows:
Sets the size of the output buffer to 1KB. or response.setbuffersize (1);
Sets the output buffer to a size of 0, which is not buffered. or response.setbuffersize (0);
The size, in bytes, of the desired output buffer with response.getbuffersize () or out.getbuffersize (). Use response.iscommitted () to check to see if the server has output data to the client. If the return value is true, the data is exported to the client, or false.
Third, service-side output redirection
There are 3 ways to do output redirection:
RESPONSE. Setrederect ("URL") This method gives the browser a redirection instruction by modifying the header portion of the HTTP protocol, so that the browser displays the contents of the redirected Web page. Response.sendredirect ("http://localhost:7001/index.html");
The following method can also change the HTTP header property, which is the same principle as 1.
<%
Response.setstatus (httpservletresponse.sc_moved_permanently);
String newlocn= "/index.html";
Response.setheader ("Location", NEWLOCN);
% >
Using the <JSP:FORWORD> method is to use the server-side first to output data to the buffer mechanism, before sending the contents of the buffer to the client, the original does not send, instead of sending the content of the page, if there is a lot of output before <JSP:FORWORD>, Special attention should be paid to the fact that the previous output has filled the buffer and will automatically output to the client, so the statement will not work. As the following example (1) will output index.html content, 2 will not output index.html content, but output out.println (""); And is thrown on the server side: 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 ("");
}
%>
<jsp:forward page= "./index.html"/>
(2)
<% @page buffer= "1KB"%>
<%
Long i=0;
for (i=0;i<600;i++)
{
Out.println ("");
}
%>
Description
1. Method (1), (2) A variable can be used to represent the redirected address, and method (3) cannot use a variable to represent the redirected address.
String add= "./index.html";
<jsp:forward page= Add/>
Unable to redirect to Index.html
String add=http://localhost:7001/index.html
Response.sendredirect (add);
Can be redirected to the http://localhost:7001/index.html.
2. Using the method (1), (2) the variables in the request (saved to the request by Request.setattribute ()) cannot be used in the new page, using the method (3). In conclusion, we should adopt (1) and (2) redirect better.
Four, the correct application of the JSP class:
You should use the class as a Java bean instead of using it directly in <%%>. The following code (1) translates into code (2) after the JSP engine:
You can see from this that if you use a class in JSP as a Java BEAN, the JSP will save it to the corresponding internal object according to its scope.
If the scope is request, save it to the request object. And it is instantiated only the first time it is called (the object's value is null). If you create an object of the class directly in <%%>, you re-create the object each time you call the JSP, which can affect performance.
Testdemo td= new Testdemo ();
Td.print ("This is use new");
%>
Code (2)
Demo.com.testdemo test = (Demo.com.testdemo) request.getattribute ("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.setattribute ("Test", test);
Out.print ("");
}
Out.print ("");
Test.print ("This are use Java bean");
Testdemo td= new Testdemo ();
Td.print ("This is use new");
Five, the JSP debugging
JSP debugging is more cumbersome, especially when the bean is in a session, more difficult. We have to start with several pages and go inside. Usually use OUT.PRINTLN () or System.out.print () to make a lot of information to check the problem. If you are using JBuilder to do development, it can directly debug JSP. But more importantly, know the cause of the error and the solution. Some common errors in JSP programming are analyzed below.
(1). Java.lang.NullPointerException anomaly
is typically caused by an operation on a variable that is a null value. If the following actions are thrown
Java.lang.NullPointerException
String a = null;
A.substring (0,1);
To avoid this exception, it is best to check to see if it is a null value before the variable is manipulated.
<% String ss=session.getattribute ("NAME")
If IsNull (ss)
{
}
Else
{
}
%>
(2). JSP is written in Java, so it is case sensitive, and people who have used other programming languages are most likely to make this mistake. Additionally, the address of the access JSP entered in the address bar of the browser is case-sensitive. As http://localhost:7001/demo/t.jsp and http://localhost:7001/Demo/t.jsp are different.
(3). In the JSP to judge the string to use the CompareTo method, do not use = = because the string variable in Java is not a simple variable but a class instance, different methods will get different results, as follows:
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".
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".
String Str1=new string ("ABCD");
String Str2=new string ("ABCD");
if (STR1==STR2)
Out.print ("yes");
Else
Out.print ("no");
The result is "no".
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) Prevent the output in the JSP or servlet from being saved in the buffer by the browser:
Browsers store browsed pages in a buffer by default, which is generally not desirable when debugging. The following script is added to the program to prevent the output in the JSP or servlet from being 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 can also be achieved by setting:/internet/Tool/set/check the newer version of the saved page, set to be checked every time you visit the page.
VI. Cookies
The HTTP cookie is essentially a normal HTTP header that is sent between the server and the client, and can be saved or not stored on the client's hard disk. If saved, a text file of no more than 4K per file size. Multiple cookies can be saved to the same file. If, from a programmatic standpoint, cookies are a class provided by Java in a JSP. The commonly used method is represented as follows, because the client may not accept cookies, so it is recommended that you do not use it instead of session and other ways.
public class Cookie
{
Public String GetDomain ()//Returns a valid field for the cookie
public int getmaxage ()//returns the validity of the cookie in seconds
Public String GetName ()//returns the name of the cookie
Public String GetPath ()//returns a valid path to the cookie
public boolean getsecure ()//Returns the security settings for this cookie
Public String GetValue ()//Returns the value of the cookie
public void SetDomain (java.lang.String pattern)//Set valid domain for this cookie
public void Setmaxage (int expiry)//Set the validity period of the cookie in seconds
public void SetPath (java.lang.String uri)//Set valid path for this cookie
public void SetSecure (Boolean flag)//Set security settings for this cookie
public void SetValue (java.lang.String newvalue)//Set the value of the cookie
}
A cookie contains the following five parts:
Name/value, set the name of the cookie and the value it holds
Cookies are usually related to the server, if the domain is set to JAVA.SUN.COM, then the cookie is related to the domain, only for the Web site, when browsing the URL, the browser will send the contents of the cookie to the service side, cookies as HTTP Part of the header is sent, and if the domain is not set, then the cookie is only relevant to the server that created the cookie.
The path is used to specify the path to the file on the server where the cookie can be used, and it only works on the application under that path under that URL. /"indicates that the cookie is available to all directories on the server.
Cookies have a validity period, the default value of 1, which means that the cookie is not saved, and when the browser exits, the cookie is immediately invalidated.
Security option True/false, if set to True, the HTTPS protocol is used when the content of the cookie is transferred between the server and the client.
How to check whether a client supports cookies:
Write a cookie to the client using the following method and confirm the 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: Use the following method to take the client's cookies into the cookie, if Cookies.length ==0, the client's browser does not support cookies
Try
{
cookie[] cookies = request.getcookies ();
if (Cookies.length ==0)
{
SYSTEM.OUT.PRINTLN ("not support Cookie");
}
}
catch (Exception e)
{
System.out.println (e);
}
Seven, JSP and servlet differences:
Sun first developed a servlet, its function is relatively strong, the system design is also very advanced, just, it output HTML statements or using the old CGI way, is a sentence output, so, write and modify HTML is very inconvenient. Later, Sun introduced a JSP similar to ASP, nested Java code into HTML statements, which greatly simplifies and facilitates the design and modification of Web pages. asp,php,jsp are nested script languages. A distributed system should be divided into three layers: the presentation layer, the business logic layer, the data access layer, in the Java EE architecture, the servlet is used to write the business logic layer is very powerful, but for the write presentation layer is very inconvenient. JSP is mainly designed to facilitate the writing of the presentation layer. The ENTITY bean implements the data access layer, and the session Bean implements the business logic layer. If it is a simple application system, you can use the structure of Jsp+beans design, JSP should only be stored with the presentation layer of things, that is, only the output of the HTML page part. And all the data calculation, data analysis, database connection processing, all belong to the business logic layer, should be placed in the Java beans. Call Java BEANS through JSP to achieve the integration of two tiers. In fact, Microsoft's DNA technology, simply speaking, is asp+com/dcom technology. Exactly like Jsp+beans, all the presentation layers are completed by the ASP, and all business logic is done by com/dcom. Why do you use these component technologies? Because the simple asp/jsp language is very inefficient, if a large number of user clicks, the Pure script language will soon reach his upper limit, and component technology can greatly increase the upper limit of the function, speed up the execution speed. On the other hand, the pure script language will be the presentation layer and the business logic layer mixed together, resulting in inconvenient modification, and the code can not be reused, the use of component technology only the reorganization of the pieces can be. For complex applications, the entity bean should be used to implement the data access layer, the session bean implements the business logic layer, and the session Bean is invoked with a JSP, and the entity Bean is called by the session Bean. The JSP+EJB is used to build a complex distributed system. It has higher throughput, reliability and security than Jsp+bean. To sum up, for simple application, can adopt Jsp+baen, to the complex application system, should adopt jsp+ejb,servlet become insignificant. JSP can replace it completely.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.