1.Web process
1.1 software architecture
1. C/S: client / server
cs architecture is built on a dedicated network and generally faces relatively fixed user groups. It can verify permissions at multiple levels, provides a more secure access mode, and has strong control over information security;
- B/S: Browser / server side
The bs architecture is based on the wide area network and is oriented to the unknowable user group. The security control ability is relatively weak.
1.2 resource classification
1. Static resources: all users get the same results after accessing them, which is called static resources. Static resources can be directly parsed by the browser, such as HTML, CSS and JavaScript
2. Dynamic resources: each user may get different results after accessing the same resources. It is called dynamic resource. After the dynamic resources are accessed, they need to be converted into static resources and returned to the browser, such as servlet/jsp,php,asp
1.3 three elements of network communication
1. IP: the unique identification of electronic equipment (computer) in the network.
2. Port: the unique identification of the application in the computer. 0~65536
3. Transmission protocol: Specifies the rules of data transmission
Base agreement:
1. tcp: security protocol, three handshakes. The speed is a little slow
2. udp: insecure protocol. speed
1.4 flow chart
1. The front end sends a request and accesses the background interface according to the path information.
The request path includes protocol, ip address, port number and path
Find the server by ip address
Find the web server program through the port number
Find the executed code through the specific path
2. After receiving the request, the back end processes it. After processing, it returns a response to the front end.
3. During back-end processing, data operations will be completed through interaction with the database.
2.Web server software
2.1 concept
Server: the computer on which the server software is installed.
Server software: receive the user's request, process the request and respond.
web server software: receive the user's request, process the request and respond.
In web server software, web projects can be deployed to allow users to access these projects through a browser. In fact, it can be understood as a web container.
2.2 common java related server software
1.webLogic: oracle company, a large Java EE server, supports all Java EE specifications and charges. 2.webSphere: IBM, a large Java EE server, supports all Java EE specifications and charges.
3.JBOSS: JBOSS company's large-scale Java EE server supports all Java EE specifications and charges.
4.Tomcat: Apache foundation, a small and medium-sized Java EE server, only supports a small number of Java EE specification servlets / JSPS. Open source, free.
2.3 Tomcat
1. Introduction
Tomcat is a core project of the Jakarta project of the Apache Software Foundation, which is jointly developed by Apache, Sun and some other companies and individuals. With the participation and support of Sun, the latest Servlet and JSP specifications can always be reflected in Tomcat. Tomcat 5 supports the latest Servlet 2.4 and JSP 2.0 specifications. Because Tomcat technology is advanced, stable and free, it is loved by Java enthusiasts and has been recognized by some software developers. It has become a popular Web application server.
Tomcat server is a free open source Web application server. It is a lightweight application server. It is widely used in small and medium-sized systems and when there are not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a beginner, you can think that when Apache server is configured on a machine, you can use it to respond to the access request of HTML (an application under the standard General Markup Language) page. In fact, Tomcat is an extension of Apache server, but it runs independently at runtime, so when you run tomcat, it actually runs independently of Apache.
2. Download, install and uninstall
Download from the official website: http://tomcat.apache.org/
Installation: decompress the compressed package
*Note: it is recommended that the installation directory should not contain Chinese and spaces
Uninstall: just delete the directory
3. Catalog introduction
4. Start access and close
Start: bin/startup.bat. Double click the file to run it
Accessing: Browser input http://localhost:8080 Enter to visit yourself Http: / / others' ip:8080 visit others
Close bin/shutdown.bat and double-click to run the file
5. Modify the port number
In the server.xml file under the Conf directory, find
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
Change 8080 to the desired port
How to solve the failure of modifying the Tomcat port number?
Because multiple Tomcat s are deployed on the server, different port numbers need to be used, but after the project is restarted after modification, the previous port number will be returned. How to solve this problem?
Methods: 1. Comment out if not "% catalina_home%" = = "goto gothome" in "bin --" startup.bat "at the startup of tomcat (rem is used for comments here).
2. Change the 8080 port in the middle to the port you set yourself in conf --- server.xml.
3. Just restart.
Tomcat console garbled
-->The default code of windows is GBK, while the default code of Tomcat is UTF-8. You need to change the code of Tomcat to GBK
-->Find the logging.properties file in the conf directory of the Tomcat directory, and change java.util.logging.ConsoleHandler.encoding to GBK
6. Project deployment
1. Mode 1
Directly put the project into the webapps directory.
Simplify deployment: type the project into a war package, and then place the war package in the webapps directory. * The war package is automatically decompressed
- Mode II
Find the conf directory \ Catalina\localhost \ under Tomcat and create the following configuration file
The abc.xml configuration file is as follows:
<!-- Context represents a project context
Path indicates the access path of the project: / abc
docBase indicates where your project directory is
-->
<Context path="/abc" docBase="E:\book" />
The path to access this project is as follows: http://ip:port/abc/ This means accessing the E:\book directory
3.Servlet
three point one summary
Servlet (Server Applet) is the abbreviation of Java Servlet, which is called small service program or service connector. The server-side program written in Java is independent of platform and protocol. Its main function is to interactively browse and generate data and generate dynamic Web content.
Servlet in the narrow sense refers to an interface implemented in Java language. Servlet in the broad sense refers to any class that implements the servlet interface. Generally, people understand servlet as the latter. The servlet runs in an application server that supports Java. In principle, servlets can respond to any type of request, but in most cases, servlets are only used to extend Web servers based on HTTP protocol.
JavaSoft's Java Web Server was the first to support the Servlet standard. Since then, some other Java based web servers began to support the standard Servlet.
What is a Servlet?
1. Servlet is one of the Java EE specifications. A specification is an interface
2. Servlet is one of the three major components of Java Web. The three components are: servlet program, Filter filter and Listener listener.
3. Servlet is a java applet running on the server. It can receive requests sent by the client and respond to data to the client.
3.2 getting started
one Create a web project in idea
Refer to Youdao cloud notes - idea user guide, the link is as follows:
http://note.youdao.com/noteshare?id=48569c74ce3c409c3ac921b1c00ed425&sub=6A790066C9734EC18A9BF90D99548AAC
two Create servlet
Generally, in the actual project development, the Servlet program is implemented by inheriting the HttpServlet class.
1. Write a class to inherit the HttpServlet class
2. Override doGet or doPost methods according to business needs
3. To the access address of the configuration Servlet program in web.xml
Code in Servlet class
public class HelloServlet_01 extends HttpServlet { /** * doGet()Called when a get request is made * @param req * @param resp * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("HelloServlet_01 Medium doGet method"); } } /** * doPost()Called at the time of a post request * @param req * @param resp * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("HelloServlet_01 Medium doPost method"); }
Configuration in web.xml
<servlet> <servlet-name>_02_ServletLife</servlet-name> <servlet-class>com.tledu.servlet._02_ServletLife</servlet-class> <!-- set up servlet Timing of initialization,The default is -1,Initialize on first request --> <!-- 0 And positive integers are started when loading,start-up TomCat When --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>_02_ServletLife</servlet-name> <url-pattern>/s</url-pattern> </servlet-mapping>
3. Execution principle
3.3 life cycle
Servlet life cycle is an execution process from the creation of servlet objects to their death
1 first execute the construction method to create the Servlet object
2. Execute the init() method for initialization
3. Execute the service()/doGet()/doPost() method to handle the real logical operation and data interaction
4. Execute the destroy() method to release and destroy resources
As can be seen from the above example, by default, the servlet is initialized at the first request, and the construction method, init method and service method will be executed at the first request
Another request will only execute the service method
Of course, we can also initialize the servlet when TomCat is started through the configuration in web.xml
Use load on startup to set the initialization time
<servlet> <servlet-name>_02_ServletLife</servlet-name> <servlet-class>com.tledu.servlet._02_ServletLife</servlet-class> <!-- set up servlet Timing of initialization,The default is -1,Initialize on first request --> <!-- 0 And positive integers are started when loading,start-up TomCat When --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>_02_ServletLife</servlet-name> <url-pattern>/s</url-pattern> </servlet-mapping>
three point four ServletConfig class
From the perspective of class name, ServletConfig class is the configuration information class of Servlet program. Both the Servlet program and the ServletConfig object are created by Tomcat and used by us. By default, Servlet programs are created during the first access. ServletConfig is that each Servlet program will create a corresponding ServletConfig object when it is created.
- Three functions of ServletConfig class
1. You can get the value of the alias Servlet name of the Servlet program
2. Get initialization parameter init param
3. Get ServletContext object
Configuration in web.xml:
<servlet> <servlet-name>HelloServlet1</servlet-name> <servlet-class>com.tledu.servlet.HelloServlet_01</servlet-class> <!--init-param Is an initialization parameter--> <init-param> <!--Is the parameter name--> <param-name>username</param-name> <!--Is the parameter value--> <param-value>root</param-value> </init-param> <!--init-param Is an initialization parameter--> <init-param> <!--Is the parameter name--> <param-name>url</param-name> <!--Is the parameter value--> <param-value>jdbc:mysql://localhost:3306/test</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>HelloServlet1</servlet-name> <url-pattern>/hello1</url-pattern> </servlet-mapping>
Code in Servlet
@Override public void init(ServletConfig servletConfig) throws ServletException { System.out.println("2 init Initialization method"); // 1,Can get Servlet Program alias servlet-name Value of System.out.println("HelloServlet The alias of the program is:" + servletConfig.getServletName()); // 2,Get initialization parameters init-param System.out.println("Initialization parameters username The value of is;" + servletConfig.getInitParameter("username")); System.out.println("Initialization parameters url The value of is;" + servletConfig.getInitParameter("url")); // 3,obtain ServletContext object System.out.println(servletConfig.getServletContext()); }
three point five ServletContext class
1. What is ServletContext
1. ServletContext is an interface that represents a Servlet context object
2. A web project has only one ServletContext object instance.
3. The ServletContext object is a domain object.
4. ServletContext is created when the web project deployment starts. Destroy when the web project stops.
What is a domain object?
A domain object is an object that can access data like a Map. It is called a domain object.
The domain here refers to the operation range of accessing data, the whole web project.
Save data Fetch data Delete / delete data
Map put() get() remove()
Domain object setAttribute() getAttribute() removeAttribute();
2. Four functions of ServletContext
1. Get the context parameter context param configured in web.xml
2. Get the current project path, format: / Project path
3. Get the absolute path on the server hard disk after project deployment
4. Access data like Map
ServletContext demo code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1,obtain web.xml Context parameters configured in context-param ServletContext context = getServletConfig().getServletContext(); String username = context.getInitParameter("username"); System.out.println("context-param parameter username The value of is:" + username); System.out.println("context-param parameter password The value of is:" + context.getInitParameter("password")); // 2,Get the current project path, format: /Engineering path System.out.println( "Current project path:" + context.getContextPath() ); // 3,Get the absolute path on the server hard disk after project deployment /** * / The slash is resolved by the server to: http://ip:port/ Project name / web Directory mapped to IDEA code < br / > */ System.out.println("The project deployment path is:" + context.getRealPath("/")); System.out.println("Under engineering css The absolute path to the directory is:" + context.getRealPath("/css")); System.out.println("Under engineering imgs Catalog 1.jpg The absolute path is:" + context.getRealPath("/imgs/1.jpg")); }
Configuration in web.xml:
<!--context-param Is a context parameter(It belongs to the whole web engineering)--> <context-param> <param-name>username</param-name> <param-value>context</param-value> </context-param> <!--context-param Is a context parameter(It belongs to the whole web engineering)--> <context-param> <param-name>password</param-name> <param-value>root</param-value> </context-param> ServletContext image Map Same access data: ContextServlet1 code: public class ContextServlet1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get ServletContext object ServletContext context = getServletContext(); System.out.println(context); System.out.println("Before saving: Context1 obtain key1 The value of is:"+ context.getAttribute("key1")); context.setAttribute("key1", "value1"); System.out.println("Context1 Get domain data from key1 The value of is:"+ context.getAttribute("key1")); } } ContextServlet2 code: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); System.out.println(context); System.out.println("Context2 Get domain data from key1 The value of is:"+ context.getAttribute("key1")); }
3.6 HTTP protocol
1. What is Http protocol
Agreement refers to the rules agreed by both parties or multiple parties and everyone needs to abide by, which is called agreement.
The so-called HTTP protocol refers to the rules that need to be observed for the data sent during the communication between the client and the server, which is called HTTP protocol. Data in HTTP protocol is also called message.
2.Http protocol format
The client sends a data request to the server.
The server sends back data to the client for response.
Requests are divided into GET requests and POST requests
- GET request
1. Request line
(1) The method of the request is GET
(2) Requested resource path [+? + request parameters]
(3) Version number of the requested protocol HTTP/1.1
2. Request header
Key: value consists of different key value pairs, indicating different meanings.
- POST request
1. Request line
(1) Request mode POST
(2) Requested resource path [+? + request parameters]
(3) Version number of the requested Protocol HTTP/1.1
2. Request header
1) key : value
Different request headers have different meanings
Blank line
3. The request body = = = > > > is the data sent to the server
- Description of common request headers
Accept: indicates the data type that the client can receive
Accpet language: indicates the language type that the client can receive
User agent: represents the information of the client browser
Host: indicates the server ip and port number at the time of the request
- Which are GET requests and which are POST requests
What are the GET requests:
1. form tag method=get
2. a label
3. link tag introduces css
4. Script tag import js file
5. img tag import picture
6. iframe introduces html pages
7. Enter the address in the browser address bar and press enter
What are the POST requests:
- form label method=post
The HTTP protocol format of the response
1. Response line
(1) The protocol and version number of the response
(2) Response status code
(3) Response state descriptor
2. Response header
(1) key : value
Different response headers have different meanings
Blank line
3. Responder
---->>>Is the data returned to the client
3. Description of common response codes
200 indicates that the request was successful
302 indicates request redirection (tomorrow)
404 indicates that the request server has received it, but the data you want does not exist (the request address is wrong)
500 indicates that the server has received the request, but the server has an internal error (code error)
4.MIME type description
MIME is the data type in the HTTP protocol.
The full English name of mime is "Multipurpose Internet Mail Extensions" multifunctional Internet mail extension service. The format of MIME type is "large type / small type" and corresponds to the extension of a file.
Common MIME types:
How does Google browser view the HTTP protocol
3.6 Request&Response
1. Role of HttpServletRequest class
Every time a Request enters the Tomcat server, the Tomcat server parses and encapsulates the requested HTTP protocol information into the Request object. Then it is passed to the service methods (doGet and doPost) for us to use. We can get the information of all requests through the HttpServletRequest object.
2. Common methods of HttpServletRequest
i. getRequestURI() Gets the requested resource path
ii. getRequestURL() gets the uniform resource locator (absolute path) of the request
iii. getRemoteHost() gets the ip address of the client
iv. getHeader() get request header
v. getParameter() gets the parameters of the request
vi. getParameterValues() gets the requested parameters (used when multiple values are used)
vii. getMethod() GET or POST the request
viii. setAttribute(key, value); Set domain data
ix. getAttribute(key); Get domain data
x. getRequestDispatcher() gets the request forwarding object
Common API sample codes:
public class RequestAPIServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // i.getRequestURI() Gets the requested resource path System.out.println("URI => " + req.getRequestURI()); // ii.getRequestURL() Gets the requested uniform resource locator (absolute path) System.out.println("URL => " + req.getRequestURL());// iii.getRemoteHost() Get client's ip address /** * In IDEA, when using localhost to access, the client ip address is = = > > > 127.0.0.1 < br / > * In IDEA, when accessing with 127.0.0.1, the client ip address is = = > > > 127.0.0.1 < br / > * In IDEA, when using real ip access, the obtained client ip address is = = = > > > real client ip address < br / > */ System.out.println("client ip address => " + req.getRemoteHost()); // iv.getHeader() Get request header System.out.println("Request header User-Agent ==>> " + req.getHeader("User-Agent")); // vii.getMethod() How to get the request GET or POST System.out.println( "Request mode ==>> " + req.getMethod() ); } }
3. How to obtain request parameters
Form:
<body> <form action="http://localhost:8080/07_servlet/parameterServlet" method="get"> user name:<input type="text" name="username"><br/> password:<input type="password" name="password"><br/> hobby:<input type="checkbox" name="hobby" value="cpp">C++ <input type="checkbox" name="hobby" value="java">Java <input type="checkbox" name="hobby" value="js">JavaScript<br/> <input type="submit"> </form> </body>
Java code:
public class ParameterServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Get request parameters String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobby = req.getParameterValues("hobby"); System.out.println("user name:" + username); System.out.println("password:" + password); System.out.println("hobby:" + Arrays.asList(hobby));} }
4. Garbled code solution
1. doGet garbled code
// Get request parameters String username = req.getParameter("username"); //1 code with iso8859-1 first //2 and then decode with utf-8 username = new String(username.getBytes("iso-8859-1"), "UTF-8");
2. doPost garbled code
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Set the character set of the request body to UTF-8, so as to solve the Chinese garbled code problem of the post request req.setCharacterEncoding("UTF-8"); System.out.println("-------------doPost------------"); // Get request parameters String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobby = req.getParameterValues("hobby"); System.out.println("user name:" + username); System.out.println("password:" + password); System.out.println("hobby:" + Arrays.asList(hobby)); }