JSP learning experience summary (transfer)

zhaozj2021-02-16  59

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

The JSP page has completed the output of information

Output buffer is full

Out.flush () or response.flushbuffer () is called in JSP.

The size of the output buffer can be used: or response.setBuffersize (), as follows:

Set the size of the output buffer to 1KB. Or Response.setBuffersize (1);

Set the size of the output buffer to 0, that is, it is not buffered. Or response.setbuffersize (0);

With response.getBuffersize () or out.getBuffersize (), the size of the output buffer, unit is byte. Use response.iscommitted () to check if the data has been 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:

Response.SetRedect ("URL") This method is a redirected command to the browser to redirect the browser to the browser to redirect the browser to the browser. Response.sendredirect ("http: // localhost: 7001 / Index.html "); The following method can also change the HTTP header attribute, and its principles and 1 are the same.

<%

Response.setstatus (httpservletResponse.sc_moved_persponse.sc_moved_persmanently);

String newlocn = "/ index.html";

Response.setHeader ("Location", Newlocn;

%>

Using the 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 JSP: Forword> There are many outputs. The previous output has made the buffer, automatically output to the client, then this statement will not work, this should be paid to it. In the following example (1) Output Index .html content, the content index.html 2 does not output, but the output out.println ( "@@@@@@@@@@@@@@@@@"); the content, and the service The end will throw: java.lang.illegalStateException: Response alleady 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:

The class should be used as a Java bean, do not use it directly in <%>> The following code (1) will change to code after transformation of JSP engine (2): From it can see if a class is in JSP as Java BEAN uses, JSP will save it to the corresponding internal object based on its scope.

If the scope is REQUEST, save it into the Request object. And only instantiate only when the first call (the value of the object is NULL). And if you create an object of this class directly in <%> , Each time you call JSP, you have to recreate the object, which will affect performance.

Code (1)

<%

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 operations will be thrown

Java.lang.nullpointerException

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 access JSP entered in the address bar of the browser is also case sensitive. Such as http: // localhost: 7001 / demo / t.jsp and http: // localhost: 7001 / demo / t.jsp is not The same (3). Judging the string in JSP To use the CompareTo method, do not use ==, because String variables in Java are not a simple variable but a class instance, different methods have different results, as follows Show:

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) 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, prevent the output from the JSP or Servlet from being saved in the browser. District

<%

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:

Name / Value pair, set the name of the cookie and the value it saved

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 to the service End, cookies are sent as part of the HTTP header, and if there is no setting domain, cookies are only related to the server created the cookie.

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 this cookie.

Both cookies have a validity period, the validity default value is -1, which means that the cookie does not save it when the browser exits, the cookie expands.

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 client's cookie to cookies with the following method, if cookies.length == 0, indicating 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);

}

Differences for seven, JSP and servlet:

转载请注明原文地址:https://www.9cbs.com/read-18552.html

New Post(0)