JSP learning Summary

Source: Internet
Author: User
When a JSP file is requested for the first time, the JSP Engine converts the JSP file into a servlet. The 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 any syntax error is found in the JSP file during conversion, the conversion process is interrupted and an error message is output to the server and client; if the conversion is successful, the JSP engine uses javac to compile the Java source file into the corresponding class file. Create an instance of the servlet. The jspinit () method of the servlet is executed. The jspinit () method is executed only once in the servlet lifecycle. Then, the jspservice () method is called to process client requests.
For each request, JSP leads the consumer to create a new thread to process the request. If multiple clients request the JSP file at the same time, the JSP Engine creates multiple threads. Each client request corresponds to a thread. Multi-threaded execution can greatly reduce system resource requirements and improve system concurrency and response time. but pay attention to the multi-thread programming restrictions. Because the servlet is always in the memory, the response is very fast. If the. jsp file is modified, the server will decide whether to recompile the file based on the settings. If you need to re-compile the file, replace the compilation result with the servlet in the memory and continue the above process. Although JSP is very efficient, there is a slight delay in the first call due to the need for conversion and compilation. In addition, if the system resources are insufficient at any time, the JSP Engine will definitely remove the servlet from the memory. In this case, the jspdestroy () method is called first, and the servlet instance is marked as added to the "Garbage Collection" processing.
The jspinit () and jspdestory () formats are as follows:
You can perform initialization in jspinit (), such as establishing a connection to the database, establishing a network connection, taking some parameters from the configuration file, etc. In jspdestory ().

<%!
Public void jspinit ()
{
System. Out. println ("jspinit ");
}

%>

<%!
Public void jspdestory ()
{
System. Out. println ("jspdestory ");
}
%>

Ii. Server output buffer

By default, the content that the server will output to the client is written to an output buffer instead of the client. the buffer content is output to the client only in the following three cases:

1. Output of the JSP webpage complete information
2. The output buffer is full.
3. jsp calls out. Flush () or response. flushbuffer ()

The size of the output buffer can be set with: or response. setbuffersize (), as follows:
Set the size of the output buffer to 1 kb. Or response. setbuffersize (1 );
Set the size of the output buffer to 0, that is, no buffer. Or response. setbuffersize (0 );

Use response. getbuffersize () or out. getbuffersize () indicates the size of the output buffer, in bytes. use response. iscommitted () can be checked to see if the server has output data to the client. if the return value is true, the data has been output to the client. If the return value is false, no data is available.

Iii. Server output redirection

There are three methods to achieve output redirection:

Response. sendredirect ("url ")
This method modifies the HTTP header to issue redirection instructions to the browser so that the browser displays the content of the redirected webpage. response. sendredirect ("http: // localhost: 7001/index.html ");
The following method can also change the HTTP header attribute. Its principle is the same as that of 1.
<%
Response. setstatus (httpservletresponse. SC _moved_permanently );
String newlocn = "/index.html ";
Response. setheader ("location", newlocn );
%>

The <JSP: forword> method is used to output data to the buffer zone on the server. The original method is not sent before the buffer content is sent to the client, if there are a lot of output before <JSP: forword> and the previous output has filled the buffer and will be automatically output to the client, the statement will not work, pay special attention to this. for example, in the following example, (1) indexindex.html content, 2 will not output index.html content, but output out. content in println ("@"); and it will be thrown at the server: Java. lang. illegalstateexception: response already committed exception, but the client has no 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 ("@@@@@@@@@@@@@@@@@");
}
%>

Note:
1. Methods (1), (2) can use variables to represent the redirected address, and methods (3) cannot use variables to represent the redirected address.
String add = "./index.html ";
<JSP: Forward page = Add/>
Go to index.html without authorization

String add = http: // localhost: 7001/index.html
Response. sendredirect (ADD );
You can redirect to http: // localhost: 7001/index.html.

2. use the method (1), (2) variables in the request (through the request. setattribute () values saved to the request) cannot be used in the new page. Method (3) can be used. in summary, we should adopt (1) and (2) redirection better.

4. Correct Application classes in JSP:

Classes should be used as Java Beans. Do not directly use the following code in <%>. (1) converted into code after JSP Engine conversion (2 ):
It can be seen that if a class is used as a Java Bean in JSP, JSP will save it to the corresponding internal object according to its scope.
If the range is request, save it to the request object. it is instantiated only when it is called for the first time (the object value is null. if you directly create an object of this class in <%>, you must re-create the object each time you call JSP, which will affect the performance.

Code (1)
<JSP: usebean id = "test" Scope = "request" class = "demo.com. testdemo">
</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. 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 ("/R/N ");
}
Out. Print ("/R/n/R/N ");
Test. Print ("this is use Java Bean ");

Testdemo TD = new testdemo ();
TD. Print ("this is use new ");

V. jsp debugging

Debugging of JSP is troublesome, especially when bean exists in a session. You have to start from several pages. Generally, out. println () or system. Out. Print () is used to query the problem. If JBuilder is used for development, it can directly debug JSP. But more importantly, it knows the cause of the error and the solution. The following describes common JSP programming errors.

(1). java. Lang. nullpointerexception exception
This is generally caused by an operation on a null variable. The following operation will throw
. Java. Lang. nullpointerexception
String A = NULL;
A. substring (0, 1 );

