008-Java Web Learning Response

Disclaimer: All my articles are the compilation of online teaching videos, including Mad God Talk, Shang Silicon Valley, Dark Horse Programmer, etc., used as reference materials, without any commercial use, please refer to the majority of netizens, please do not spray ,Thank you. (Note that due to the website, some code characters may have problems. It is recommended that when reading the code, it is best to correspond with the picture below) After the
web server receives the client's http request, it creates a representative for this request. The requested HttpServletRequest object and an HttpServletResponse object representing the response. If we want to get the parameters sent by the client request, we will find the HttpServletRequest object; if we want to respond to the client with some information, we will find the HttpServletResponse object, so today we will analyze the HttpServletResponse object.
1. The simple classification of HttpServletResponse object methods is
responsible for sending data to the browser:
ServletOutputStream getOutputStream() throws IOException;

PrintWriter getWriter() throws IOException;
These two methods inherit from the method of its parent class
responsible for sending response headers to the browser:
void setCharacterEncoding(String var1);

void setContentLength(int var1);

void setContentLengthLong(long var1);

void setContentType(String var1);
These four methods are inherited from its parent class
void setDateHeader(String var1, long var2);

void addDateHeader(String var1, long var2);

void setHeader(String var1, String var2);

void addHeader(String var1, String var2);

void setIntHeader(String var1, int var2);

void addIntHeader(String var1, int var2);

void setStatus(int var1);
自身的方法
响应状态码:
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2. Common applications
1) Output a message to the browser
2) Steps
to download the file To obtain the path of the
downloaded file The download file name is
set so that the browser can support downloading us want files
get downloaded file input stream
to create a buffer
to obtain OutputStream object
will FileOutputStream stream buffer is written to the buffer
using OutputStream output data buffer to the client
3, which produce the experimental frame
1) create a new Maven project javaweb- response, created using the webapp template. In order to prevent conflicts, it is recommended to delete all the dependent jar packages in the local warehouse, and then let IDEA re-download
2) configure the pom.xml of the parent project, import the Servlet dependent jar package
008-Java Web Learning Response
3) here Under the project, create a new Maven module response, use the webapp template to create, and add a directory and mark to it, the structure is shown in the figure
008-Java Web Learning Response
3) According to the previous steps, change the pom.xml under the response module to make it Clean module
008-Java Web Learning Response
4) Configure tomcat server
008-Java Web Learning Response
008-Java Web Learning Response
5) Modify web.xml under src->main->webapp->WEB-INF under the response module
008-Java Web Learning Response
6) If there is no index.jsp and other files in the webapp directory, we can manually create it by ourselves, as shown in the figure below
008-Java Web Learning Response
7) Start tomcat, test whether the configuration is successful, and the
008-Java Web Learning Response
above figure appears, everything is OK!
4. Create the com.kuang.servlet package in the java directory, and create the FileServlet file below.
008-Java Web Learning Response
5. Start writing the code according to our above analysis, and place a "play.png" file in the resources directory. Our goal is to do this After the file is accessed through Servlet, it can be downloaded to the local hard disk
//. To obtain the path of the downloaded file
String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/play.png");
System.out .println("The path of the downloaded file:" + realPath);
//2. The downloaded file name
String fileName = realPath.substring(realPath.lastIndexOf("\") + 1);
//3. Set the browser to Support downloading the file we want. Here, since the file name is Chinese, the file name should be encoded with URLEncoder.encode
resp.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName," utf-8"));
//4.












008-Java Web Learning Response









008-Java Web Learning Response

008-Java Web Learning Response
008-Java Web Learning Response


How to realize the verification code? There are two ways, one is to use the front-end implementation, the other is the back-end implementation, you need to use the java image class to generate a picture, here we mainly talk about the back-end implementation.
The
008-Java Web Learning Response
code in the doGet to create the ImageServlet file is as follows:
//How to make the browser refresh automatically every 3 seconds
resp.setHeader("refresh","3");
//Create an image in memory
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//Get the picture
Graphics2D g = (Graphics2D) image.getGraphics();
//Set the background color of the picture
g.setColor(Color.white);
g.fillRect(0,0,80,20);
//Write data to the picture
g.setColor(Color.BLUE);
g.setFont(new Font(null,
Font.BOLD ,20)); g.drawString(makeNum(),0,20);
//Tell the browser , This request is opened as a picture
resp.setContentType("image/jpeg");
//The website has a cache, and the browser is not allowed to cache
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control ",
resp.setHeader("Pragma","no-cache");
//Write the picture to the browser
ImageIO.write(image,"jpg",resp.getOutputStream());
008-Java Web Learning Response
The method code for generating random numbers is as follows:
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;
}
008-Java Web Learning Response
Modify web.xml and add servlet entries, the code is as follows
<servlet>
<servlet-name>image</servlet -name>
<servlet-class>com.kuang.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/img</url-pattern>
</servlet-mapping>
008-Java Web Learning Response
Start tomcat, enter http://localhost:8080/resp/img, view the result
008-Java Web Learning Response

Guess you like

Origin blog.51cto.com/12859164/2545411