First, Web Basics
http protocol principle (master HTTP Compliance Request/Response model, HTTP is stateless protocol, port number is 80)
http protocol Processing Process
1. Establish a connection between the client and the Web server
2, the client sends the HTTP request
3. Server generates HTTP response postback
4, close the connection
http protocol request and Response Information format
Request Information:
Divided into request line, request header, blank line, message body (POST)
Response Information:
web Server defects:
Only static pages can be sent. The solution is to increase the number of secondary applications, and CGI is the standard for Web servers and external application communications. Can be developed in a variety of languages. But each time a request opens the process, which consumes a lot of server resources, Java uses a Web container plus a servlet to solve the auxiliary application. Every time a request opens a thread, all threads share the process where the Web container resides
web container function
The Web container is responsible for managing and running the servlet
Container support for the servlet includes
1. Communication support
2. servlet Lifecycle Management
3, multithreading support
4, JSP support
5. Handling Security
The composition of the web application
The content inside the Web-inf is not directly accessible by the client. Generally used to store some of the more secret information
TOMCAT directory Structure (
Bin directory (Tomcat startup and shutdown directory)
Conf (Tomcat configuration directory)
WebApps (Web application Drop directory)
Work (mainly used as JSP translation and compilation directory)
) Second, the servlet
servlet class Structure
In accordance with Sun's specifications, each servlet class must implement a servlet interface. where the service () method is provided to the user to implement the business method. Genericservlet implements a simple implementation of the servlet and ServletConfig (interfaces for servlet configuration), but does not implement the service method. The method is implemented by its subclasses according to the characteristics of its different protocols. HttpServlet is a subclass of Genericservlet. The service () method is implemented specifically for the HTTP protocol. Invoke the Doxx () method for different request types. So when we write a servlet class, we generally just need to inherit httpservlet and rewrite the Doxx () method.
Coding and deployment of servlet
public class Testservlet extends HttpServlet {
public void doget (HttpServletRequest request,httpservletresponse response) throws ioexception,servletexception{
}
The servlet can be recognized by the container only after the Web container is registered
Test servlet name, the container finds the corresponding servlet based on it
Com.lovo.Test servlet class full path
Test servlet name, which is found by the client according to the request URL
/ABC Client Request URL
@webservlet (urlpatterns= "/test") registration can be used in the SERVLET3 standard
servlet URL Mapping path
1. Exact match/ABC The servlet can be found with ABC request
2, extended matching *.do to the. Do end request to find the servlet
3, path matching/abc/* to/abc/directory requests can find the servlet
Plus Slash, back to the WebApps root directory, then the request path must be added to the cloth signature
Find in current directory
## #Servlet生命周期
1, the container starts, will read the Conf/server.xml file, to determine the boot port and Web application storage path
2. Web container startup reads the Web.xml file configuration information for each Web application and resolves the web.xml file. Get servlet configuration information.
3. Container load and instantiate servlet
(web.xml file Configuration servlet if one is greater than or equal to 0, the startup container is instantiated, if it is a negative number or the default is the first request instantiation)
4. The container invokes the Init () method initialization
5, each request calls the service () method to complete the logic
6. Container Discard servlet call Destroy () method
1, 2, 3, 4, 6 execute only one line, and only 5 are executed on every request. And throughout the lifecycle, the Servlet object has only one single instance of multithreading.
servlet Configuration object: ServletConfig can read related initialization information.
servlet Global objects: ServletContext for the entire Web application
Function: 1, can use Getrealpath () to obtain the true path of resources
2. You can use the getattribute (), and setattribute () methods to share global variables.
3, can read the global initialization information three, redirect
http Status Code
HTTP status code:
100-199: Informational code, indicating the other actions the client should take, the request is in progress.
200-299: The customer request is successful.
300-399: Represents the resource file that has been moved, indicating the new address.
400-499: An error that is raised by the client.
500-599: An error that is raised by the server side.
Sets the status code senderror (code, "Resource not Found");
In the format of the response information, there is a status line, then a message body, so note that the status code is set before using PrintWriter to output information to the client
Set HTTP response headers
Purpose to tell the client
The type of content sent back
How much content is being sent
The type of server that sent the content
Set the response header method: SetHeader () or setheaders (). Note: Setting the response header can only be an HTTP protocol. So SetHeader and Setheaders () are all methods in HttpServletResponse.
Set HTTP message body
Response.getwriter () Gets the print character stream and can output text
Response.getoutputstream () obtains output byte stream, can send binary data.
Principle of Redirection
Redirect Call Method Response.sendredirect ("http://127.0.0.1:8080/lovobook/bar.html");
1, the browser sends an HTTP request to the server.
2, when the server receives the request, the Response.sendredirect () method is invoked, indicating that the resource has been moved. A 302 status code and a location response header are sent. In the location response header, indicate the address to forward.
3, after receiving the 302 status code, the browser reads the contents of the location response header and assigns the value of the address bar to the contents of the location response header. A second request is made to the server. Because it is two requests, redirection cannot get the property information encapsulated in Request Iv. Get/post
The main methods of http request submission are get and post
Get Request method
The browser sends an HTTP request to the Web server
User clicks on a hyperlink on a Web page
User submits a form that is completed on a Web page
The user enters the URL address in the browser address bar and returns
By default, the request is submitted using the Get method of the HTTP protocol
Post Request method
Difference between get and post methods:
The format of the stream:
The Get method request parameter is placed behind the URL with no message body.
Post-mode request parameters are placed in the body of the message.
Use:
Get mode is primarily used for resource lookup, indicating that clients need to find a resource on the server
Post methods are mainly used for data transmission, mainly for the server to receive the information sent by the client.
Transmission performance:
Feature Get method Post method
Submit data type text text, binary text
Submission data length not exceeding 255 characters no limit
Submitting data visibility as part of the URL address is displayed in the browser address bar as the requested message body, not visible,
The commit data cache cache is not cached by the browser in the browser URL history state
Get HTTP request line
GetMethod (): Gets the HTTP request method, such as GET, post, etc.
GetQueryString (): Gets the query string after the request URL. Only valid for Get
Getservletpath (): Get the mapping path of the servlet
Fetch Request Headers (valid only for HTTP protocol)
GetHeader (name): Returns the value of the specified request header
Getheaders (name): Returns a enumeration (enum) containing all the values in the request header
## #获得表单数据
GetParameter () Method: Gets the parameter value of the specified name, returning the string type. If there are multiple keys with the same name, the value of the first key is returned.
Getparametervalues () Method: Gets multiple values of the parameter of the specified name, and returns the result as an array of strings.
Get message body
Post requests can not only obtain form data through the GetParameter () method, but can obtain form data in bytes by getInputStream (), so you can get the binary stream of the uploaded file
Request for distribution
RequestDispatcher dis = request.getrequestdispatcher (path)
Dis.forward (Request,response);
Client requests can be sent to multiple servlet and other resources in the Web application. The whole process is done only on the server side, without the participation of the client, that is, the client can implement the forwarding function by sending the original request only once. So by requesting forwarding, the target resource can get the attribute information encapsulated in the request
Request forwarding and redirection cannot be made after request forwarding and redirection.
Request Range
Variables can be saved in the request scope
The difference between internal forwarding and redirection cannot be accessed beyond the scope of the request:
1. Internal forwarding is issued by RequestDispatcher, and redirects are sent by response.
2, the internal forwarding a request, redirect two times request.
3. Internal forwarding can remove the data encapsulated in the request, redirection cannot be.
4, internal forwarding only within the server, redirection can request other servers. v. State Management
Why to state management
The HTTP protocol uses a stateless connection
For a container, each request comes from a new customer
Solution:
1. Hide form fields
2. Cookies
3, session
4. URL rewrite Cookie
The client makes a request to the server, after the server receives the request, if the Response.addcookie () method is invoked. The server sends the Set-cookie response header to the client, which places the text information in the client's cookie. When a client sends a request to the server again, the contents of the cookie are sent to the server as a cookie request header, which can be judged by the contents of the cookie to be the same customer's request.
Cookies are easily turned into privacy issues because they are placed on the client and sent as text. Cookies are divided into two types, one in the client browser cache and one in the client's file. Session
A session is an object that is placed on the server side. Used to save client user information.
Session working principle:
The client sends a request to the server, and the server assigns a session object to the client at the time of receiving the request and assigns a unique identification Jsessionid to the session. When this process is complete, the ID and session object are saved in a map collection and the session ID is sent to the client in a cookie. When the client sends the request again, the ID of the session is sent to the server in the form of the request header, and the server finds the corresponding session object from the map collection through the ID of the session.
Session and Cookie differences:
1, the session data is placed on the server side, and the cookie information placed on the client.
2, the session is a server-side object, the encapsulated data is an object. And the cookie's data is text.
Access to session objects:
Gets the session through the Request.getsession (Boolean) method. Parameter is true if there is no session object, a Session object is created, and if there is a session object, it is returned directly, but false if there is a session object that returns null if there is no reply object. It is worth noting that there are no parameters and getsession (true) is the same effect. Session life cycle:
Within the scope of a session. When the session object is generated, the object is bound to the client browser, and the session is valid for the timeout period, as long as the browser is not closed. When the browser is closed and a browser is reopened, the server will be allocated a new session object.
Because session is the object that is placed on the server side. So when the client closes the browser, it does not mean that the session object is destroyed. So at some time, be sure to destroy the session object to free up the server memory resources.
• Several ways to destroy a session:
1, set the session timeout time
Setmaxinactiveinterval (int) The maximum time, in seconds, to specify a client request for a dialog
Configuring in Web.xml
15
It's worth noting that 15 is a minute here.
2, call the session of the Invalidate () method
3, application end, or server crashes
# # #URL重写
Cookies may be disabled by some clients because of their unsafe conditions. Because the session (mainly refers to the ID of the session) is also passed by cookie, when the user disables cookies, SessionID can not reach the server. The server also cannot maintain and client state. In this case, the ID of the session can be imposed at the end of each URL by URL rewriting, so that SessionID can be sent to the server when the server is asked.
Invokes the Encodeurl () method of the response object to compile the URL, attaching sessionid to the URL.
Click VI, Listener, and scope objects
Scope object property Action method scoping range description
ServletContext (context) void setattribute (String, Object)
Object getattribute (Sting)
void RemoveAttribute (String)
Enumeration Getattributenames () the entire Web application
HttpSession (session) A session interaction process
ServletRequest (Request) One request process
Listener Overview
1. Monitor the change of access data in these three objects of Session,request,servletcontext
2. The Listener object can do some necessary processing before and after the event.
3. The main purpose of the servlet listener is to increase the event handling mechanism for Web applications to better monitor and control state changes in Web applications
Listener implementation steps:
1. Determine the source of the event. Event Source: Servletcontext,session,request
2, determine the listener. Listeners must implement the listener interface and implement logical methods in the Listener interface
3, registration
The listener can only be recognized by the container after it has been registered.
Com.lovobook.MyServletContextListener
@weblistener registration can be used in the SERVLET3 standard
Listener Type
1, Servletcontextlistener: for monitoring ServletContext object creation and destruction of events.
void contextinitialized (Servletcontextevent SCE)--When a context object is created, triggers
void contextdestroyed (Servletcontextevent SCE)--triggers when a context object is destroyed
2, Httpsessionlistener interface: monitor the creation and destruction of httpsession.
sessioncreated (httpsessionevent se) Method-Creates a httpsession trigger.
sessiondestroyed (httpsessionevent se)--Destroy HttpSession Trigger
3, Httpsessionbindinglistener: The only interface that does not need to register
When a class implements the Httpsessionbindinglistener interface, As long as the object joins the session scope (that is, when the setattribute method of the HttpSession object is invoked) or is removed from the session scope (that is, when the RemoveAttribute method of the HttpSession object is invoked or session Time out, the container automatically invokes the following two methods, respectively:
Valuebound (Httpsessionbindingevent Event)--triggered when bound to session
Valueunbound (Httpsessionbindingevent Event)--trigger when session is removed seven, filter filter Concept
A filter is an intermediary component used to intercept messages between source and destination data
Filter the data passed between the two
Filter Implementation steps:
1, writing Filter class
Filter class must implement Javax.servlet.Filter interface
public class Helloworldfilter implements Filter {
Private Filterconfig Filterconfig;
public void init (Filterconfig filterconfig) {//initialization method
This.filterconfig = Filterconfig;
}
public void Dofilter (
ServletRequest request, Servletresponse response,//requests and responses are not based on HTTP protocol
Filterchain Filterchain//Send the request to a later filter or target resource
Throws Servletexception, IOException {//Business method, writing filter content
PrintWriter pw = Response.getwriter ();
......
Filterchain.dofilter (Request,response);
}
public void Destroy () {//Destroy method
}
}
After the Filterchain Dofilter method is invoked, the request resource is sent to the target resource. At this point, you can no longer do redirection and internal forwarding, or throw an exception.
2, complete the filter in the container registration
Helloworldfilter
Com.lovobook.HelloWorldFilter
Helloworldfilter
/filter/*//resource filtering corresponding to request URL
testservlet//for servlet filtering
In the SERVLET3 standard, you can register filter types using @webfilter (urlpattern= "/test")
<filter-mapping>
<filter-name>ValidatorFilter</filter-name>
<url-pattern>/ Filter/*</url-pattern>
<dispatcher></dispatcher>--If the request is represented by requesting URL filtering (default), If the internal forwarding filter is forward
Filter Chain
Working with multiple filters on the same request
Use multiple elements to configure the filter chain
First call the filter that matches the request URI
Find all filters that match the request URI with the servlet name
The order in which filters are executed is sorted by the order in which they appear in the deployment description file
# #八, JSP servlet flaw
–servlet's coding, deployment, and debugging tasks are tedious
-Create dynamic Web pages cumbersome, not conducive to project division of Labor
jsp is created to address the servlet flaw. Let's write the output as if it were a normal web page. jsp life cycle
1. The first time a Web container receives a request for a JSP page, it first automatically translates the JSP page into Java code.
Tomcat puts the translated code under the/work subdirectory of the Tomcat installation directory
Tomcat has the following descriptions under the/conf subdirectory
Jsp
org.apache.jasper.servlet.jspservlet//jsp engine, complete translation work by it
... ...
Jsp
*.jsp
2. The Web container is responsible for compiling the servlet code into byte code. With the source files in the same directory, in the JSP lifecycle, the entire translation and compilation steps occur only once
3. The Web container mounts the newly generated servlet class
4. The Web container creates a Servlet instance object when the first request arrives. There is only one object in the whole life
5, the Web container calls the Servlet sample Jspinit () method, JSP page load resource
6, each request arrives executes the _jspservice () method, the output content
7. The container invokes the Jspdestroy () method of the generated Servlet object, destroying the loaded resource
by JSP specification all JSP classes must implement the Httpjsppage interface, which is a servlet sub-interface, so the JSP is essentially a servlet
jsp is a servlet class, so you can write Java code in your JSP, but don't embed too much Java code to increase the difficulty of reading and maintaining. The JSP is displayed, and the servlet is logically implemented. JSP Implicit Object
In the translated class, there are nine local variables in the _jspservice (), and all are initialized. Because the content we write in the JSP is Rich _jspservice () method, we can use these local variables directly, this is the implicit object
Four scopes:
PageContext: Acting on the page
Request: Acting on requests
Session: Acting on sessions
Application: Acting on the global (type is ServletContext)
Two outputs:
Response: Response Object
Out: Print character stream, type JspWriter
A Configuration Object
Config: type is servletconfig
A current object
Page: Refers to the object of the currently translated class
An exception object
Exception: Type is throwable jsp script element
Script element Script syntax
Statement <%! Declare%> for JSP translations class, define member variables, static variables, and methods
Scriplet <% Code%> Rich _jspservice method, is normal Java code
Script expression <%= script expression%> equivalent to Out.print but note that the following cannot be followed by a semicolon directive
in JSP, there are three kinds of instructions
The page instruction provides processing instructions for the current page
ContentType sets the MIME type and character encoding output to the client
Import imports packages in the current JSP class
The include directive is used to include another file in the JSP
Format: <%@ include file= "Relativeurl"%>
Static inclusion, which occurs at compile time. Copies the contents of the included file in the include file. So two pages cannot have the same variable. Contains content and can only contain files
The taglib directive specifies how to include and access a custom tag library
<% @taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%> action
Action is a dynamic inclusion
The syntax format is:
Page: Represents a dynamic inclusion of a relative path, containing the result, which occurs at the time of the request, so that the two pages can have the same variable, can contain the file and can contain the results of the servlet output, and can pass parameters. But the efficiency is lower than the instruction contains
The included page can be taken out of the value by Request.getparameter ("ABC")
Action, equivalent to Request.getrequestdispatcher (). Forward () internal forwarding
The syntax format is:
JSP comments:
<%––%>jsp annotations, containers are not translated, and are not visible to the server or client only when the source code is visible. Most secure.
HTML annotation, the container will output HTML comments to the client, both the server and the client are visible. Cannot annotate dynamic scripting code.
/* * */Java code comments. Visible only on the server. Nine, JavaBean
JavaBean Specification:
The JavaBean class must be a common class and set its Access property to public.
The JavaBean class must have an empty constructor
A JavaBean class should not have public instance variables, and class variables are private. To access these class variables, you should access them through a set of accessor methods (GetXXX and SETXXX), you cannot name the member variables in uppercase letters, and the first two letters cannot be uppercase
JavaBean should be serializable (serializable), that is, to implement the Java.io.Serializable interface
Three-tier architecture:
Persistence layer (DAO mode): Create entity classes and database tables for mapping. That is, which table corresponds to which class, which attribute corresponds to which column, and the persistence layer is to complete the object data and relational data conversion.
Business layer (transaction script): Encapsulates the data requested by the client into a single method. The method may invoke multiple Data update operations depending on the business needs. You must ensure that these operations succeed at the same time and fail. Data confusion caused by partial failure of partially successful parts is not allowed.
Presentation Layer (MVC):
M: The model, which is the entity bean. Used to encapsulate and transmit data
V: View, which is HTML and JSP. For presentation of data
C: Control, which is the servlet. The business method that invokes the business class and controls the flow of the operation. 10, EL
El expression:
My dog's name is: ${person.dog.name} need attention. When a property value is taken from an El expression, the Get method is invoked. If the attribute is not written, but there is a get method, the data can also be fetched through an EL expression
Look for attribute values from PageContext, request, Session, ServletContext, and look up from small scopes to large scopes, and then find them no longer.
You can reduce the search scope by using an El expression implicit object ${requestscope.name}
El implicitly-scoped object scope
Pagescope the Map class associated with the name and value of the page scope property
Requestscope the Map class associated with the name and value of the request scope property
Sessionscope the Map class associated with the name and value of the session scope property
Applicationscope the Map class associated with the name and value of the application scope property
An El expression can also support an operation. 1+2 display 3 {1+2} on the page display 3 {3>2} on the page true JSTL standard tag Library (emphasis)
Requires two jar files. The first file is Jstl.jar, which provides an API class for the JSTL tag library. The second file is Standard.jar, which provides the implementation class for the tag library.
Jstl is divided into five kinds: core Library core,xml Library, SQL Library, i18n Library, function library. Core libraries are most commonly used
Import a standard tag library on a JSP page
Introduced to JSP via <%@ taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%>
Judge Tags: The condition is true, the contents of the execution tag body
${X}
Loop label
Traverse Collection Collection
Man.id {man. id} {mans. Name}
Traversing the Map collection
Key object: Bean.key value: {Bean. Key} value: {Bean.value. Name}
AJAX
Ajax involves 7 technologies, Javascript, XMLHttpRequest, Dom, XML, css,xhtml, and server-related APIs
The content of this chapter is mainly based on operation
Creation of XMLHttpRequest objects
var xmlHttp = null;
function Setxmlhttp () {
if (window. ActiveXObject) {//ie
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (window. XMLHttpRequest) {//firefox
XmlHttp = new XMLHttpRequest ();
}
}
XMLHttpRequest Common Properties and methods
When the readiness state changes, call the press method to monitor the object and get the response information
Xmlhttp.onreadystatechange = Press;
Get mode send request
The first argument is the Commit method, the second parameter represents the request URL, and the third parameter is true to the asynchronous transmission, while indicating that the client does not execute the code when the response information is not reached
This step is to set the request line
Xmlhttp.open ("Get", "checkservlet?name=" +username,true);
This step sets the body of the message and sends the request to the server
Xmlhttp.send (NULL);
Post mode send request
Xmlhttp.open ("POST", "Checkservlet", true);
Set the request header to submit for normal form format
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Post method, the message body content is the request parameter
Xmlhttp.send ("name=" +username);
callback function
function Press () {
When the XMLHTTP ReadyState property is 4, the XMLHttpRequest object returns the response information
if (xmlhttp.readystate = = 4) {
Xmlhttp.status indicates the status code to obtain the response information
if (Xmlhttp.status = = 200) {
The call server returns information about the body of the message
var info = Xmlhttp.responsetext;
}
}
}
Use jquery to send an AJAX request
GET request
. Get ("Test", Name: "John", Time: "2pm", function (data) alert ("dataloaded:" +data);, " JSON ")