javaweb02-jsp Data interaction

Source: Internet
Author: User

01. Page Encoding Format

The 001.jsp page itself is encoded in the Pageencoding property of the pages Directive!
002. The encoding ContentType property used by the browser rendering page
003. The encoding (request) used by the server to save data defaults to Iso-8859-1

Attention:
01.--the first two (Pageencoding/contenttype), once specified one, and the other if not specified by default with the specified encoding!
--request.setcharacterencoding (String charset) is used to format the data stored within the request! (Not including url! )
The difference between 02.contentType and pageencoding:
ContentType defines a resource type for a response, or a character set that contains a JSP page and response content;
pageencoding Specifies the character set of the JSP file and the default ContentType character set!

02.JSP of nine built-in objects!
An instance of the Out:jspwriter class!
Common methods: 01.void print (Object); = = "Output various types!"
02.void println (Object); = = "Output various types!"
03.void write (charset); = = "Output character type!" Cannot print null String str=null!
Response: most commonly used redirects! void Sendredirect (String location)

Session: Conversation! (an instance of the HttpSession class)
The browser communicates with the Web server using the HTTP protocol!
The HTTP protocol is a stateless access protocol based on request/Response mode!
"Stateless" means that every HTTP request is independent! The server does not save previous requests and sessions!
Therefore, when a client sends a request to a Web server, whether it is a first visit or not, the server will be the first time he visits!
As a server, there must be a mechanism to uniquely identify each requesting user (or not to be sure that each operation is the same user!). ), while recording the user's status information! = = "Session tracking mechanism!"
This mechanism can save session information for each requesting user!

The term "session" refers to the beginning and ends of a series of actions!
Session Execution Process:
01. Session mechanism is a server-side mechanism! When a user sends a request to the server for the first time, the server creates a unique session for that user, and the session continues until the end of the user's visit!
02. When the server receives a client request, the server will first determine if a session is created for that client!
If created, associate the request with this session! Instead, create a new session!
03. The server side has created a related session, is through a unique identity sessionid to achieve!
If a SessionID is included in the client's request. The previous session has already been created for the client!
The server reads the previous session object according to this SessionID!
Otherwise, create a new Session object and generate a sessionid!
And SessionID in this response "back to the client save"! (SessionID is saved in the client cookie!) )

SessionID will return to the client, so where is the client SessionID saved??
Save the information on the client using a cookie, in the cookie, the name of the saved SessionID is jeseeionid! (consists of a string of complex strings!) )

Session and browser window:
A new window opens with a hyperlink, and the new window is the same as the SessionID of its parent window!
(currently with Google/ie8 above the browser, multiple windows for the same sessionid! Share the same cache! Save in a local cookie! )

Expiration of Session:
01. Session Timeout: The time interval of two requests exceeds the maximum allowed time interval for the server!
001. Set the session's "Inactive Time" by Setmaxinactioninterval (unit seconds) of the Session Object! (The browser finally accesses the server to start computing!) )
002. Set it in the project's Web. Xml!
<session-config>
&LT;SESSION-TIMEOUT&GT;10 (units per minute) </session-timeout>
</session-config>
003. Set in Web. XML in the application server!

A concept is introduced here:
Web. XML in Project Web. XML and Tomcat server
01.tomcat-web.xml + Project-web.xml = merged xml
02. If duplicate configuration appears in both of the items, the priority in the project! (Nearest principle)
Global configuration in the 03.TOMCAT server! The project is local! Valid only for this project!

02. Manually invoke the method to invalidate it
Session.invalidate (): Set Session object to expire! Mainly applied to the user logoff login function!
If you want to empty only one of the data objects in the session, use Session.removeattribute (String key)! The session is still valid!

Note: The value of Session.setattribute (String key,object value) is of type Object and get is required to be transformed downward!


Request: Encapsulate the URL and data as request requests!
The problem with Chinese garbled in the request:
A. Post Request method: Tomcat uses ISO-8859-1 encoding for request data by default!
Request.setcharacterencoding ("Utf-8"); On the page
The encoding of the page itself is not the same as the request code! <% @page contenttype= "Text/html;charset=utf-8"%>
A. Get Request method:
Because of the GET request, the submitted data is appended to the end of the URL as a query string to the server!
For this part of the data, use Request.set. It's not working!
Workaround 1:
Get the requested parameters after encoding the conversion!
String name = Request.setparameter ("name");
name = new String (name.getbytes ("iso-8859-1"), "Utf-8");
where GetBytes () converts the name to a byte array according to the ISO-8859-1 encoding format!
Creates a new string! for a byte array dog by using the specified utf-8 with new String ()
Workaround 2:
In mode 1, if there are more than one parameter, you have to operate on each parameter! Cumbersome, not high efficiency!
You can \conf\server.xml files through the Tomcat directory structure
Settings <Connector> nodes!
<connector port= "8080" protocol= "http/1.1"
connectiontimeout= "20000" redirectport= "8443"
uriencoding= "UTF-8"/>

Application: A global variable similar to the system! Data sharing among all users in the same app!
Common method: String getrealpath (); Returns the true path of the relative path!
E:\apache-tomcat-7.0.73\webapps\ ...
Often applied to statistics visitors!
Integer count = (integer) application.getattribute ("Count");
if (count! = null) {
Count = count+1;
}else{
Count = 1;
}
Application.setattribute ("Count", count);

