Servlet in-depth service response response

Source: Internet
Author: User

HttpServletResponse and HttpServletRequest
When the Web server receives a cry justifying HTTP request, it creates a request object and a response object representing the response for each request, and obtains the data submitted by the client, and only needs to find the request object. To output data to the client only need to find the Response object, HTTP request, the corresponding object is HttpServletRequest encapsulation request data, HTTP response time corresponding to the object is the HttpServletResponse package response data.

HttpServletResponse interface
Common API Methods
SetStatus (int sc) Set status code
SetHeader (String name,string value) Setting header information
AddHeader (String name,string value) uses this method to add a value when there are multiple values in the head message.
Getwriter ();//get character write stream
Getoutreponse ();//Gets the byte output stream.
These four methods can generate all the content of the response header information
To know that there are no implementation classes in Java EE that provide both interfaces, these implementation classes are done on the server. It can be seen from here that the object-oriented programming of the external environment such as the framework should be oriented to the interface programming transformation.

The implementation of redirection function
Two methods
1. Change the response header information status and location by traditional means
Response.setstatus (302);
Response.setheader ("location", url) URL is an absolute path and you want to include the root directory
2, use the encapsulated method Sendredirect
Response.sendredirect (URL)

Implementation of automatic refresh
Refresh by changing the response header information
Response.setheader ("Refresh", Time,url);

Note that there is a <meta> tag in the HTML to simulate the header information
The name attribute specifies the contents of the keyword, content-specific keyword. Before Baidu keyword search is through the designation of keywords, by picking keywords to determine the page information, but this way can be used to specify keywords so the information is often incorrect, now is the beginning to pick up the overall page of data to search the keywords.
The Http-equiv property specifies the protocol state impersonation information header, content specified time, and URL specifies the protocol access address. This is generally used to automatically jump Web pages.

Disallow browser Cache Implementation
Cache is stored in the browser's temporary files, the disadvantage of local cache is that the servlet dynamic programming often need to change the Web page, if the browser has a cache, is the priority to access the cache, so that the real-time dynamic updates can not be done
expires:-1//set expiration time, 1 is forbidden cache, normal date format is cache valid time
Cache-control:nocache
program:nocache//These three are used together to control whether the client is cached, and for dynamic resources should disallow caching. The third sentence is to solve the browser compatibility problem.

Response output Stream character encoding problem
1, gets the output stream object
OutputStream out=response. Getoutputstream (); byte stream
PrintWriter pw=response.getwriter (); character Stream
2. Specifies the type of the body content
setContentType ("text/html ; Charset=utf-8 ");
3, specifying the encoding format of the output data
setcharacterencoding ("");//This method differs from the above method in that the method can only set the encoding of the response content but cannot set the browser's view encoding, the method above is to set the browser to view the encoded, Because this method cannot be encapsulated in the header information, ContentType is encapsulated in the response header information, and the Setcharaterencoding method is no longer used after the setContentType method is used in development.
The encoding format is iso-8859-1 by default;
It is important to note that 2 and 3 must be written before 1 gets the stream object, encapsulating the encoding into the stream. Getoutputstream and Getwriter are buffered, and the stream is automatically closed at the end of the service method, Flsuh buffering the content.

Implement response File Download
content-type:text/html,charsetgb2132---response data type, the response data type uses the MIME protocol to specify the default type of HTML file, which can be viewed in tomcat/conf/web.xml
Related response header information, content-disposition:attachment;filename=aaa.zip; Specify file attachment name----file download
Two ways to implement downloads
First: Complete file download with hyperlinks
Direct hyperlinks in HTML Specify the file path, this way if the browser can recognize the file, is directly open the file is not downloaded, only the unrecognized file format will be downloaded
The second type: through the servlet program
1. Hyperlinks to the servlet program, with the file parameter information included with the
<a href= "Url?filename" >
2. Get the file name via request
String filename=request.getparameter ("filename");
3. Set header information Specifies that the file type//notation is basically fixed.
Response.setcontenttype (Getservletcontext (). GetMimeType (filename));
Response.setheader ("Content-dispositon", "attachment;filename=" +filename);
4. Absolute disk Path Read file
String Realfilename=getservletcontext (). Getrealpath ("root directory +filename");
InputStream in=new FileInputStream (realfilename);
OutputStream Out=response.getoutputstream ();
int b;
while ((B=in.read ())!=-1) {
Out.write (b);
}
In.close ()
Out.close ()//This response stream is auto-off and can not be written

Implement verification Code output case
Generate a Captcha picture from the Java graphics API
Create an in-memory buffered picture
Image is the class in Java for manipulating graphics.
Width,height is a pixel, imagetype is a picture type, a static field encapsulated inside an image
BufferedImage bufferedimage=new BufferedImage (width,height,imagetype);
background color; The process of drawing is actually the process of coloring. The default initial background color is black.
The wrapper class for the graphics drawing brush
Graphics Graphics=bufferedimage.getgraphics ();
Graphics.setcolor (Color.yellow);//Set Brush color
Graphics.fillrect (0,0,width,height)//fill rectangle, parameter is a coordinate of four directions
Graphics.setcolor (Color.Blue);
Graphics.drawrect (0,0,widt-1,height-1); draw a rectangular border
Write Verification Content
String content= "ABCDEFGHIJK1234567890"
Graphics.setcolor (color.red);
Graphics.setfont (New Font (name,style,size));
Randomly extracting the captcha from the content
Random random=new random ();
for (int i=0;i<4,i++) {
int Index=random.nextint (Content.length ());
Char Letter=content.charat (index);
Graphics.DrawString (letter+ "", X, y);
X+=30
}
Draw random line of interference, need coordinates of two points
Graphics.setcolor (Color.light_gray);
int x1,x2,y1,y2;
for (int i=0,i<20;i++) {
X1=random.nextint (width);
X2=random.nextint (width);
Y1=random.nexint (height);
Y2=random.nextint (height);
Graphics.drawline (X1,Y1,X2,Y2);
}
Frees the in-memory graphics resource.
Graphics.dispose ();
Writes the output stream in the response stream via the picture IO stream and generates a JPG-formatted picture
Imageio.write (bufferedimage, "JPG", response.getoutputstream);
It is then configured in the HTML file
In Changing the Style property, the mouse will turn into a finger.
<script>
function Change () {
document.getElementById (). src= "Servleturl?" +new Date (). GetTime ()//reload path, remember to disallow caching. Adding the current time behind the path is also a way to resolve the caching problem.
}
</script>

Servlet in-depth service response response

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.