Tip: servlet Introduction
Servlet is a technology provided by Sun for developing dynamic web resources.
Sun provides a servlet interface in its API. To send a dynamic Web Resource (that is, to develop a Java program to output data to the browser), follow these two steps:
Compile a Java class to implement the servlet interface.
Deploy the developed Java class to the web server.
Quick Start: Use servlet to output "Hello servlet" to the browser ".
Read the servlet API to solve two problems:
Which method should I write the Java code that outputs Hello servlet in?
How to output data to IE browser?
Create a web application, write a JAVA Implementation servlet interface in the WEB-INF \ Classes directory of the Web application, and overwrite the service method
Package CN. itcast;
Import java. Io .*;
Import javax. servlet .*;
Public class servletdemo1 extends genericservlet {
Public void Service (servletrequest req, servletresponse res) throws servletexception, java. Io. ioexception
{
Outputstream out = res. getoutputstream ();
Out. Write ("Hello servlet !!! ". Getbytes ());
}
}
2. Add servlet-related jar to the build path. javac only imports the j2se package API
Set classpath = % classpath %; C: \ apache-Tomcat-6.0.20 \ Lib \ servlet-api.jar;
3. Go to the directory where servletdemo1.java is located and compile servletdemo1.java
Javac-D. servletdemo1.java
4. Create a web. xml file in the WEB-INF directory of the web project and configure the external access path of Servlet
<? XML version = "1.0" encoding = "ISO-8859-1"?>
<Web-app xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
Version = "2.5">
<Servlet>
<Servlet-Name> servletdemo1 </servlet-Name>
<Servlet-class> CN. itcast. servletdemo1 </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> servletdemo1 </servlet-Name>
<URL-pattern>/servletdemo1 </url-pattern>
</Servlet-mapping>
</Web-app>
5. start Tomcat and IE access: http: // localhost: 8080/day05/servletdemo1
Servlet call Diagram
LServlet running process
The servlet program is called by the Web server. After the Web server receives the servlet access request from the client:
1. The web server first checks whether the servlet instance object has been loaded and created. If yes, go to step 1. Otherwise, go to step 2.
2. Load and create an Instance Object of the servlet.
3. Call the init () method of the servlet instance object.
4. Create an httpservletrequest object that encapsulates the HTTP request message and an httpservletresponse object that represents the HTTP Response Message. Then call the servlet Service () method and pass the request and response object as parameters.
Before the web application is stopped or restarted, the servlet engine uninstalls the servlet and calls the Servlet's destroy () method before uninstalling the servlet.
Servletdemo1ExtendsGenericservlet note that the imported source code is the SRC file of tomacat
LServlet interface implementation class
Servlet interface sun defines two default implementation classes: genericservlet and httpservlet.
Httpservlet is a servlet that can process HTTP requests. It adds some HTTP protocol processing methods to the original servlet interface. It is more powerful than the servlet interface. Therefore, when writing a servlet, developers should generally inherit this class, instead of directly implementing the servlet interface.
When httpservlet implements the servlet interface, it overwrites the service method. The code in this method automatically determines the user's request method. For example, if it is a GET request, it calls the doget method of httpservlet, for a POST request, the dopost method is called. Therefore, when writing a servlet, developers generally only need to override the doget or dopost method, rather than the service method.
The method that an object must be executed within the lifecycle is called the method related to the lifecycle.
Life cycle: When is the Life Cycle executed?
Some data is not suitable for writing in a program. It can be written through the configuration file.
Servletconfig object: Used to encapsulate servlet configuration information
In actual development, some items are not suitable for writing to the servlet program. Such data can be allocated to the servlet through configuration, for example, which code table is used by the servlet, Which database the servlet connects to, and which configuration file the servlet uses?
Servlet Lifecycle
When the server is requested by the servlet for the first time, the servlet will generate and then wait for the memory to respond to the request again without creating the object. The first created object will remain in the memory and respond to the request init method service method for the Service to be if the destory method is used to disable the server when the web application is deleted, it will die.
You must use refactor to change the name when changing the name, but you must modify web. xml.
Change the template to the eclipse folder, search for servlet. Java in the previous step, and then change
Be careful with name issues
LServlet details (1)
Because the client accesses resources on the Web server through the URL address, if the servlet program is to be accessed by the outside world, the servlet program must be mapped to a URL address, which works on the web. use the <servlet> element and <servlet-mapping> element in the XML file.
The <servlet> element is used to register a servlet. It contains two main sub-elements: <servlet-Name> and <servlet-class>, set the Registration Name of the servlet and the complete Class Name of the servlet respectively.
A <servlet-mapping> element is used to map an external access path of a registered servlet. It contains two sub-elements: <servlet-Name> and <URL-pattern>, it is used to specify the Registration Name of the servlet and the external access path of the servlet respectively. For example:
LServlet details (2)
The same servlet can be mapped to multiple URLs, that is, the value of the <servlet-Name> sub-element of multiple <servlet-mapping> elements can be the Registration Name of the same servlet.
* Wildcard can also be used in the URL mapped to the servlet, but there are only two fixed formats: one is "*. extension. The other format starts with a forward slash (/) and ends with a slash.
Exp: *. Do/Action /*
LServlet details (3)
For the following mappings:
Serving servlet1 to/ABC /*
Serving servlet2 /*
Serving servlet3 to/ABC
Serving servlet4 to *. Do
Problem:
When the request URL is "/ABC/a.html", "/ABC/*" and "/*" match, which servlet response
The Servlet Engine calls servlet1.
When the request URL is "/ABC", "/ABC/*" and "/ABC" Both match and the servlet response
The Servlet Engine calls servlet3.
When the request URL is "/ABC/a. Do", "/ABC/*" and "*. Do" Both match and the servlet response
The Servlet Engine calls servlet1.
When the request URL is "/a. Do", "/*" and "*. Do" Both match and which servlet responds
The Servlet Engine calls servlet2.
When the request URL is "/XXX/YYY/a. Do", "/*" and "*. Do" Both match and the servlet response
The Servlet Engine calls servlet2.
* Lowest priority
Pseudo-static: ing dynamic web resources to static Web Resources
Servlet is a Java class called by other Java programs (Servlet Engine). It cannot run independently. Its running is controlled and scheduled by the servlet engine.
For multiple servlet requests from the client, the server usually creates only one servlet instance object. That is to say, once the servlet instance object is created, it will reside in the memory, for other subsequent request services, the servlet instance object will not be destroyed until the Web Container exits.
If a <load-on-startup> element is configured in the <servlet> element, when a web application is started, the instance object of the servlet will be loaded and created, and the init () method of the servlet instance object will be called.
Example:
<Servlet>
<Servlet-Name> invoker </servlet-Name>
<Servlet-class>
Org. Apache. Catalina. servlets. invokerservlet
</Servlet-class>
<Load-on-startup> 2 </load-on-startup>
</Servlet>
Purpose: Write an initservlet for a web application. This servlet is configured to start the loading and create necessary database tables and data for the entire web application. When the server is started, initialize servlet for servlet configuration. The smaller the number, the higher the startup priority.
If the servlet ing path of a servlet is only a forward slash (/), the servlet becomes the default servlet of the current web application. The default URL is not followed by the URL-pattern.
All in the web. the URL of the matching <servlet-mapping> element cannot be found in the XML file. All access requests are sent to the default servlet for processing. That is to say, the default servlet is used to process access requests that are not processed by other servlets.
In the <tomcat installation directory> \ conf \ Web. an XML file named Org. apache. catalina. servlets. servlet ultservlet Servlet and set this servlet as the default servlet.
When accessing a static html file and image on the Tomcat server, the default servlet
You must never set the default value, so that you cannot view static html files and images when accessing Web Resources externally.
LServlet details (7)-thread security
When multiple clients concurrently access the same servlet, the web server creates a thread for each client's access request and calls the servlet service method on this thread, therefore, if the same resource is accessed in the service method, thread security problems may occur.
If a servlet implements the singlethreadmodel interface, the servlet engine calls its service method in single-threaded mode.
No method is defined in the singlethreadmodel interface (Mark interface: Only one interface has no method, and nothing is defined to implement such an interface, as if the class has a label, there are some functions ), you only need to add a Declaration to implement the singlethreadmodel interface in the servlet class definition.
For servlets that implement the singlethreadmodel interface, the servlet engine still supports multi-threaded concurrent access to the servlet. The method used is to generate multiple servlet instance objects, each concurrent thread calls an independent servlet instance object.
Implementing the singlethreadmodel interface does not really solve the servlet thread security problem, because the servlet engine creates multiple servlet instance objects, to solve the multi-thread security problem, a servlet instance object is called by multiple threads at the same time. In fact, in servlet API 2.4, singlethreadmodel has been marked as deprecated (obsolete ). Static, thread-safe, and memory crash
Be careful about static things that may cause memory bursts.
Java Web parameter passing Method
- Traditional Response Request
- Put the parameter in the threadlocal container, where the thread can retrieve the Parameter
- Start the JNDI container when the Java Virtual Machine starts and then bind the parameter to the container.
Thread security issues occur when multiple resource operations share data.
Web exceptions must be caught and cannot be thrown out.
When a subclass overwrites the parent class, it cannot throw more exceptions than the parent class, but it can catch
During the entire servlet lifecycle, the servlet init method is called only once (only one object is created ). Each access request to a servlet causes the servlet engine to call the servlet service method once. For each access request, the servlet engine will create a new httpservletrequest request object and a new httpservletresponse response object, and then pass these two objects as parameters to the servlet Service () It calls () the service method then calls the doxxx Method Based on the Request Method.
LServletconfig object
In the servlet configuration file, you can use one or more <init-param> labels to configure some initialization parameters for the servlet. Context-Param configures initialization parameters for the entire web application
L when the servlet configures initialization parameters, the Web Container automatically encapsulates these initialization parameters into the servletconfig object when creating the servlet instance object. When the servlet init method is called, pass the servletconfig object to the servlet. Then, the programmer can get the initialization parameter information of the current servlet through the servletconfig object.
Servletconfig object: Used to encapsulate servlet configuration information
// In actual development, some items are not suitable for writing to the servlet program. Such data can be allocated to the servlet through configuration, for example
// The code table used by the servlet, the database to which the servlet connects, And the configuration file of the Servlet
LServletcontext
When a Web container is started, it creates a corresponding servletcontext object for each web application, which represents the current web application.
L The servletconfig object maintains the reference of the servletcontext object. When writing a servlet, developers can obtain the servletcontext object through the servletconfig. getservletcontext method.
L because all servlets in a web application share the same servletcontext object, Servlet objects can communicate with each other through servletcontext objects. The servletcontext object is also calledContext domain object.
L view the servletcontext API documentation to understand the functions of the servletcontext object
Servletcontext implements request-based data forwarding so that it cannot be included because it is shared with the request domain.
Domain: Container Application Scope
Data sharing can be implemented using the servletcontext domain.
Two things: 1 is a container
2. The servletcontext field indicates the container's scope of application.
Request forwarding: 1 request
Redirection: 2 Requests
Each web application will be destroyed when a servletcontext is stopped.
Configuration File: XML (data related) Property (data does not matter)
Read resource files through servletcontext
Get the absolute path of the resource through getrealpath of servletcontext, and then read the resource file through the traditional stream
The Resource Name is better.
String Path = This. getservletcontext (). getrealpath ("/WEB-INF/classes/DB. properties ");
String filename = path. substring (path. lastindexof ("\") + 1); // method for obtaining the Resource Name
System. Out. println ("the name of the currently read resource is:" + filename );
Fileinputstream in = new fileinputstream (PATH );
From: http://archive.cnblogs.com/a/2038605/
Properties props = new properties (); // Map
Props. Load (in );
String url = props. getproperty ("url ");
String username = props. getproperty ("username ");
String Password = props. getproperty ("password ");
System. Out. println ("the currently read resource data is :");
System. Out. println (URL );
System. Out. println (username );
System. Out. println (password );
If the program that reads the resource file is not a servlet, it can only read the updated data through the class loader.
/*
// The following Code reads the data in the resource file, but cannot obtain the updated data class loading method.
Properties dbconfig = new properties ();
Inputstream in = userdao. Class. getclassloader (). getresourceasstream ("DB. properties ");
Dbconfig. Load (in );
System. Out. println (dbconfig. getproperty ("url "));*/
// Obtain the location of the resource file by means of class loading, and then read the data of the resource file in the traditional way, so that the updated data can be read.
String Path = userdao. Class. getclassloader (). getresource ("DB. properties"). getpath ();
Fileinputstream in = new fileinputstream (PATH );
Properties dbconfig = new properties ();
Dbconfig. Load (in );
System. Out. println (dbconfig. getproperty ("url "));
LCache servlet output on the client
L for infrequently changed data, you can set a reasonable cache time value for the servlet to avoid frequent browser requests to the server and improve server performance.
Range Header for breakpoint download