Javaweb Learning Summary (eight)--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:

 1 package gacl.response.study; 2 3 Import Java.awt.Color; 4 Import Java.awt.Font; 5 Import Java.awt.Graphics2D; 6 Import Java.awt.image.BufferedImage; 7 Import java.io.IOException; 8 Import Java.util.Random; 9 Import javax.imageio.imageio;10 Import javax.servlet.servletexception;11 import javax.servlet.http.httpservlet;12 Import javax.servlet.http.httpservletrequest;13 Import javax.servlet.http.httpservletresponse;14 public class RESPONSEDEMO03 extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) 1 8 throws Servletexception, IOException {response.setheader ("Refresh", "5");//Set Refresh response The Head Control browser refreshes 21//1 every 5 seconds. Create a picture in memory bufferedimage image = new BufferedImage, Bufferedimage.type_int_ RGB); 23//2. Get Picture//graphics g = image.getgraphics (); graphics2d g = (graphics2d) image.getgraph ICS (); G.setcolor (color.white);//Set the background color of the picture G.fillrect (0, 0, 80, 20);//Fill background color 28//3. Write data to the picture G.setcolor (Color.Blue);//Set the color of the font on the picture to G.setfont (The new font (NUL L, Font.Bold, ()); g.DrawString (Makenum (), 0, 20), 32//4. Setting the response header control the browser browser opens as a picture Response.setco Ntenttype ("Image/jpeg");//equivalent to Response.setheader ("Content-type", "Image/jpeg"); 34//5. Setting the response header control browser does not cache picture data Esponse.setdateheader ("Expries",-1); Response.setheader ("Cache-control", "No-cache"); PNs Response.sethea     Der ("Pragma", "No-cache"); 38//6. Write the picture to the browser at Imageio.write (image, "JPG", Response.getoutputstream ()); 40 }41 42/**43 * Generate random number of * @return45 */46 private String makenum () {* * random random = new R Andom (); String num = Random.nextint (9999999) + "", stringbuffer sb = new StringBuffer (); (int i = 0; i < 7-num.length (); i++)    {Wuyi Sb.append ("0");}53 num = sb.tostring () +num;54 return num;55 }56-public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servlete Xception, IOException {doget (request, response); 60}61 62}

The results of the operation are as follows:

  

Second, HttpServletResponse Common application--set the response header to control the behavior of the browser 2.1, set the HTTP response Header control browser prohibit caching the contents of the current document
1 Response.setdateheader ("Expries",-1), 2 response.setheader ("Cache-control", "No-cache"), 3 Response.setheader (" Pragma "," No-cache ");
2.2. Set the HTTP response header to control the browser to refresh the Web page periodically (refresh)
1 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:

 1 package gacl.response.study; 2 Import java.io.IOException; 3 Import javax.servlet.ServletException; 4 Import Javax.servlet.http.HttpServlet; 5 Import Javax.servlet.http.HttpServletRequest; 6 Import Javax.servlet.http.HttpServletResponse; 7 8 public class ResponseDemo04 extends HttpServlet {9. public void Doget (HttpServletRequest request, HTTPSERVLETR Esponse response) throws Servletexception, IOException {12/**13 * 1. Calling the Sendredirect method to implement a request reset The Sendredirect method internally calls the * Response.setheader ("location", "/javaweb_httpservletresponse_study_201406          15/index.jsp "); Response.setstatus (httpservletresponse.sc_found);//Set 302 status code, equivalent to Response.setstatus (302); 17 */18 response.sendredirect ("/javaweb_httpservletresponse_study_20140615/index.jsp"); 19 20// 2. Use response to set 302 status code and set location response header to implement Redirect request redirect//response.setheader ("Location", "/javaweb_httpservletresponse_ Study_20140615/index.jsp "); 22         Response.setstatus (Httpservletresponse.sc_found);//Set 302 status code, equivalent to Response.setstatus (302);}24 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (request, response); 28}29}
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/**2 * 1.servletcontext.getrealpath ("/download/1.jpg") is used to obtain a resource on the server, 3 * then this "/" is for the server, "/" At this time represents the Web project 4  * Servletcontext.getrealpath ("/download/1.jpg") means reading 1 of the download folder under Web Engineering. JPG This resource 5 * As long as you understand the specific meaning of the "/" representation, you can quickly write down the absolute path of the Web resource to be accessed 6 */7 this.getservletcontext (). Getrealpath ("/download/1.jpg");

②. Forward to other pages on the server side

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

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

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

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

3.2. "/" represents the WebApps directoryCommon Application Scenarios for

①. Using Sendredirect to implement request redirection

1 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

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

This is changed into

1 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

1 <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:

1 <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

1 <form action= "/javaweb_httpservletresponse_study_20140615/servlet/checkservlet" method= "POST" >    2         <input type= "Submit" value= "Submission" >3 </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:

1 <form action= "${pagecontext.request.contextpath}/servlet/checkservlet" method= "POST" >2          < Input type= "Submit" value= "Submission" >3 </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

1  <%--Reference JS script using absolute path--%>2  <script type= "Text/javascript" src= "${ Pagecontext.request.contextpath}/js/index.js "></script>3  <%--${pagecontext.request.contextpath } and Request.getcontextpath () The result is the same--%>4  <script type= "Text/javascript" src= "<%= Request.getcontextpath ()%>/js/login.js "></script>5  <%--using absolute paths to reference CSS styles--%>6  < Link rel= "stylesheet" href= "${pagecontext.request.contextpath}/css/index.css" type= "Text/css"/>

Comprehensive Example:

 1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 3 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 4 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.

Javaweb Learning Summary (eight)--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.