To avoid this exception, you are advised to check whether it is a null value before performing the variable operation. For example:
<% String Ss = session. getattribute ("name ")
If isnull (SS)
{

}
Else
{

}
%>

(2) JSP is written in Java, so it is case sensitive. People who have used other programming languages are most likely to make this mistake. In addition, the JSP access address entered in the address bar of the browser is case sensitive. for example, http: // localhost: 7001/demo/t. JSP and http: // localhost: 7001/demo/t. JSP is different.

(3 ). in JSP, The compareto method is used to judge strings. Do not use =, because in Java, the string variable 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 JSP or servlet output from being saved in the buffer by the browser:
By default, the browser saves the browsed web pages in the buffer zone. This is generally not desired during debugging. add the following script to the program to prevent the JSP or servlet output from being saved by the browser in the buffer.
<%
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 also set the new version of the stored page to check each access to the page by setting/tools/Internet Options/General/settings.

Vi. Cookie

HTTP cookies are essentially common HTTP headers transmitted between the server and the client, which can be stored or not stored on the customer's hard disk. if the file is saved, the size of each file cannot exceed 4 kb. multiple cookies can be saved to the same file. from the programming point of view, in JSP, cookie is a class provided by Java. the common method is as follows. Because the client may not accept cookies, we recommend that you use session or other methods instead.

Public class cookie
{
Public String getdomain () // returns the valid domain of the cookie
Public int getmaxage () // returns the Cookie's validity period, in seconds
Public String getname () // return the cookie name
Public String getpath () // returns the valid path of the cookie.
Public Boolean getsecure () // returns the Cookie's Security Settings
Public String getvalue () // return the cookie value
Public void setdomain (Java. Lang. String Pattern) // sets the valid domain of the cookie.
Public void setmaxage (INT expiry) // sets the cookie validity period, in seconds
Public void setpath (Java. Lang. String URI) // you can specify a valid path for this cookie.
Public void setsecure (Boolean flag) // sets the cookie Security Settings
Public void setvalue (Java. Lang. String newvalue) // set the cookie value
}
A cookie contains the following five parts:

Name/value pair, set the cookie name and its saved value
Cookie is usually related to the server. If you set the domain to Java. sun. com, then the cookie is related to this domain and only takes effect for this URL. When you browse this URL, the browser will send the content of this cookie to the server, cookie is sent as part of the HTTP header. If no domain is set, the cookie is only related to the server on which the cookie is created.
The path is used to specify the path of the file on which the cookie can be used on the server. It only takes effect for the application under the path under the URL. "/" indicates that the cookie can be used in all directories on the server.
Each Cookie has a validity period. The default validity period is-1, indicating that the cookie is not saved. When the browser exits, the cookie will immediately become invalid.
Security Options: True/false. If this parameter is set to true, https is used when the content of the cookie is transmitted 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 retrieve the cookie from the client to cookies. If the cookie. Length = 0, the browser on the client does not support the cookie.
Try
{
Cookie [] cookies = request. getcookies ();
If (cookies. Length = 0)
{
System. Out. println ("not support cookie ");
}
}
Catch (exception E)
{
System. Out. println (E );
}

VII. Differences between JSP and Servlet:

Sun first developed the servlet, which has powerful functions and advanced system design. However, it still uses the old CGI method to output HTML statements. Therefore, it is inconvenient to write and modify HTML. Later, Sun introduced JSP similar to ASP, nesting Java code into HTML statements, which greatly simplifies and facilitates the design and modification of web pages. ASP, PHP, and JSP are nested script languages. A Distributed System should be divided into three layers: presentation layer, business logic layer, and data access layer,
In the J2EE architecture, servlet is powerful for writing business logic layers, but it is inconvenient for writing the presentation layer. JSP is designed to facilitate the presentation layer. Entity Bean implements the data access layer, and Session Bean implements the business logic layer. For a simple application system, the structure of JSP + beans can be used for design. jsp should only store the content related to the presentation layer, that is, only the part of the HTML webpage is output. All data computing, data analysis, and database connection processing all belong to the business logic layer and should be placed in Java Beans. Java Beans are called through JSP to achieve integration of two layers. In fact, Microsoft's DNA technology, simply put, is ASP + COM/DCOM technology. Similar to JSP + beans, all presentation layers are completed by ASP, and all business logic is completed by COM/DCOM. Why are these component technologies used? The simple ASP/JSP language is very inefficient for execution. If a large number of users click, the pure script language will soon reach the upper limit of its functions, the component technology can greatly increase the function ceiling and speed up the execution. On the other hand, the pure script language merges the presentation layer and the business logic layer, making modifications inconvenient and the Code cannot be reused. By using the component technology, you only need to modify the component. For complex applications, Entity Bean should be used to implement the data access layer. Session Bean is used to implement the business logic layer, JSP is used to call session bean, and Session Bean calls Entity Bean. JSP + EJB is used to build a complex distributed system. It has higher throughput, reliability, and security than JSP + bean. To sum up, JSP + baen can be used for simple and single applications. JSP + EJB should be used for complex application systems, and Servlet becomes insignificant. JSP can replace it completely.

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.