Web Learning History Record (9) - Request Response

Web Learning History Record (9)

Case 1: Complete file download

Overview of HttpServletReaponse
In the Servlet API, an HttpServletReaponse interface is defined, which inherits from the SeveletResponse interface and is specially used to encapsulate HTTP response messages. Http response messages are divided into
three parts: response line, response message header, and message body.
Method for sending response status code, response header, and response body to the client

Action Response Three Parts

The operation response line
is usually the first line

Commonly used status codes:
200: Success
302: Redirect
304: Access cache
404: Client error
500: Server error

Operation response header
One key can correspond to multiple values, or it can correspond to one value

Mastered method: setHeader(String key,String value)

Commonly used response headers:
Refresh: Timing jump
Location: Redirection
Content-Disposition: Set the header when the file is downloaded
Content-Type: Set the MIME type of the response content

response body

File download method

The first method: the hyperlink method
directly writes the path of the file on the server to the href attribute. If the browser does not support the file in this format, it will prompt you to download it. If the browser supports the file in this format, open it directly. no more downloads

The second method: manual coding method
Manual coding realizes the download, regardless of whether the browser recognizes the format, it will be downloaded

Manual encoding format requires
setting two headers and one stream
Two headers:
Content-Dispostion: The browser recognizes the format file and prompts the browser to download
Content-Type: file type (MIME type)
One stream:
Get the input stream of the file to be downloaded

import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@WebServlet("/downloadServletDemo01")
public class DownloadServletDemo01 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        String fileName = request.getParameter("fileName");
        System.out.println("fileName = " + fileName);


        String realPath = getServletContext().getRealPath("/download/" + fileName);
        InputStream is = new FileInputStream(realPath);

        response.setHeader("Content-Disposition","attachment;filename=" + fileName);

        String mimeType = getServletContext().getMimeType(fileName);
        response.setHeader("Content-Type",mimeType);


        ServletOutputStream os = response.getOutputStream();
        byte[] bs = new byte[1024];
        int len;
        while ((len = is.read(bs))!= -1){
    
    
            os.write(bs,0,len);
        }
        os.close();
        is.close();

    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>文件下载</h1>
<h3>超链接方式</h3>
<!--超链接方式下载文件,直接将文件的路径写入到href中即可。但是如果浏览器支持文件格式(jpg,png)会直接打开,不会再进行下载-->
<a href="download/WEB01.zip">web01.zip</a><br/>
<a href="download/a.jpg">a.jpg</a>
<h3>编码方式</h3>
<a href="downloadServletDemo01?fileName=a.jpg">a.jpg</a><br/>
<a href="downloadServletDemo01?fileName=WEB01.zip">web01.zip</a><br/>
<a href="downloadServletDemo01?fileName=美女.jpg">美女.jpg</a>
</body>
</html>

ResponseOther operations

Timed refresh

response.setHeader("refresh","秒数";url = 跳转的路径)//几秒之后跳转到指定的路径上
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
    response.setContentType("text/html ;charset = utf-8");
    response.getWriter().write("5秒后跳转");
    response.setHeader("refresh", "5; url = http://www.baidu.com");
}

Redirection
Redirection is two requests
. Redirection address bar path changes.
Redirection path writes absolute path

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        response.getWriter().print("1");
        System.out.println("111");
        response.sendRedirect("http://localhost:8080/servletDemo02");
    }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        response.getWriter().print("222");
        System.out.println("2");
    }

Output content to the page

response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type","text/html;charset=utf-8");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write("你好".getBytes("utf-8"));

Case 2: Website login case

request operation request three parts

Get client information (operation request line)
Request method Request path (url) Protocol version
POST /day17Request/WEB01/register.htm?username=zs&password=123456 HTTP/1.1

getMethod(): Get the request method
getRemoteAddr(): Get the IP address of the client
getContextPath(): Get the current application project name
getRequestURI(): Get the request address without the host name
getRequestURL(): Get the request address with the host name
getServerPort (): Obtain the port of the server
getQueryString(); Obtain the request parameters (get request, URL? eg: username=zs&password=123456)

Obtain request header information (operation request header)
getHeader(String name)
user-Agent: browser information
Referer: which website it came from (anti-leeching)

Accept relevant parameters (operation request body)

String getParameter(String name)
gets the value corresponding to the specified parameter, and does not return null. If there are more than one, get the first
String[] getParameterValues(String name)
get all the values ​​corresponding to the specified parameter name.
This method is dedicated to the Map getParameterMap() provided for the checkbox
to get all the request parameters

Use BeanUtils package

Set up a landing page and prepare to submit form data (username, password)
Import BeanUtils related jar packages
Create Servlet to obtain request parameters
Call BeanUtils.populate method to encapsulate data

Summarize

Forward

request.getRequestDispatcher(url).forward(request,response);

The difference between forwarding and redirection:
Forwarding is a one-time request, while redirection is a second request.
The path in the forwarding address bar remains unchanged. The redirection address bar path has changed.
The forwarding path can only write the internal path of the current project. The redirection can be internal or external.
The value accessed by the external request domain object is valid in forwarding, but invalid in redirection

access value as domain object

ServletContext: the scope of the entire application
request: the scope of a valid request
domain object is a container, this container is mainly used for data transmission between Servlet and Servlet/JSP

Guess you like

Origin blog.csdn.net/qq_49658603/article/details/108392597