For simple applications, JSP+BAEN can be used, and for complex application systems, JSP+EJB should be used, SERVLET becomes insignificant. It is completely replaceable with JSP.
1. How JSP works
When a JSP file is requested for the first time, the JSP engine converts the JSP file into a servlet. 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 there is any syntax error in the jsp file during conversion, the conversion process will be interrupted and error information will be 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.
Then create an instance of the SERVLET, and the jspInit() method of the SERVLET is executed, and the jspInit() method is executed only once in the life cycle of the servlet. Then the jspService() method is called to handle the client's request. 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.
Execution in a multi-threaded way can greatly reduce the resource requirements for the system and increase the concurrency and response time of the system. However, attention should be paid to the programming limitations of multi-threaded. Since the servlet always resides in memory, 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 recompile is required, the compilation result will replace the servlet in memory and continue the above processing process. While JSP is very efficient, there is some slight delay on the first call due to the need for conversion and compilation.
Furthermore, if at any time if due to insufficient system resources, the JSP engine will remove the servlet from memory in some uncertain way. When this happens, the jspDestroy() method is called first, and then the servlet instance is marked for "garbage collection" processing. The formats of jspInit() and jspDestory() are as follows: some initialization work can be performed in jspInit(), such as establishing a connection to the database, establishing a network connection, taking some parameters from the configuration file, etc., and releasing the corresponding resources in jspDestory().
<%! public void jspInit() { ("jspinit"); } %>; <%! public void jspDestory() { ("jspDestory"); } %>;
2. The output buffer of the server side
By default: the server needs to output the content to the client, and does not write it directly to the client, but first write it to an output buffer. Only in the following three cases can the content of the buffer be output to the client:
The JSP web page has completed the output of information
The output buffer is full
() or () is called in JSP
The size of the output buffer can be set using: or (), as follows:
Set the size of the output buffer to 1KB. or
(1);
Set the size of the output buffer to 0, that is, it does not buffer. or
(0);
Use () or () to select the size of the output buffer, in bytes. Use () to check whether the server has outputted the data to the client. If the return value is TRUE, the data has been outputted to the client, and if it is FALSE, there is no.
3. Server output redirection
There are three ways to achieve output redirection:
("URL") This method changes the HEADER part of the HTTP protocol and issues redirection commands to the browser, so that the browser displays the content of the redirected web page.
("http://localhost:7001/");
The following method can also change the HTTP HEADER attribute, and its principle is the same as 1.
<% (HttpServletResponse.SC_MOVED_PERMANENTLY); String newLocn="/"; ("Location",newLocn); % >;
Use <JSP:FORWARD>;
This method uses the mechanism of the server to output data to the buffer first. Before sending the content of the buffer to the client, the original one is not sent, but instead send the content of the page. If there is a lot of output before <JSP:FORWORD>;, the previous output has made the buffer full and will be automatically output to the client, then this statement will not work. Pay special attention to this point. For example (1) below, the content will be output, and (2) will not output the content, but the content in ("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); and the ::Response already committed exception will be thrown on the server, but the client does not have any error output.
(1)
<%@page buffer="1kb"%>; <% long i=0; for(i=0;i<10;i++) { ("@@@@@@@@@@@@@@@@@"); } %>; <jsp:forward page="./" />;
(2)
<%@page buffer="1kb"%>; <% long i=0; for(i=0;i<600;i++) { ("@@@@@@@@@@@@@@@@@"); } %>;
illustrate:
1. Methods (1), (2) can use variables to represent the redirected address; method (3) cannot use variables to represent the redirected address.
String add="./"; <jsp:forward page= add />;
Can't redirect to the middle
String add=http://localhost:7001/ (add);
You can redirect to http://localhost:7001/.
2. Using method (1), (2) variables in request (values saved to request through ()) cannot be used in new pages, and using method (3) can. In summary, we should use (1) and (2) redirection is better.
4. Correct application classes in JSP:
Classes should be used as JAVA BEAN, and do not use them directly in <% %>;. The following code (1) will become code after being converted by the JSP engine (2):
It can be seen from this that if a class is used in JSP as JAVA BEAN, JSP will save it to the corresponding internal object according to its scope of action.
If the scope of action is request, save it to the request object. It will be instantiated only when it is called the first time (the value of the object is null). If an object of this class is created directly in <% %>;, the object must be recreated every time JSP is called, which will affect performance.
Code (1)
<jsp:useBean scope="request" class="">; </jsp:useBean>; <% ("this is use java bean"); testdemo td= new testdemo(); ("this is use new"); %>;
Code (2)
test = ()("test"); if (test == null) { try { test = () (getClass().getClassLoader(), ""); } catch (Exception _beanException) { throw new ("cannot instantiate '' ",_beanException); } ("test", test); ("\r\n"); } ("\r\n\r\n\r\n"); ("this is use java bean"); testdemo td= new testdemo(); ("this is use new");
V. JSP debugging
Debugging JSP is more troublesome, especially when beans exist in a session, which is even more difficult. You have to start from several pages and go inside. Usually, you use () or () to type a lot of information to check the problem. If you are using jbuilder for development, it can directly debug JSP. However, more importantly, you know the cause and solution of the error. The following is analyzing some common JSP programming errors.
(1).Exception
Generally, it is caused by operating a variable with a NULL value. If the following operation is thrown
String a = null; (0,1);
To avoid this exception, it is best to check whether it is a NULL value before operating on the variable. For example:
<% String ss=("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. In addition, the address accessing JSP entered in the browser's address bar is also case sensitive. For example, http://localhost:7001/demo/ is different from http://localhost:7001/Demo/
(3). In jsp, you should use the compareTo method 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 shown below:
String str1="ABCD"; String str2="ABCD"; (or String str2="AB"+"CD"; ) if (str1==str2) ("yes"); else ("no"); turn out"yes"。 String str1,str2,str3; str1="ABCD"; str2="AB"; str3=str2+"CD"; if (str1==str3) ("yes"); else ("no"); turn out"no"。 String str1=new String("ABCD"); String str2=new String("ABCD"); if (str1==str2) ("yes"); else ("no"); turn out"no"。 String str1=new String("ABCD"); String str2=new String("ABCD"); if ((str2)==0) ("yes"); else ("no"); turn out"yes"。
(4) Prevent the output in JSP or SERVLET from being saved in the buffer by the browser:
By default, the browser will save the browsed web pages in a buffer. This is generally not intended during debugging. Adding the following scripts to the program can prevent the output in JSP or SERVLET from being saved in the buffer by the browser.
<% ("Cache-Control","no-store"); //HTTP 1.1 ("Pragma","no-cache"); //HTTP 1.0 ("Expires", 0); //prevents caching at the proxy server %>;
In IE, it can also be implemented through settings: set the newer version of the stored page of /Tools/INTERNET options/General/Settings to check each time the page is accessed.
6. COOKIE
HTTP COOKIE is essentially a normal HTTP header transmitted between the server and the client. It can be saved or not saved on the client's hard disk. If saved, each file size does not exceed 4K. Multiple COOKIE can be saved to the same file. From a programming point of view, COOKIE is a class provided by JAVA. Common methods are indicated below. Because the client may not accept COOKIE, it is recommended not to use it and use SESSION and other methods.
public class cookie { public String getDomain() //Return the valid domain of this COOKIEpublic int getMaxAge() //Return the validity period of this COOKIE, in secondspublic String getName() //Return the name of the COOKIEpublic String getPath() //Return the valid path of this COOKIEpublic boolean getSecure() //Return to the security settings of this COOKIEpublic String getValue() //Return the value of this COOKIEpublic void setDomain( pattern) //Set the valid domain of this COOKIEpublic void setMaxAge(int expiry) //Set the validity period of this COOKIE, in secondspublic void setPath( uri) //Set the valid path of this COOKIEpublic void setSecure(boolean flag) //Set the security settings of this COOKIEpublic void setValue( newValue) //Set the value of this COOKIE}
A COOKIE contains the following five parts:
NAME/VALUE pair, set the name of the COOKIE and the saved value
COOKIE is usually related to the server. If the domain is set to, then the COOKIE is related to this domain and only works for the URL. When browsing the URL, the browser will send the COOKIE content to the server. COOKIE is sent as part of the HTTP HEADER. If the domain is not set, then COOKIE is only related to the server that created the COOKIE.
The path is used to specify the path on the server where the file where the COOKIE can be used is located. It only works for applications under the path under the URL. "/" means that all directories on the server can use the COOKIE.
COOKIE has a valid period, and the default value of the valid period is -1, which means that the COOKIE is not saved. When the browser exits, the COOKIE will be invalid immediately.
The security option true/false. If set to true, the HTTPS protocol is used when transmitting the COOKIE content between the server and the client.
How to check whether a client supports COOKIE:
Use the following method to write a COOKIE to the client and confirm that it is successful
try { Cookie c = new Cookie("mycookie","COOKIE TEST"); (c); } catch(Exception e) { (e); }
Then in a new JSP file: use the following method to take the client's COOKIE into cookies. If ==0, it means that the client's browser does not support COOKIE
try { Cookie[] cookies = (); if( ==0) { ("not support cookie"); } } catch(Exception e) { (e); }
7. The difference between JSP and SERVLET:
SUN first developed SERVLET, which has relatively strong functions and advanced system design. However, it still uses the old CGI method to output HTML statements, which are output sentence by sentence, so it is very inconvenient to write and modify HTML. Later, SUN launched 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 all nested SCRIPT languages.
A distributed system should be divided into three layers: presentation layer, business logic layer, data access layer,
In J2EE architecture, SERVLET is very powerful for writing business logic layers, but it is inconvenient for writing presentation layers. JSP is mainly designed to facilitate writing presentation layers. ENTITY BEAN implements the data access layer, and SESSION BEAN implements the service logic layer. If it is a simple application system, it can be designed using the JSP+BEANS structure. JSP should only store things related to the presentation layer, that is, only the part of the output HTML web page is placed. All data calculation, data analysis, and database connection processing all belong to the business logic layer and should be placed in JAVA BEANS. Calling JAVA BEANS through JSP to achieve two-layer integration.
In fact, Microsoft's DNA technology, simply put, is ASP+COM/DCOM technology. It is exactly similar to JSP+BEANS, all presentation layers are completed by ASP and all business logic is completed by COM/DCOM. Why use these component technologies? Because a simple ASP/JSP language is very inefficient to execute, if a large number of user clicks occur, the pure SCRIPT language will soon reach its functional limit, and component technology can greatly increase the functional limit and speed up execution.
On the other hand, the pure SCRIPT language mixes the presentation layer and the business logic layer, which makes it inconvenient to modify and the code cannot be reused. Using component technology, just modify the components. For complex applications, ENTITY BEAN should be used to implement the data access layer, SESSION BEAN should be used to implement the business logic layer, JSP should be used to call SESSION BEAN, and ENTITY BEAN should be called by SESSION BEAN. That is, use JSP+EJB 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, and JSP+EJB should be used for complex application systems, and SERVLET will become insignificant. It is completely replaceable with JSP.
The learning experience about JSP compiled in this article hopes that it will be helpful to your study.