HttpServletResponse Object (ii)

Source: Internet
Author: User

First, HttpServletResponse Common application-Generate verification code 1.1, generate a random image as a verification code

The main use of a BufferedImage class is to generate a picture.

  

Example of generating a random picture:

 PackageGacl.response.study;ImportJava.awt.Color;ImportJava.awt.Font;ImportJava.awt.Graphics2D;ImportJava.awt.image.BufferedImage;Importjava.io.IOException;ImportJava.util.Random;ImportJavax.imageio.ImageIO;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classResponseDemo03extendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setheader ("Refresh", "5");//Set Refresh response header control Browser refresh every 5 seconds//1. Create a picture in memoryBufferedImage image =NewBufferedImage (80, 20, Bufferedimage.type_int_rgb); //2. Get the picture//Graphics g = image.getgraphics ();Graphics2D g =(graphics2d) image.getgraphics (); G.setcolor (color.white);//set the background color of a pictureG.fillrect (0, 0, 80, 20);//Fill Background Color//3. Write the data to the pictureG.setcolor (Color.Blue);//set the color of a font on a pictureG.setfont (NewFont (NULL, Font.Bold, 20)); g.DrawString (Makenum (),0, 20); //4. set the response header to control the browser browser open as a picture         Response.setcontenttype ("Image/jpeg");//equivalent to Response.setheader ("Content-type", "image/jpeg"); //5. Set the response header control browser does not cache picture dataResponse.setdateheader ("Expries", 1); Response.setheader ("Cache-control", "No-cache"); Response.setheader ("Pragma", "No-cache"); //6. Write the picture to the browser        Imageio.write (image, "JPG" , Response.getoutputstream ()); }    /*** Generate random numbers *@return     */    PrivateString Makenum () {random random=NewRandom (); String Num= Random.nextint (9999999) + ""; StringBuffer SB=NewStringBuffer ();  for(inti = 0; I < 7-num.length (); i++) {sb.append ("0"); } num= sb.tostring () +num; returnnum; }         Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

The results of the operation are as follows:

  

Second, HttpServletResponse common application--Setting the response header to control the behavior of the browser2.1. Set HTTP response Header control browserDisable caching of the current document contents
Response.setdateheader ("Expries",-1); Response.setheader ("Cache-control", "No-cache"); Response.setheader ("Pragma", "No-cache");
2.2. Set HTTP response Header control browserRefresh Web pages regularly(refresh)
Response.setheader ("Refresh", "5"); // Set Refresh response header control Browser refresh every 5 seconds
2.3.implementing request redirection via Response

Request redirection means that when a Web resource receives a client request, it notifies the client to access another Web resource, which is called a request redirection.

Application Scenario: User login, the user first access to the login page, login success, will jump to a page, this process is a request redirection process

Implementation:Response.sendredirect (String location), which calls the Sendredirect method of the response object to implement the request redirection
Sendredirect Internal Implementation principle: Use response to set 302 status Code and set location response header for redirection

