Java Web principles and related knowledge

Source: Internet
Author: User

 

1. [web server function] is to receive browser requests in real time and send the corresponding results back to the browser.
For access requests to static html file content, the web server can directly read the file content from the file system and return it to the browser.
However, for access requests that need to dynamically create content based on certain conditions, the web server itself does not have the ability to process such requests, but needs to be processed by a dedicated web server program module. Therefore, the process of creating a dynamic web page content consists of two steps: first, use a programming language to write the corresponding dynamic web page program, and then a dedicated web server program module to explain and execute the dynamic web page program.

[What is the engine? How does it interact with dynamic web pages ?]
Web server program modules that specifically explain the execution of a dynamic web page are often called engines, such as ASP engines, JSP engines, and servlet engines. The engine is provided in the form of expansion modules of web servers. Usually developed by companies that provide dynamic Web solutions. To communicate with dynamic web pages, the engine must provide some APIs (Application Programming Interface programming interfaces) for dynamic web pages.

[What are the functions of the APIS provided by the engine ?]
Send the request information to a dynamic web page, such as the visitor's IP address and request message header.
Transmits the results generated by the dynamic web page program to the engine.
[What is the role of the engine ?]
Only the engine can directly interact with the browser. A dynamic web page program does not directly interact with the browser. It only interacts with the engine. A dynamic web page program requires a dedicated web server program module to explain the execution (engine ).

[What is a Web Container ?]
2. servlet is a Java class called by other Java programs (Servlet Engine). It cannot run independently. The relationship between Servlet and Servlet Engine is the same as that between Applet and Web browser. Servlet running is fully controlled by the servlet engine. The servlet engine is a container program that manages and maintains the lifecycle of all servlet objects. Therefore, it is also called a Web Container or servlet container.

[What is the difference between a web server and a Web Container ?]
A Web container is an engine provided by the expansion module of web servers. A Web container is a capability of a Web server and a module of the Web server.

3. [What is Servlet ?]
Servlet technology is a solution provided by Sun to implement dynamic web pages. It is a web server-side Programming Technology Based on Java programming language. It is mainly used to obtain client access request information on the Web server and dynamically generate client response messages. Servlet technology is also the basis of JSP technology.

