Organizing Notes--web Basics

Source: Internet
Author: User
Tags connection pooling session id server memory

c/S is a client/server, b/S is a browser/server.

IPv4 192.168 ..... (intranet IP) through the router's NAT (maintains a table, used to convert IP corresponding to the extranet).

When the IPv6 is promoted, no routers are used.

Communication principle:

Write IP address access is too troublesome, so there is a domain name, it will first visit the local hosts, no network access to the DNS server, the DNS server will help us to find the target server, and then return the corresponding IP address.

Virtual Host (multiple host names can be run on a single server (or a server group), and each single host name can be supported separately),

Web. XML was put in Web-inf in order to have access to the virtual host.

Servlet

Life cycle:

Any method in the servlet life cycle is not invoked when the server is started.
When the servlet is first accessed, the constructor is called first, followed by the Init () method, which is called only once, followed by the service () method.
If the servlet is again accessed, each access server will open a new thread and invoke the service () method.
The Destroy () method is called when the server restarts or gracefully shuts down (shutdown.bat).
The Servlet object is created by Tomcat, and each request invokes the service () method, and the Tomcat server creates a request object and a response object for the method each time the service () method is invoked.
In the HttpServlet code implementation, depending on how the request is requested, the corresponding Doxxx method is called, such as a Get method request to call the Doget () method, which calls the Dopost () method.

Add:

<!--servlet initializes with server--><load-on-startup>1

Cookie (key-value form) principle:

The effective time of the cookie:

Cookie.setmaxage (value): -1, default, indicates that only the browser memory is alive.   for one hour.  0, the Representative is void. Cookie.setpath ("/"): Sets the path.

The life cycle of a cookie:

Cookie cookie =new cookie ("name""value") Create

Destroyed:
1. Session cookies are destroyed when the browser is closed.

2. Persistent cookies are destroyed when the cookie expires.

Session principle:

When the session is first used, the server side to create the session,session is saved on the server side, and to the client is the session ID (a cookie saved SessionID). The client takes away the SessionID, and the data is stored in the session.
When the client accesses the server again, the SessionID is brought in the request, and the server finds the corresponding session through SessionID without having to create a new session.

The session life cycle:

Request.getsession ();/// Create

Destroyed:
1. Destroy the server when it shuts down.
2.Session is destroyed when it expires.
3. Call Httpsession.invalidate ().

To set the session Expiration time:
1. Configure Web. XML:

<session-config> <!--units are minutes--><session-timeout><session-timeout></ Session-config>

2. Call Session.setmaxinactiveinterval (int interval), in seconds.
3. Manually call Session.invalidate ().

ServletContext
Life cycle: Created at server startup, server shutdown destroyed, all servlet shares save global data.
Purpose: Database connection pool, engineering configuration properties, configuration file contents.

A. Forwarding and redirection:

Forwarding (Java-specific):

1. If the server requires multiple server programs to process at the same time when processing a client request, use forwarding is required.

2. Servletcontext.getrequestdispatcher (String path): Specifies the forwarding path. 3.requestdispatcher.forward (servletrequest request, servletresponse response): Forwards the parameters for subsequent operation.

Redirect: After the server receives the request, notifies the client that it needs access to the next target program for subsequent processing.

Difference:

1. Forwarding produces a single request response, and redirects generate two requests two responses.
2. Forwarding can only jump in the station resources, redirect any site resources.
3. The forwarding URL address is unchanged and the redirect URL address is changed.
4. Forwarding is not visible to the client, and redirection is visible to the client.
5. Forwarding shares data in the same request, redirects generate two requests, two different request objects, and cannot share the request data.

B. Get the Web App resource file:

1. In a Web application, you must obtain the file through an absolute disk path. If the file is in the/web-inf/classes directory (the src file is stored in the/web-inf/classes directory), you can also get it through the class loader
Clazz.getresource ("/File"). GetFile ();

2. Servletcontext.getrealpath (string path): Gets the absolute disk path of the resource in the Web App, and the String path parameter represents the relative path.

C. Get parameters:

1.getServletConfig ()-and initialization parameters. 2.getServletContext ()--Global parameters.

D. Data sharing

1. Servletcontext.setattribute (String name, Object object): holds a global parameter. 2.servletcontext.getattribute (String name): Gets the value of a global parameter.

HttpSession
Life cycle: Created when accessing programs such as Jsp/servlet.
Usage: System login information, Shopping cart data

The same client machine requests the same resource multiple times, is it the same as the session?

For multi-tabbed browsers (such as 360 browsers), in a browser window, multiple tabs simultaneously access a page, the session is a. For multiple browser windows, at the same time or a short distance to access a page, the session is multiple, and the browser process. The session is the same for a single browser window that accesses different resources of the same application directly into the URL.

