Two main lines of servlet technology
1. HTTP protocol
2. servlet life cycle
The init () method in the parameter ServletConfig object uses
Get ServletContext objects using ServletConfig
The service method consists of two parameter objects ServletRequest Servletresponse
There is no need to overwrite the service----in the actual development of the servlet HttpServlet automatically calls Doget or DoPost as requested
Doget and Dopost parameters HttpServletRequest and HttpServletResponse
Today's study highlights: HttpServletRequest HttpServletResponse
The request object and the response object are created each time the client requests------be passed Service/doget/dopost
HttpServletRequest encapsulates client-side information that server servlet programs can manipulate client information through the Request object
HttpServletResponse Encapsulation Server sends response data information to the client, and the Servlet program sends a response to the client through the response object
Response Common API
setStatus Setting the status code in the response profession
SetHeader Setting the response header information
getoutputstream get byte stream ----Output response body content
getwriter get character stream ----output response body content
* HttpServletResponse inherits Servletresponse interface, Servletresponse does not provide API related to HTTP protocol, HttpServletResponse adds protocol related API
* The Java EE API does not provide a HttpServletResponse implementation class----implementation class provided by the Tomcat server
Common status Code: 200 302 304 404 500
success of request processing
302 Client redirection
304 Client Access resource is not modified, client accesses local cache
404 Access resource does not exist
Internal Error in server
Case one: Using 302 + Location header information to achieve page redirection effect
Response.setstatus (302);
Response.setheader ("Location", "/day06/welcome.html"); Relative path and absolute path
* /Directed by client server, on behalf of client /, must add engineering virtual directory
1 Public voiddoget (httpservletrequest request, httpservletresponse response)2 throwsservletexception, IOException {3ServletContext sc =Getservletcontext ();4 intTime= (Integer) Sc.getattribute ("Times");5time++;6Sc.setattribute ("Times", time);7System.out.println ("Visited:" +time+ "Times");8Response.setstatus (302);9 //The conut here is the access virtual path set in Web. XMLTenResponse.setheader ("Location", "/day03/count"); One}
to set up client request redirection, you must add the project virtual directory
Header information has multiple values
Accept-encoding:gzip, deflate---key:value1,value2
Response. AddHeader is used to set the response header to have multiple values------infrequently used
Focus: SetHeader
Provide sendredirect----Complete 302+location redirection effect in the response API
For example: Response.sendredirect ("/day06/welcome.html");
Case Two: Login redirect
Case three: Automatically refresh the Web page
* Login successful, after 5 seconds automatically jump XX page
Principle: Through the Refresh header information
Format-----Refresh: time; url= Jump Path
For example: refresh:3;url=http://www.itcast.cn--------automatically jump to http://www.itcast.cn website after 3 seconds
* There is a class of very special tags in the HTML page <meta>,<meta> to set the header information function
<meta content= "3;url=/day06/response/demo3/result.html" http-equiv= "Refresh" >----Complete automatic jump
Case FOUR: Setting browser disable cache via response header information
Principle: and Disable cache related header information three
Cache-control:no-cache
Expires:thu, 1994 16:00:00 GMT-----Setdateheader ("Expires",-1);
Pragma:no-cache
IE Tools---Internet Options---general---settings---viewing files
For servlet-generated HTML pages, changes are often required to disallow servlet dynamic program caching
* When setting expires, it is usually setdateheader to set a millisecond value for the expiration time, and when the HTTP response is generated, the date string representation is automatically converted
---------------------------------------------------------------
The client response body is generated through the response, with two output modes of byte stream and character stream.
* What is the use of the word stream? Which cases use character streams?
File copy----byte stream
Parse the contents of a file---character stream (Chinese action character stream)
Case FIVE: Output Chinese information
Encode the information in Chinese
Response.setcharacterencoding ("Utf-8");
Response.setcontenttype ("Text/html;charset=utf-8");
The difference between Setcharacterencodig and setcontenttype?
Conclusion: Only the use of setContentType can be used in development.
Attention:
1, Getoutputstream and getwriter cannot be used simultaneously
2. The response encoding must be set before Getoutputstream and Getwriter
3, Getoutputstream and getwriter output is the HTTP response body
4, Getoutputstream and getwriter exist in the buffer, at the end of the service method, automatically close the stream, flush buffer contents
Case six File download
First: Complete file download with hyperlinks
* If the browser can recognize the file format, open directly, only the link file browser does not recognize the file format, will be implemented to download
The second type: Download through the servlet program
Principle: Read the target program through the servlet and return the resource to the client
Set two header information by program download file Content-type content-disposition
Response.setcontenttype (Getservletcontext (). GetMimeType (filename)); ----Setting File types
Response.setheader ("Content-disposition", "attachment;filename=" + filename); ----settings files are downloaded as attachments (for browser-aware format files)
Case seven verification Code output case
Java Graphics API Generate CAPTCHA Image-----Understand
Why do I need a verification code? Prevent someone from malicious attacks on the website through the program
Why is the verification code a picture? Why snowflakes or interference lines?
Common verification Code: letters and Numbers
Verification Code Rotation effect
Rotate (double theta, double x, double y)-----parameter theta rotational radians
2PI radians = 360 angle
-30----30 Angle
Verification code can not see clearly, click Switch Verification Code----write JavaScript program
Method One: Set the captcha picture not cached
Method Two: Each access makes the URL different-----url?new Date (). GetTime () Current time
-----------------------------------------------------------------
HttpServletRequest is divided into four parts
HttpServletRequest want to add protocol-related APIs than servletrequest
1. Obtaining Client Information
URI and URL differences
Url:http://localhost/day06/request1---Complete
Uri:/day06/request1----part
URI contains URL, url must complete path, URI can be relative path
Http://localhost/day06/request1 is a URL and also a URI
./hello/day06/request1----are URIs, not URLs.
Obtained ip:request.getRemoteAddr ();
Get the current Access resource path: Request.getrequesturi (). substring (Request.getcontextpath (). Length ());
2. Get Request header information
GetHeader gets the value of the header information, converts a string
Getheaders Get header information value, get enumeration
Getheadernames get all header information name return enumeration
* Master GetHeader Use, Traverse enumeration get all header information
Write anti-theft chain program, there is a legitimate referer is not hotlinking, otherwise control the target resources can not be accessed!
* Judge by URL bypass hotlinking
3. Get Request Parameters
What is a request parameter? The user submits the server some data by request-----<a href= "url?xxx=xxx" >, <form method= "Get" >, <form method= "POST" >
/day06/request4?name=zhangsan&city=beijing----includes two parameters for name and city
Common API Four
GetParameter
Getparametervalues
Getparameternames
Getparametermap
Non-null check
if (username! = null && Username.trim (). Length () > 0) {}-----Short Circuit
Garbled problem
Post----request.setcharacterencoding ("Client encoding set");
Get garbled manual fix
Username = Urlencoder.encode (username, "iso-8859-1");//ISO-coded
Username = Urldecoder.decode (username, "utf-8"); Decode with Utf-8
Simplify the notation above: username = new String (username.getbytes ("iso-8859-1"), "Utf-8");
Get garbled configuration tomcat default decoding character set
In Tomcat/conf/server.xml
Add an attribute uriencoding= "Utf-8" in connector
Conclusion: When developing, try not to modify the tomcat default decoding set, submit the request please use post, if not to use GET, manual encoding
Question: Http://localhost/day06/servlet?username=zhangsan+lisi
On the server side through Request.getparameter ("username") The result is??? -----Zhangsan Lisi
4. Passing objects using the request domain
HttpServletRequest and ServletContext are similar to data domain objects, keeping data in map mode
Distinction: Survival Time is different
ServletContext Object Server startup object creation, server stop object destruction
The ServletRequest object is created when a request is made, and when the response is finished, the object is destroyed
Requests are forwarded by request, requesting that data be saved for delivery between servlets----application?
Servlet data Processing---generated results---forwarded results to the JSP display
Precautions
1. The response content cannot be transmitted to the client until the forward is used
Situation one response output stream execution flush
Situation two the same servlet cannot continuously use forward and redirect
2. When forward and redirect are executed, the response stream data is written before the purge
3, ServletContext forwarding path must/start, request forwarding path can use relative path
Forwarding and redirection differences
1. Forward one request, one response redirect two requests two responses
2, forwarding can only jump in the station program, redirect to any site
3, forwarding URL address is unchanged, redirect URL address change
4. Forwarding is not visible to the client, and redirection is visible to the client
5, forwarding share the same request data, redirect two requests, different request object, cannot share the request data
* Request.setattribute must be used with Request.getrequestdispatcher (). Forward
RequestDispatcher's include method is used to make page layouts------<% @include%> <jsp:include>
Extract the common parts of the page,----easier to maintain by using the include reference to the page
Summarize:
1, Response four must API setStatus setheader getoutputstream getwriter
SetStatus Status Code
SetHeader Header Information
Getoutputstream getwriter Response Body
2. REDIRECT 302 + location----Shorthand Sendredirect
Case User Login Redirection
3. Refresh the webpage automatically
<meta> Label Use
4. Disable browser cache three header fields
5, in response to Chinese garbled----use setContentType
6. File download hyperlink and servlet program
Servlet program set two header fields Content-type content-disposition
7. Verification Code Program (write full archive)
* Two methods of verification code click Switch
8. Request line related API Getrequesturi Getcontextpath getremoteaddr GetMethod
Thinking: Getting access to a resource path
9. Request header information obtained (not important)----grasp the case of anti-theft chain
10, get the request parameter garbled solve GET, post (Super important)
11. Forward shared request data, include for page layout----understand
The path of the Java Siege Architect--Review the Java Web Request_respone