4. [servletconfig interface]. The Servlet Engine encapsulates the Objects representing the servlet container and the configuration parameter information of the servlet into a servletconfig object, it is passed to the servlet when initializing the servlet Instance Object (through the init (servletconfig config) method. The servletconfig interface defines the methods provided by the servletconfig object.

5. [How does the genericservlet class implement the servletconfig interface ?]
Although servlet. getservletconfig. servletconfig can be used.
To facilitate servlet programs to access various methods of servletconfig.

6. [genericservlet and httpservlet class .]
Genericservlet is a base class that implements the basic features and functions of servlet interfaces,
Httpservlet is a subclass of genericservlet. It provides the basic architecture for processing HTTP protocol. If a servlet needs to make full use of HTTP functions, it should inherit httpservlet.
Therefore, httpservlet can call not only newly defined internal methods, but also methods defined in servlet, genericservlet, and servletconfig classes.

7. [How do I differentiate between callback methods and tool methods ?]
The method specifically used for system calling is called a callback method, that is, the method that will be called by the system.
The callback methods in the genericservlet and httpservlet classes are for the container to call. They can be overwritten in the subclass, but cannot be directly called in the program code block.
In the genericservlet and httpservlet classes, callback methods and tool methods are processed. programmers can directly call the code block to complete a task. For example, the log method in genericservlet is used to record a piece of information to a log file.

8, [servletcontext class ],
Each web application is an independent servlet container, and each application is represented by a servletcontext object. The servletcontext interface defines the methods provided by the servletcontext object to external users. The servlet program communicates with the servlet container through these methods. The servlet engine creates a corresponding servletcontext object for each w/w complement and application. The servletcontext object is included in the servletconfig object.

9. You can set several initialization parameters for a Web application in the server. xml file and web. xml file.
For example, if multiple servlet programs in a web application need to output the company name of the current site, and the Web application may be used by multiple companies, then we can set the company name as the initialization parameter.
, You only need to modify the company name in the web. xml file, and the company name output by all servlet programs will change accordingly. To set initialization information for a Web application in the server. xml file, add the <parameter> sub-element to the <context> element corresponding to the Web application.

10. record logs. The servletcontext interface defines two reload log methods.
Two log methods are also defined in the genericservlet class. They call the corresponding log methods in the servletcontext object respectively.
The log method records the log file name and storage path based on the Web server. Set the storage path of the log file in Tomcat and the server. xml file. <Logger classname = "" directory = "" prefix = "" suffix = "" timestamp = "true">.

11. Obtain the local path mapped to the virtual path: the servletcontext interface defines a getrealpath method to return the local file system path mapped to a virtual path. If the path string passed to the getrealpath method starts with "/", this "/" indicates the root directory of the current web application, to return the local file path system mapped to the root directory of the Web application, the path passed to the getrealpath method can contain only one "/" character or an empty string.

[Httpservletresponse object ]:

12. If the Chinese characters in the source file of a webpage are not garbled, the display may be garbled because the browser displays the character encoding of the webpage.
The character texts of Java programs exist in the memory in the form of Unicode encoding,
The printwriter object returned by the getwriter method of the servletresponse object is converted to a byte array using the ISO8859-1 character encoding by default. However, there are no Chinese characters in the ISO8859-1 character set, and the unicoed Encoded chinese characters are converted into invalid character encoding and then output to the client. You can use setcharacterencoding, setcontenttype, and setlocale to specify the character encoding used by the servletresponse. getwriter object.

13. Let the browser regularly refresh the webpage or jump to another page. A refresh header field is defined in HTTP.
Response. setheader ("refresh", "2; url =/zhangxiaoxiangbook1/index. jsp ");
Response. setheader ("refresh", "2 ");

14. Disable the browser from caching the content of the current document.
You can disable the browser from caching the current page with three HTTP response header fields.
Response. setdateheader ("expires", 0 );
Response. setheader ("cache-control", "No-Cache ");
Response. setheader ("pragam", "No-Cache ");
Not all browsers fully support these three response headers. It is best to use it at the same time.

15. Use the <meta> label to simulate the response message header. The HTTP response header field allows the browser to complete various useful functions. For example, the browser does not want to cache a static html page whose content is often updated, you can add the following three statements between the <Meta http-equiv = "Pragma" content = "no-Cache">
<Meta http-equiv = "cache-control" content = "no-Cache">
<Meta http-equiv = "expires" content = "0">
However, if you add the following statement to the webpage body: <meta http-equiv = "refresh" content = "0; url = http://www.it315.org">
When you open this webpage document in your browser, you will immediately jump to the homepage of www.it315.org.
<Meta> one of the most common functions of a tag is to set the character encoding of the current webpage. When we access the static page of a Chinese website, the source file contains the following <meta> statement:
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> it implies what encoding the browser uses to display the webpage.
A <meta> statement should be added at the beginning of each static Chinese HTML page to set the character set encoding of the page, which has become the guiding principles and acceptance criteria for designing HTML pages.

16. servletresponse is an excuse for the servlet program to communicate with the servlet engine. The servlet program transmits the response body to the servlet engine through the servletresponse object, and then the servlet engine outputs the response body to the client. If a large amount of data needs to be transmitted between two modules. It is best to use an input or output stream as an interface for two modules to transmit data.
· The Byte output stream object type returned by the getoutputstream method is servletoutputstream, and servletoutputstream is a subclass of outputstream, which can directly output binary data in the byte array. This method should be used if the servlet needs to output the response body in binary format.
· The getwriter method wraps the data buffer of the servlet engine into a printwriter-type character output stream object and returns it. The printwriter object can directly output the character text content, so it is dedicated to outputting webpage documents with all the text characters.
· The preceding two methods cannot be used at the same time.
· It is best to call the HTTP response header information method before using the printwriter or servletoutputstream object. Pay special attention to setting the mime-type Content-Type header field.
· The service engine checks whether the close method is called for the output stream object of the getwriter or getoutputstream method after the servlet service method ends. If no close method is called, the service engine is automatically disabled. It is recommended that developers close the service to release related resources as soon as possible.
· Can the servlet program call the getwriter method of the httpservletresponse object multiple times? Can it be the same object?
A: Yes. It is the same object. The same is true for servletoutputstream.
· What is the difference between the printwriter. Print method and the printwriter. println method?
A: There is no difference in HTML display. Only when viewing the source file, if it is printwriter. println, it will automatically wrap the line for the personnel to read and understand.

17. [output buffer :]
The response body of the HTTP message output by the servlet program is not directly sent to the client, but first written to the servlet engine to provide an output buffer.
If the buffer is filled or the servlet program has written all the response content, the content in the buffer will be sent to the client by the servlet engine.
What are the benefits of using a buffer?
The servlet engine can adjust the response status lines, response headers, and response bodies in strict accordance with the HTTP message Location Order and then output them to the client, in particular, the context-Length header field can be automatically set and adjusted. If the output buffer is not used, the servlet cannot know the size of the response body before outputting the response body to the client, the context-Length header cannot be set automatically.
If the content loaded in the output buffer is only part of the response when a response is submitted to the client, the servlet engine cannot compute the context-Length header field, he will transmit the response content using the chunked encoding method of http1.1 (specified by setting the transfer-encoding header field), so that the context-Length header field does not need to be set.
Servletresponse defines several methods related to the output buffer:
· Setbuffersize () is used to set the expected output buffer size. The actual buffer used by the servlet engine is not necessarily equal to this value, but not smaller than it.
· Getbufferzsize () is used to return the actual buffer size used by the servlet engine.
· Flushbuffer () is used to forcibly output the buffer content to the client,
· Reset () is used to clear the content in the output buffer, as well as the configured response status code and various response headers. If the current response has already output some content to the client, an exception is thrown. Note that the difference between flushbuffer () and flushbuffer () is that the buffer content is handed over to the client in advance to free up the buffer space. Reset () is to void the buffer content and free up the buffer space.
· Incommitted () determines whether a part of the response content has been submitted to the client. If yes, true is returned. Otherwise, false is returned.
Response. setbuffersize (0 );
Int Len = response. getbuffersize ();
System. Out. println (LEN );

JSP.
1. Basic JSP Syntax:
· The JSP expression (expression) provides a simplified method to compute the results of a Java variable or expression to the client. variables or expressions in the JSP expression cannot be followed by semicolons (;), the JSP expression is translated into an out in the servlet program. print (...) statement. For example, <% = new java. util. Date () %> is translated into an out. Print (New java. util. Date () Statement in the servlet program.
· A jsp script (scriptlet) is one or more Java program codes nested between <% and %>. In JSP script snippets, you can define variables, execute basic program operations, call other Java classes, and other functions that can be implemented by common Java programs. The program code that must comply with the Java syntax requirements in the JSP script fragment. A JSP page can contain multiple script fragments.
Note: The Java statements in a single script fragment can be incomplete, but must the combined results of multiple scripts be complete Java statements, such as conditional statements or cyclic control statements. Because the Java code in all the script fragments will be moved into the _ jspservice method of the servlet translated from the JSP page.
· The Declaration JSP page is finally compiled into a servlet program. The variable declared in the script snippet is a local variable. If a method is defined in the script, it will also be moved into _ jspservice (), which will become an error of nested methods in the method. The JSP declaration solves such an error. It encapsulates the code in <%! And %>, and the code written by him will be inserted outside of _ jspservice. JSP Declaration can only define static code blocks, methods and variables. The scope of the JSP built-in object is limited to the Servlet's _ jspservice () method.
2. jsp designation (Directive): Page, include, taglib.
3. Out object: If out. the println statement is in response. getwriter (). before the println statement, the output content is placed after the output content of the latter, because out. the println statement only writes content to the buffer zone of the out object. when the end of the JSP page is reached, the out object writes the content in its buffer zone to the buffer zone provided by the servlet engine, response. getwriter (). the println statement directly writes the content to the buffer zone provided by the servlet engine.
[·] Note: In the following JSP, jspout. jsp
<% Servletoutputstream SOS = response. getoutputstream ();
SOS. println ("dddddd ");
%>
If any character is entered before or after the initial "<%" in this JSP, for example, a return key is entered after the last "%>, when displayed in a browser, an exception is reported.
Because any character text other than the JSP script element is converted into the out of the Servlet Source file translated from the JSP page. the Write statement is output to the client. Even if a carriage return is input outside the JSP script element, it is converted into an out. write ("\ r \ t"); statement. As long as the content is written to the out object, it will call the servletresponse. getwriter method at the end of the JSP page, which conflicts with the response. getoutputstream method called in the program.
Another example is jspout. jsp.
<%
Requestdispatch RD = application. getrequestdispatch ("test.html ");
Rd. forword (request, response );
%>
If any character is entered before or after the initial "<%" in this JSP, for example, a return key is entered after the last "%>, when displayed in a browser, an exception is reported.
Because the client's access requests to static html files and images are handled by Tomcat's default servlet, the default servlet first checks whether the getwriter object of the current httpservletresponse object has been called. If yes, the printwriter object returned by getwriter is used to output the content in the HTML file. Otherwise, the default servlet calls the servoutputstream object returned by the getoutputstream method to output the content in the static html file to the client as a byte stream.
When the requested jspfile is forwarded to the test.html page, servletresponse has not been called. getwriter method. The default servlet will call servletresponse. the getoutputstream method. After the default servlet is processed, the program returns to the JSP page for further execution, because the JSP page subsequently writes content to the out object ("\ r \ t" caused by the carriage return), servletresponse will be called at the end of the JSP page. the getwriter method causes a conflict.
If you add the following statement before the first sentence in the JSP script segment of the JSP page:
Response. getwriter ();
4. pagecontext object:
The pagecontext object is an instance object of the javax. servlet. jsp. pagecontext class. The pagecontext object encapsulates the running information of the current JSP page, and provides methods for returning other implicit objects on the JSP page.
Obtain other implicit objects:
· The getexception method returns the exception implicit object;
· The getpage method returns an implicit Page Object;
· The getrequest method returns an implicit request object;
· The getresponse method returns the response implicit object;
· The getservletconfig method returns an implicit config object;
· The getservletcontext method returns the application implicit object;
· The getsession method returns the implicit session object;
· The getout method returns an out implicit object;

5. jsp labels:
I.
<JSP: Include> the tag is used to insert the output content of a resource into the output content of the current JSP page.
<JSP: forword> A tag is used to forward data to another resource. Page is used to specify the relative path of the resource to which the request is forwarded.
<JSP: param> labels are used when <JSP: Include>, <JSP: forword>
When the resource to which tags are introduced or forwarded by requests is a program that can be dynamically executed, such as Servlet and JSP pages, you can also use <JSP: param> label to pass parameter information in this program. For example:
<JSP: Include page = "">
<JSP: Param name = "" value = ""/>
</Jsp: Include>
II.
Script element Tag: The jsp2.0 Specification defines script snippets, JSP statements, and JSP expressions on some tag pages, so that these script elements can be written in XML Syntax:
· <%> Can be replaced by <JSP: scriptlet> </jsp: scriptlet>
· <%! %> Can be replaced by <JSP: Declaration> </jsp: Declaration>
· <% = %> Can be replaced by <JSP: expression> </jsp: expression>
III.
Tag: The jsp2.0 Specification defines <JSP: Directive. directivetype> instead of <% @ direve ve... %> to define JSP settings in XML format. For example:
<% @ Page import = "" %> can be replaced by <JSP: Directive. Page import = ""/>

6. jsp Chinese garbled characters:
When the JSP Engine wants to determine the character set encoding of a JSP file, it first searches for the <page-encoding> element settings that match the JSP file in the deployment descriptor of the Web application. If not found, go down:
The pageencoding attribute specified by PAGE ---> Search character set encoding in the contexttype attribute specified by PAGE ---> Use ISO-8859-1.
Enter the following code in the web. xml file:
<JSP-config>
<JSP-property-group>
<URL-pattern>/JSP/* </url-pattern>
<Page-encoding> gb2312 </page-encoding>
</JSP-property-group>
</JSP-config>
Note: Web. the XML file does not declare the servlet specification version it complies with. By default, Tomcat complies with the servlet2.3 specification, JSP-cofig, JSP-proprty-group, page-encoding, and other elements are newly defined in the standardized deployment description file of servlet2.4, therefore, the <JSP-config> element configured above and its content do not take effect. You need to declare that the Web. xml file complies with the servlet2.4 specification (you can copy the file ). 7. handle the issue of sending requests in the get method: ① string name = request. getparameter ("name"); you can use new string (name. getbytes ("ISO-8859-1"), "GBK"); ② In the Tomcat server. modify in the XML file to add the uriencoding parameter to get data in get mode to specify UTF-8 (iso-8859-1 by default ): <connector Port = "8080" protocol = "HTTP/1.1" connectiontimeout = "20000" redirectport = "8433" uriecoding = "UTF-8"/>

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.