Javaweb Learning to organize--httpservletresponse objects

Source: Internet
Author: User
first, HttpServletResponse Common application-Generate verification code

1.1. Generate a random image to use as a verification code

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

  

Example of generating a random picture:

Package Gacl.response.study;import Java.awt.color;import Java.awt.font;import java.awt.graphics2d;import Java.awt.image.bufferedimage;import Java.io.ioexception;import Java.util.random;import Javax.imageio.ImageIO; Import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class ResponseDemo03 Extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Ser Vletexception, IOException {response.setheader ("Refresh", "5");//Set Refresh response header control browser refreshes every 5 seconds//1. In memory        Create a picture bufferedimage image = new BufferedImage (BUFFEREDIMAGE.TYPE_INT_RGB);        2. Get picture//graphics g = image.getgraphics ();        Graphics2D g = (graphics2d) image.getgraphics (); G.setcolor (Color.White);//Set the background color of the picture g.fillrect (0, 0, 80, 20);//fill background color//3. Write data to the picture G.setcolor (Color.Blue );//Set the font on the pictureColor G.setfont (new Font (null, Font.Bold, 20));        g.DrawString (Makenum (), 0, 20); 4. Set the response header to control the browser browser to open Response.setcontenttype ("Image/jpeg") as a picture, or//equivalent to Response.setheader ("Content-type", "image/        JPEG ");        5. Set the response header control browser does not cache picture data Response.setdateheader ("Expries",-1);        Response.setheader ("Cache-control", "No-cache");        Response.setheader ("Pragma", "No-cache");    6. Write the image to the browser imageio.write (image, "JPG", Response.getoutputstream ());        /** * Generates random numbers * @return */private String Makenum () {Random random = new random ();        String num = random.nextint (9999999) + "";        StringBuffer sb = new StringBuffer ();        for (int i = 0; i < 7-num.length (); i++) {Sb.append ("0");        num = sb.tostring () +num;    return num; } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (Request, ResponSE); }}

The results of the operation are as follows:

Second, HttpServletResponse Common application--Set the response header control browser behavior

2.1. Set HTTP response Header control Browser prevents the current document content from being cached

Response.setdateheader ("Expries",-1); Response.setheader ("Cache-control", "No-cache"); Response.setheader ("Pragma", "No-cache");

2.2. Set the HTTP response header to control the browser to refresh the Web page periodically (refresh)

Response.setheader ("Refresh", "5");//Set Refresh response header control browser refreshes every 5 seconds

2.3. 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:

Package Gacl.response.study;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class ResponseDemo04 extends HttpServlet {public void doget (HttpServlet Request request, HttpServletResponse response) throws Servletexception, IOException {/** * 1. Call The Sendredirect method implements the request redirection, * The Sendredirect method internally calls the * Response.setheader ("location", "/javaweb_httpservletrespons         E_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 the 302 status code and set the location response header to implement the redirect 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 void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex    ception {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 remember "/" in the following way: if "/" is used for the server, it represents the current Web project, and if "/" is 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 of the resource

/*** 1.servletcontext.getrealpath ("/download/1.jpg") is used to get 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 you want to access */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 means" 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 and uses 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}   the effect is equivalent to Request.getcontextpath (), both get "/project name"

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

<%--reference JS script using absolute path--%>  <script type= "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 using absolute paths--%>  <link rel= "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.

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.