JSP learning experience

Source: Internet
Author: User

Author: Xu Chunjin

Below are some of my experiences in learning JSP:

I. Working Principles of JSP

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, the JSP Engine creates 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 latency 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 remove the servlet from the memory in an uncertain way. In this case, the jspDestroy () method is called first, and the servlet instance is marked as "Garbage Collection. The jspInit () and jspDestory () formats are as follows: You can perform initialization in jspInit (), such as establishing a connection to the database or establishing a network connection, take some parameters from the configuration file and release the corresponding resources 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:

  1. Set the size of the output buffer to 1 kb. Or response. setBufferSize (1 );
  2. 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 check whether 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:

  1. RESPONSE. SETREDERECT ("URL") This method modifies the http header to issue a redirection command to the browser so that the browser displays the content of the redirected webpage. response. sendRedirect ("http: // localhost: 7001/index.html ");
  2. 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 );
    %>
  3. The <JSP: FORWORD> method is used to output data to the buffer zone first on the server side. 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 ");
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:

      
  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) 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:

  1. NAME/VALUE pair, set the cookie name and its saved VALUE
  2. 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.
  3. 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.
  4. 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.
  5. 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 very powerful in writing business logic layers, however, it is inconvenient to write 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 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.