JavaWeb
JavaWeb technology mainly includes server technology (back-end), such as
Tomcat,Servlet,JSP
Waiting, and client-side technologies (front-end) such asHTML,CSS,JavaScript
wait a minute!
web server
Web servers are mainly responsible for processing HTTP requests from the client and respond accordingly
- Web server.Computers with server software installed are used only for complex processing of requests, sending out the corresponding
- Web server software:: Accepting client requests, processing requests and making responses
- web serverYou can deploy a web project and let the browser act as a medium to access it.
Web server software
Server software is deployed in the server program, there are mainly the following kinds, we mainly learn the use of Tomcat
- weblogic: oracle, a large javaEE server, supports all JavaEE specifications, charges.
- websphere: IBM, a large javaEE server, support for all ovaTE specifications, charges.
- JBOSS: JBOSS company, a large javaEE server, support for all the JavaIL specification, the charge.
- Tomcat : Apache Foundation , small and medium-sized javaEE server , open source , free .
Tomcat
Tomcat is a free open source Java Servlet (Server Applet, service program) container , mainly for the deployment and operation of Java-based Web applications , was founded by the Apache Foundation , belongs to the lightweight server .
Tomcat main features
- Servlet container:TomcatImplementing a Servlet Specification Container, can be used to deploy Servlet and JSP Web applications .JSP (JavaServer Pages) is a dynamic web content technology, which allows developers to embed Java code and features of JS into HTML pages
- Lightweight.Tomcat is a lightweight server, compared to other commercial servers.Fast startup and low resource consumption
- Easily configurable.Tomcat configuration file is simple and clear, easy to understand the modifications
Tomcat Architecture
-
Connector.Used to receive client HTTP requests and forward them to the corresponding
Servlet
,also providesSocket
together withRequest
cap (a poem)Response
Related transformations. -
Container:
Container
beTomcat
deal withServlet
The core component of the system consists ofEngine, Host, Context, Wrapper.
Tomcat
There is only oneServer
One.Server
can contain more than oneService
One.Service
Can only contain oneContainer
However, it is possible to include more than oneConnector
Because a service can have multiple connections; the schematic is as follows.
multi- (faceted, ethnic etc)Connector
and aContainer
It is then possible to form aSevrice
withService
It can be made available to the public, but it needs a runtime environment.Server
provides a runtime environment whose relationships can be found in theTomcat
(used form a nominal expression)conf
directory of theView in configuration file
Connector's relationship with Container
It is clear from the content of the appeal that a request sent to the
Tomcat
When it does, it passes through theService,
and then forwarded to ourConnector
-
Connector
is used to receive requests and encapsulate them intoRequest
respond in singingResponse
to deal specifically with.Request
cap (a poem)Response
After encapsulation, it will be handed over to theContainer
Processing.Container
After the request is processed it is returned to theConnector
, and finallyConnector
pass (a bill or inspection etc)Socket
Putting the results of the processing back to the client
Servlet
A Java Servlet is a program that runs on a web server or application server.It is used as a Web browser or other HTTP client requests and HTTP servers on the database and the application of the middle layer , which is essentially written in the java language, an interface
Advantages of Servlets
- Good performance
- Servlets execute in the address space of the web server, theSo there is no need to create a separate process to handle each client's request
- Servlets are platform independentBecause it is written in the Java development language.
Servlet Architecture
The following figure shows the location of the Servlet in the web application.
Servlet Tasks
- Reading display data sent by the client (browser). HTML forms on included web pages, or can be forms from applets or custom HTTP clients.
- Read the implicit HTTP request data sent by the client (browser), theIncludes cookies, media types and compression formats understood by the browser, etc.
- Processing data and generating results, a process that may require access to a database, execute RMI or CORBA calls, invoke web services, or directly calculate the corresponding response.
- Send explicit data (i.e. documents) to the client (browser). The format of the document can be various, including text files (HTML or XML), binary files (GIF images)
- Send an implicit HTTP response to the client
Servlet Life Cycle
*Servlet
life cycle can be understood as the process from creation to destruction*.
- Called after Servlet initialization
init()
methodologies - Servlet calls
service()
method to handle client requests - Called before Servlet destruction
destroy()
methodologies - Finally, servlets are garbage collected by the JVM's garbage collector.
Now we begin to explain in detail the Servlet's life cycle methods
init() method
init()
method is designed to be called only once. It is called when the Servlet is first created, thewill not be called for each subsequent user request.Therefore it is used for one-time initial
-
Servlet
is created on the first user call corresponding to theServlet
When the URL of theHowever, it is also possible to specifyServlet
Loaded when the server is first started - When a user calls a
Servlet
When it does, it creates aServlet
instance, a new thread is created for each user request. -
init()
method as long as its purpose is to simply create or load some data., these data are used by the user servlet throughout the cycle
The init() method is defined as follows.
public void init(ServletConfig servletConfig) throws ServletException {
//Initialization Code
}
service() method
The service() method is the main method for performing the actual task.
- Each time the server receives a Servlet request, the server spawns a new thread and invokes the service.
- The service() method checks the HTTP request type
(GET,POST,PUT,DELETE)
and, when appropriate, call theand other methods
Here is the code for its method
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
}
The service() method is called by the container, and the service method is called at the appropriate time. , so you don't have to do anything with the service() method, you just rewrite it for the different types of user requests.
doGet()
maybedoPost()
Methods can be
doGet() method
- A GET request comes from a normal request for a URL, or from an unspecified
METHOD
(used form a nominal expression)HTML
form, which is processed by the doGet() method
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost method
- The POST request comes from a specially specified
METHDO
because ofPOST
(used form a nominal expression)HTML
form, which consists ofdoPost()
methodology
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
Destroy() method
-
destory()
methodology andinit()
method can only be called once.Called at the end of the Servlet lifecycle - The destroy() method allows your Servlet to close a database connection, stop a background thread, write a list of cookies or a hit counter to disk, and so on.
- After calling the
destroy()
After theservlet
The object is then marked for garbage collection
The destory() method is defined as follows.
public void destroy() {
// Termination code...
}
The architecture diagram is as follows
configure
-
<web-app>
:The root element of the XML file, used to declare the version of the XML. encoding format and the location of the Web application's schema file (XSD).
-
<servlet>
cap (a poem)<servlet-mapping>
<servlet>
Class information used to define a Servlet, including its name and implementation of the class-
<servlet-name>
:SettingServlet
Name of the instance -
<servlet-class>
:: Configure the path to the class, make sure there is a corresponding class before you create it.
<servlet-mapping>
: Used to specify one or more URL patterns over the previously definedServlet
Mapping between-
<servlet-name>
:: Used to bindservlet
Label name needs to be the same as<servlet>
tagged<servlet-name>
concordance -
<url-patter>
: Configure the request path, the client request according to the path, can trigger the correspondingServlet
instance of theservlet
methodologies
<load-on-startup>
: Create a Servlet object on first access, set the value in the middle to a negative number.<load-on-startup>
:: Created after server startup, set intermediate value to a number greater than 0<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="/xml/ns/javaee" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>servlet01</servlet-name> <servlet-class>.MyServlet01</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>servlet01</servlet-name> <url-pattern>/a</url-pattern> </servlet-mapping> </web-app>
-
Servlet annotations
The use of annotations avoids the need for the
file for explicit configuration, thus reducing the complexity of the configuration file and improving development efficiency.
@WebServlet
- Role: tags are used to define their URL mapping and other configurations directly on the Servlet class
- Attributes.
-
value
maybeurlPatterns
: Specify one or more URL patterns that can be used to match HTTP requests and distribute them to servlets. -
name
:forServlet
Configure a name -
loadOnStartup
:DesignationServlet
Whether and in what order it is loaded at server startup -
asyncSupported
: Indicates if the Servlet supports asynchronous processing -
initParams
:: Initialize the parameter list
-
-
urlPatterns
Configuration method.
Configure multiple attributes with their attribute names
@WebServlet({"/demo1","/demo2",...}) // Configure multiple request paths to correspond to one servlet
@WebServlet("/user/demo1")//configure multiple paths
@WebServlet("/user/*")//match requests that begin with user
@WebServlet("/*")//match all requests
@WebServlet("/*.do")//match requests ending in do
HttpServlet
HttpServlet
beServlet
is an implementation of an abstract class. It is an abstract class that is implemented in the sourceServlet
interface adds some information about theHttp
protocol processing method, which is more powerful than theServle
t is powerful, and in the actual development, theImplementing an interface service usually inherits from this class and avoids direct inheritance.Servlet
resemble
GET requests and POST requests
GET request
A GET request is a
HTTP
Methods,Used to request resources from the server.When a client (usually a browser) makes a request to a server, the client can use it to create an application.It is in requesting a specific resource
-
Parameters for GET requests
- The parameters of a GET request are usually appended to the URL, using the
?
Separate URLs and parameters with the - The parameters are separated by using the
&
segregation - Example.
/resource?param1=value1¶m2=value2
- The parameters of a GET request are usually appended to the URL, using the
-
Security of GET requests
- All parameters in a GET request are exposed in the URL, so it may be recorded in the browser's history or log files, less secure
- Therefore, GET requests cannot be used to pass sensitive information, such as passwords, etc.
-
cache speed
- Browsers and other intermediate components cache the results of GET requests, thus leading to faster GET requests and improved performance
-
Limitations of GET
- Since the GET request is sent via a URL, and the URL itself has a length limitation.Therefore the length of GET is limited
-
General usage scenarios for GET
- GET requests are usually used to retrieve information, thesuch as querying a database or fetching static resources
POST request
Consistent with the GET request the POST request is also a
HTTP
method, which is used to send data to the server. When a client (browser) sends a request to the server using the POST method, theIt is submitting the data to the server for processing
-
POST request body
- POST requests are usually not placed in the URL, but in the body of the request.
- This means that the data will not be displayed in the URL, which is more secure and implicit than GET requests.
-
safety
- Since the data is not displayed in the URL, POST is more suitable for transmitting sensitive information.
- The data in a POST request is usually organized using an encoded format
-
POST Restrictions
- POST length is not limited, so large amounts of data can be transferred.
- But servers still have their own maximum limits
-
POST General Usage Scenarios
- POST requests are usually used to submit data, andsuch as login forms, registration forms
doGet() and doPost()
doGet()
doGet()
The methodology isHttpServlet
A method in the class
-
Type of request
-
doGet()
method is specialized for handling HTTP GET requests
-
doPost()
doPost()
The methodology isHttpServlet
A method in the class
- Type of request
-
doPost()
method is specialized in handling HTTP POST requests
-
:
@WebServlet("/login")
public class MyHttpServlet01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
("fulfillmentGETRequest business logic");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
("fulfillmentPOSTRequest business logic");
}
}
MyHttpServlet01
class isHttpServlet
class, overriding itsdoGet()
respond in singingdoPost()
method, we in Postman software can go to test its GET request and POST request respectively