Page: Object instantiated by current JSP page (this)
The difference between the following two include is explained here:
01.include command:
<% @include file= "**.jsp"%>
For example a.jsp include b.jsp
Process:
Will a.jsp+b.jsp= c.jsp (after merging generates C.JSP) C is we simulate, actually no c.jsp file!
c.jsp--c.java--c.calss--Execution!
So say two pagecontext in the same scope!
02.pagecontext.include ("**.jsp");
For example a.jsp include b.jsp
Process:
01. Perform b.jsp--b.java--b.class--execution first! --get result C (NULL)
02. Merge result C (null) and a.jsp into a new c.jsp! --c.java--c.class--Execution! --Get results
So say two PageContext in a and b two scopes!
a.jsp page:
String name = "Haha";
Pagecontext.setattribute ("name", name);
Content in a: <%=pagecontext.getattribute ("name")%>
<%=pagecontext.include ("b.jsp")%>//introduction of page B in page a
b.jsp page:
Content in B: <%=pagecontext.getattribute ("name")%>

Run a.jsp to get the result: haha null

Config: Specifies the JSP page initialization configuration (the servlet will use!). )

Exception: Exceptions are generally handled with Java code! This object is seldom used!
The object is only used in pages that are set Iserrorpage to true in the page directive!

PageContext: The synthesizer of built-in objects! 8 additional built-in objects can be obtained through PageContext! Pagecontext.getrequest () ...
Object GetAttribute ();//Return object type value Value!
void include ();//request the specified resource and include the response result of the target resource in the response of the calling page!

Does the JSP built-in object need not be instantiated?
The so-called built-in object is a set of SERVLETAPI instances that are loaded by the Web container, which is initialized by default by the JSP specification! (In _jsp.java!) )
Built-in object names are reserved words for JSP!

03.JSP four-scope
A page that corresponds to the operation of a JSP
Request: Once requests
Session: Within the period of validity
Application: The entire application context

Scope: Application > Session > Request > Page


04. Forwarding and redirection!
Forwarding process:
Within the Web container, the process of requesting a request is given to another resource, which belongs to the same request/response procedure! The Request object information is not lost!
Forwarding is a function on the server side! The submission information is passed across multiple pages through the forward () of the RequestDispatcher object.
Forwarding is the transfer of control within the server! The client browser address bar does not show the forwarding address! (You can share the data in the request!) )
REDIRECT process:
The Web container returns a response to the browser, and the browser receives the response before sending a new HTTP request to the server (two different requests!). The information for the request object will be lost for the first time! )
Redirection is what works on the client! By requesting a new address to implement the page jump! (The browser re-requests the address!) The Address bar shows the post-turn address! )

Note: If you want to pass a small number of parameters under redirection, you can append the parameter to the end of the URL!
Response.sendredirect ("welcome.jsp?username=" +name+ "&pwd=" +pwd);

When using hyperlinks <a> data passing, the Get method is used!
(in addition to specifying post in the form and Ajax specifying post, the other case is to submit the request by a GET method by default!) )

05.include Instructions!
Use the include directive to reference common code files to alleviate code redundancy issues!
<% @include file= "file path"%>
01. Insert a file that contains text or code during the JSP compilation phase, and the process is static! (can include JSP HTML text file, etc...) )
The 02.include directive has only one attribute file! The file path that is included!

06.cookie
Cookies, invented by Netscape, are the most common way to track user sessions!
is generated by the server side and sent to the client browser! The browser will save it in a directory of text files!

Application Scenarios:
01. Determine if the user registered user is logged in, save the information for the next easy login!
02. Recently Viewed Items
03. Statistics Website views
04. Realize personalized service, show different content for user preferences

Attention:
Cookies Store user information on the client, and there is a risk of cookies on security! It is not recommended to keep sensitive information in cookies!

01. Create a cookie
Cookie cookie = new Cookie (String name,string value);
02. Write a cookie
Response.addcookie (cookie);
03. Read Cookies
cookie[] cookies = request.getcookies ();//The method returns an array of Coookie in the HTTP request!

Iterate through this array, get through GetName () and GetValue ()!

04. Verify that SessionID is stored as a cookie in the client!
Create a session
Session.setattribute ("str", "haha");
Response.sendredirect ("getcookie.jsp");
If you are forwarding here, you will not get the jsessionid! in the cookie
Because forwarding is a request, the client does not get a response! Therefore, no cookie! is written to the client

Get in getcookie.jsp
Out.print ("sessionid=" +session.getid ());
cookie[] cookies = request.getcookies ();
if (cookies!=null) {
for (Cookie cookie:cookies) {
Out.print ("Cookiename=" +cookie.getname ())
Out.print ("cookievalue=" +cookie.getvalue ());
}
}

Get the results SessionID and cookievalue the same value!

Expiration date of 05.cookie
Cookies are life-cycle!
Cookie.setmaxage (int expiry); In seconds!

Attention:
Setting expiry=0 means that the cookie! is removed from the client
If set expiry is negative/not set then the cookie will expire after the current window is closed!

07.cookie and Session

Session scope is to save the user information on the server side, the cookie is on the client!
The value saved in the session scope is the OBEJCT type, and the value stored by the cookie is of type string!
The session scope destroys the data it stores with the end of the conversation, and the cookie can be stored on the client for a long time!
The session usually holds important information, and cookies usually keep unimportant information!

For example, save user login/password cannot use cookie!
The "Recently viewed items" in the e-commerce website can be saved with a cookie!


















javaweb02-jsp Data interaction

Related Article

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.