For example:

 PackageGacl.response.study;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classResponseDemo04extendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {/*** 1. Call the Sendredirect method to implement the request redirection, * The Sendredirect method internally calls the * Response.setheader ("location", "/javaweb         _httpservletresponse_study_20140615/index.jsp ");         * Response.setstatus (Httpservletresponse.sc_found);//Set 302 status code, equivalent to Response.setstatus (302); */response.sendredirect ("/javaweb_httpservletresponse_study_20140615/index.jsp"); //2. Use response to set 302 status code and set location response header to implement redirection for request redirection//Response.setheader ("Location", "/javaweb_httpservletresponse_study_20140615/index.jsp"); //Response.setstatus (httpservletresponse.sc_found);//Set 302 status code, equivalent to Response.setstatus (302);    }     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}
Iii. recommended wording for URL addresses in Web projects

In Javaweb development, as long as the URL address is written, it is advisable to start with "/", that is, the use of absolute path , then what does this "/" represent? You can memorize "/" in the following way:

If the "/" is for the server, it represents the current Web project,

if "/" is used for the browser, it represents the WebApps directory .

3.1. "/" represents a common application scenario for the current Web project

①.Servletcontext.getrealpath (String path) gets the absolute path to the resource

/** * 1.servletcontext.getrealpath ("/download/1.jpg") is used to obtain a resource on the server, * then this "/" is for the server, "/" represents the Web project at this time * Servletcontext.getrealpath ("/download/1.jpg") means reading 1 of the download folder under Web Engineering. JPG This resource * As long as you understand the exact meaning of the "/" representation, you can quickly write down the absolute path of the Web resource to be accessed */This.getservletcontext (). Getrealpath ("/ Download/1.jpg ");

②. forward to other pages on the server side

/** * 2.forward * client requests a Web resource, the server jumps to another Web resource, this forward is also for the server, * then this "/" is for the server, so at this time "/" represents the Web project */ This  . Getservletcontext (). Getrequestdispatcher ("/index.jsp"). Forward (request, response);

③. introducing pages using include directives or <jsp:include> tags

<% @include file= "/JSPFRAGMENTS/HEAD.JSPF"%> <jsp:include page= "/jspfragments/demo.jsp"/>

At this point, "/" stands for Web engineering.

3.2. "/" represents a common application scenario for the WebApps directory

①. using Sendredirect to implement request redirection

Response.sendredirect ("/javaweb_httpservletresponse_study_20140615/index.jsp");

The server sends a URL to the browser, the browser gets the URL address, and then requests the server, so This "/" is for the browser, "/" represents the WebApps directory , "/javaweb _httpservletresponse_study_20140615/index.jsp "This address refers to" webapps\javaweb_httpservletresponse_study_20140615\ Index.jsp "

  Response.sendredirect ("/Project name/folder directory/page"); This kind of writing is to write the project name to die in the procedure , not flexible, in the event of the day when the name of the project changed, the program must be changed, so we recommend the following flexible wording:

Will

Response.sendredirect ("/javaweb_httpservletresponse_study_20140615/index.jsp");

This is changed into

Response.sendredirect (Request.getcontextpath ()+ "/index.jsp");

What Request.getcontextpath () gets is "/javaweb_httpservletresponse_study_20140615", which makes it more flexible, Use Request.getcontextpath () instead of "/project name", it is recommended to use this method, flexible and convenient!

②. using hyperlinks to jump

<a href= "/javaweb_httpservletresponse_study_20140615/index.jsp" > Jump to Home </a>

This is the hyperlink jump used by the client browser, this "/" is used for the browser, at this time "/" represents the WebApps directory .

Using hyperlinks to access Web resources, it is recommended to use the following syntax to improve the absolute path:

<a href= "${pagecontext.request.contextpath}/index.jsp" > Jump to Home </a>

This avoids the occurrence of the project name in the path, using ${pagecontext.request.contextpath} instead of the "/javaweb_httpservletresponse_study_20140615 "

③.form form Submission

<form action= "/javaweb_httpservletresponse_study_20140615/servlet/checkservlet" method= "POST" >            < Input type= "Submit" value= "Submission" ></form>

This is the client browser submits form form to the server, so this "/" is used for the browser, at this time "/" represents the WebApps directory.

It is also recommended to use the following ways to improve the absolute path of the action attribute in form submission:

<form action= "${pagecontext.request.contextpath}/servlet/checkservlet" method= "POST" >          <input type= " Submit "value=" > </form>

 ${pagecontext.request.contextpath} got "/javaweb_httpservletresponse_study_20140615".

${pagecontext.request.contextpath} has the same effect as Request.getcontextpath (), both get "/project name"

④.js a reference to a script and CSS style file

<%--using absolute paths to reference JS scripts--%> <ScriptType= "Text/javascript" src= "${pagecontext.request.contextpath}/js/index.js "></script> <%--${pagecontext.request.contextpath} and Request.getcontextpath () The writing is getting the effect is the same--%> <script type= "Text/javascript" src= "<%=request.getcontextpath ()%>/js/login.js" > </script> <%--referencing CSS styles by using absolute paths--%> <LinkRel= "stylesheet" href= "${pagecontext.request.contextpath}/css/index.css "type=" Text/css "/>

Comprehensive Example:

<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >Iv. details of the response

The Getoutputstream and Getwriter methods are used to obtain the output binary data , output text data Servletouputstream, PrintWriter objects respectively.
  The two methods of Getoutputstream and Getwriter are mutually exclusive , and any one of them is called, and no other method can be called .
The data written to the Servletoutputstream or PrintWriter object by the servlet program is fetched by the servlet engine from the response, and the servlet engine treats the data as the body of the response message. It is then combined with the response status line and each response header to output to the client.
After the Serlvet service method finishes, the Servlet engine checks whether the output stream object returned by the Getwriter or Getoutputstream method has already called the Close method, and if not, The servlet engine calls the Close method to close the output stream object.

HttpServletResponse Object (ii)

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.