Use session after disabling cookies:

API:response.encodeURL
Attention:
If the server makes URL rewriting, all paths must be rewritten,
Do not allow users to disable cookies in real-world development.

Example:

protected voiddoget (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException {HttpSession Session=request.getsession (); Session.setattribute ("name","Zhangsan"); Response.setcontenttype ("Text/html;charset=utf-8"); Response.getwriter (). Write ("Write Success"); String URL="/logindemo/getsession";//rewrite URLString Encodeurl =response.encodeurl (URL); Response.getwriter (). Write ("<a href= '"+ Encodeurl +"' > View data </a>");}

HttpServletRequest
Life cycle: When a client initiates a request, the server creates the object, and at the end of the response, the object destroys the save servlet transmits the data information to the JSP, and the servlet passes the result of the operation to the JSP.

Purpose: Login error message

A. Forwarding:

Getrequestdispatcher (Path). Forward (Request,response)

And the difference between ServletContext:

1.ServletContext objects are created when the server is started and destroyed when the server shuts down

2.HttpServletRequest objects are created when a request is made and destroyed at the end of the response

B. Hair Problem Solving:

1.POST Request:

Request.setcharacterencoding ("Client code set");

2.GET Request: Re-encode the data using the new String (Name.getbytes ("iso-8859-1"), "Utf-8") constructor

Length of life cycle:

The principle of choice in development: priority to use short life cycle.

HttpServletResponse

About SetHeader (header information):

1. Auto Refresh

Requirements: Complete a similar forum login success, three seconds after the function of opening the homepage.
Realize:
Way One:

// Set Header information

Way two: Using META tags
Meta tags can achieve the same effect as header information

Http-equiv == value of header information

2. Disable caching

Realize:

To set the information header:

"Cache-control", "No-cache" "Pragma", "No-cache" "Expires", "Thu, Dec 1994 16:00:00 GMT"

The following is a simple way to set the time

Setdateheader ("Expires",-1)

Because of the number of browsers on the market, the supported properties are inconsistent, so it is common to set up three information headers at the same time.

3. Download the file

Getservletcontext (). GetMimeType (PATH): Gets the encoding type of the file ("Content-disposition", "attachment;filename=" +  FileName)  //attachment: To download this file as a download  //  filename: Specify the name of the file to download

Output Chinese characters:

setcharacterencoding (): Sets the encoding of the contents of the external output, unable to generate header information setContentType ("Text/html;charset=utf-8"): Sets the encoding of the contents of the external output, Also generate header information to inform the browser to parse the content in the corresponding format

Servlet and Thread Safety:

Because there is only one instance object for a servlet of a type, it is possible to present a servlet that handles multiple requests simultaneously, and the servlet is not thread-safe.
So we should not create member variables arbitrarily in the servlet.

Tomcat FAQs:
1. Memory Overflow
The system popup sets the Tomcat configuration page, appended in the VM arguments in the Add parameter at the end of the argument:

-xms256m-xmx512m-xx:permsize=256m-xx:maxpermsize=512m


The meaning of the parameter

-Vmargs: Description is followed by the parameters of the VM-xms40m: Virtual machine occupies the system's minimum memory -xmx256m: Virtual machine occupies the maximum memory of the system -xx:permsize: Minimum stack memory size. Generally reported insufficient memory, is said that this is too small, heap space remaining less than 5% will be warned, it is recommended to make this slightly larger, but depending on the size of your machine memory to set -xx:maxpermsize: Maximum stack memory size. This is also appropriate larger -xmx512m 5% is 25.6M, theoretically requires-XMX value and-xx:maxpermsize must be greater than 25.6M


2. Command Not start
Right-click Edit Start command to add below the first line

SET java_home=c:\program files\java\jdk1.7. 0_80set tomcat_home=c:\ruan_jian\apache-tomcat-7.0.73


3. Fast startup speed

Servers under the Server.xml 116 line comment out the original

4. Resolving GET Requests
64 rows Tomcat Get garbled filter uriencoding= "Utf-8"

5. Local Tomcat cannot boot maven tomcat to boot (or vice versa)
Change a workspace and reconfigure Tomcat

Connection pool:

Disadvantages of not using connection pooling:

Each time a user requests a link to the database, the database creation connection typically consumes a relatively large amount of resources and is created longer. Assuming that the site 100,000 visits a day, the database server needs to create 100,000 connections, greatly wasting the resources of the database, and it is very easy to cause database server memory overflow, extension machine.

3rd party Connection Pool:

1.DBCP 2.c3p0

Organizing Notes--web Basics

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.