javaweb Note 3: request and response

HttpServletResponse

When we create a Servlet, we will override the service() method, or doGet()/doPost(). These methods have two parameters, a request representing the request and a response representing the response. The type of response in the service method is ServletResponse, while the type of response in the doGet/doPost method is HttpServletResponse. HttpServletResponse is a sub-interface of ServletResponse, with more powerful functions and methods.

The running process of response
insert image description here
Capture the Http response through the packet capture tool
insert image description here
Because the response represents the response, we can set the response line, response header and response body of the Http response through this object

Set the response line by response

Set the status code of the response linesetStatus(int sc)

//手动设置http响应行中的状态码
response.setStatus(404);

Set the response header through response, where add means to add, and set means to set

addHeader(String name, String value) 
addIntHeader(String name, int value) 
addDateHeader(String name, long date) 
setHeader(String name, String value) 
setDateHeader(String name, long date) 
setIntHeader(String name, int value)

for example:

Date date = new Date();

//设置响应头
response.addHeader("name", "zhangsan");
response.addIntHeader("age", 28);
response.addDateHeader("birthday", date.getTime());

response.addHeader("name", "lisi");

response.setHeader("age", "28");
response.setHeader("age", "50");
 //设置定时刷新的头
 response.setHeader("refresh", "5;url=http://www.baidu.com");

//----------重定向--------------------------
//没有响应 告知客户端去重定向到servlet2
//1、设置状态码302
//response.setStatus(302);
//2、设置响应头Location
//response.setHeader("Location", "/WEB14/servlet2");

//封装成一个重定向的方法sendRedirect(url)
response.sendRedirect("/WEB14/servlet2");

Set the response body through response

Response body setting textPrintWriter getWriter()

response.getWriter().write("hello");

To obtain the character stream, the string can be set into the response buffer through the write(String s) method of the character stream, and then Tomcat will assemble the content in the response buffer into an Http response and return it to the browser.

Regarding the problem of garbled characters in setting Chinese
Reason: the default encoding of the response buffer is iso8859-1, there is no Chinese in this code table, you can setCharacterEncoding(String charset)set the encoding of the response through the response.

However, it is found that the client still cannot display text normally. The reason is that we set the encoding of the response buffer to UTF-8, but the default encoding of the browser is the encoding of the local system. Because we are all Chinese systems, the client browser's The default encoding is GBK, we can manually modify the encoding of the browser to be UTF-8.

You can also specify the encoding method of the browser parsing the page in the code, and specify setContentType(String type)the encoding when parsing the page through the response method is UTF-8, response.setContentType("text/html;charset=UTF-8");
the above code can not only specify the encoding when the browser parses the page, but also contains setCharacterEncoding Function, so in the actual development, just write response.setContentType("text/html;charset=UTF-8"); can solve the problem of page output Chinese garbled characters.

//设置response查询的码表
        //resp.setCharacterEncoding("UTF-8");
        //通过一个头 Content-Type 告知客户端使用何种码表
        //resp.setHeader("Content-Type", "text/html;charset=UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write("你好");

Response header settings bytes

ServletOutputStream getOutputStream(): Obtain the byte stream, through the write(byte[] bytes) of the byte stream, you can write bytes to the response buffer, and the Tomcat server will form the byte content into an Http response and return it to the browser.

Case 1: Downloading pictures on the server

//使用response获得字节输出流
        ServletOutputStream out = resp.getOutputStream();

        //获得服务器上的图片
        String realPath = this.getServletContext().getRealPath("a.jpg");
        InputStream in = new FileInputStream(realPath);

        int len = 0;
        byte[] buffer = new byte[1024];
        while((len=in.read(buffer))>0){
    
    
            out.write(buffer, 0, len);
        }

        in.close();
        out.close();

Case 2: Output Chinese using byte stream

//1 获得输出字节流
        OutputStream os = resp.getOutputStream();
        //2 输出中文
        os.write("你好 世界!".getBytes("UTF-8"));
        //3告诉浏览器使用GBK解码 ==> 乱码
        resp.setHeader("Content-Type", "text/html;charset=utf-8");

Case 3: Complete file download

The essence of file download is file copy, copying files from the server to the browser. Therefore, file download requires IO technology to read the file on the server side using InputStream, and write it to the response buffer using ServletOutputStream

code show as below:

package response;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by yang on 2017/7/23.
 */
public class Demo01 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //要下载的文件的名称
        String filename = "a.flv";

        //要下载的这个文件的类型-----客户端通过文件的MIME类型去区分类型
        resp.setContentType(this.getServletContext().getMimeType(filename));
        //告诉客户端该文件不是直接解析 而是以附件形式打开(下载)
        resp.setHeader("Content-Disposition", "attachment;filename="+filename);

        //获取文件的绝对路径
        String path = this.getServletContext().getRealPath("download/"+filename);
        //获得该文件的输入流
        InputStream in = new FileInputStream(path);
        //获得输出流---通过response获得的输出流 用于向客户端写内容
        ServletOutputStream out = resp.getOutputStream();
        //文件拷贝的模板代码
        int len = 0;
        byte[] buffer = new byte[1024];
        while((len=in.read(buffer))>0){
    
    
            out.write(buffer, 0, len);
        }
    }
}

HttpServletRequest

When we create a Servlet, we will override the service() method, or doGet()/doPost(). These methods have two parameters, a request representing the request and a response representing the response.

The type of request in the service method is ServletRequest, and the type of request in the doGet/doPost method is HttpServletRequest. HttpServletRequest is a sub-interface of ServletRequest. It has more powerful functions and methods. Today we will learn about HttpServletRequest.

The running process of request

insert image description here
Capture the Http request through the packet capture tool.
insert image description here
Because request represents the request, we can obtain the request line, request header and request body of the Http request through this object.

Get the request line through request

1. Obtain the request method of the client: String getMethod()

 //1、获得请求方式
String method = req.getMethod();
System.out.println("method:"+method);//method:GET

2. Get the requested resource:

String getRequestURI() 
StringBuffer getRequestURL() 
String getContextPath() ---web应用的名称
String getQueryString() ---- get提交url地址后的参数字符串username=zhangsan&password=123

for example:

 //2、获得请求的资源相关的内容
String requestURI = req.getRequestURI();
StringBuffer requestURL = req.getRequestURL();
System.out.println("uri:"+requestURI);//uri:/Demo01
System.out.println("url:"+requestURL);//url:http://localhost:8080/Demo01
        //获得web应用的名称
String contextPath = req.getContextPath();
System.out.println("web应用:"+contextPath);//web应用:
//地址后的参数的字符串
String queryString = req.getQueryString();
System.out.println(queryString);//name=yyb&pwd=123
//3、获得客户机的信息---获得访问者IP地址
String remoteAddr = req.getRemoteAddr();
System.out.println("IP:"+remoteAddr);//IP:0:0:0:0:0:0:0:1

3. Request obtains some information about the client (client): request.getRemoteAddr() — obtains the IP address of the accessed client

4. Obtain the request header through request.

long getDateHeader(String name)
String getHeader(String name)
Enumeration getHeaderNames()
Enumeration getHeaders(String name)
int getIntHeader(String name)

for example:

//1、获得指定的头
        String header = request.getHeader("User-Agent");
//Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240
        System.out.println(header);
//2、获得所有的头的名称
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
    
    
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            System.out.println(headerName + ":" + headerValue);
        }
//accept:text/html, application/xhtml+xml, image/jxr, */*
//accept-language:zh-CN
//user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240
//accept-encoding:gzip, deflate
//host:localhost:8080
//connection:Keep-Alive
//cookie:JSESSIONID=ABC9B9C2FFC81561CA377311BD3BD409

6. Obtain the request body through request.

The content in the request body is the request parameters submitted by post, the format is: username=zhangsan&password=123&hobby=football&hobby=basketball

key --------value
username [zhangsan]
password [123]
hobby [football,basketball]

Taking the above parameters as an example, the request parameters can be obtained through the following methods:

String getParameter(String name) 
String[] getParameterValues(String name)
Enumeration getParameterNames()
Map<String,String[]> getParameterMap()

Note: The request parameters of the get request method can be obtained in the same way as above.

//1、获得单个表单值
        String username = request.getParameter("username");
        System.out.println(username);
        String password = request.getParameter("password");
        System.out.println(password);
        //2、获得多个表单的值
        String[] hobbys = request.getParameterValues("hobby");
        for(String hobby:hobbys){
    
    
            System.out.println(hobby);
        }
        //3、获得所有的请求参数的名称
        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()){
    
    
            System.out.println(parameterNames.nextElement());
        }
        System.out.println("------------------");
        //4、获得所有的参数 参数封装到一个Map<String,String[]>
        Map<String, String[]> parameterMap = request.getParameterMap();
        for(Map.Entry<String, String[]> entry:parameterMap.entrySet()){
    
    
            System.out.println(entry.getKey());
            for(String str:entry.getValue()){
    
    
                System.out.println(str);
            }
            System.out.println("---------------------------");
        }

Solve the garbled characters of the parameters
Solve the garbled characters of the post submission method: request.setCharacterEncoding("UTF-8");
Solve the garbled characters of the get submission method: parameter = new String(parameter.getbytes("iso8859-1"), "utf-8" );

//设置request的编码---只适合post方式
request.setCharacterEncoding("UTF-8");
        
//get方式乱码解决
String username = request.getParameter("username");//乱码
//先用iso8859-1编码, 在使用utf-8解码
//username = new String(username.getBytes("iso8859-1"),"UTF-8");

Other functions of request

request is a domain object, and the request object is also a region object for storing data, which will be developed in the future. When request forwarding is used, the servlet finishes processing the data, and the processing result is handed over to jsp for display. You can use the request field to bring the processing results from the servlet to the jsp for display. So it also has the following methods:

setAttribute(String name, Object o)
getAttribute(String name)
removeAttribute(String name)

Note: The scope of the request field is within one request. There are as many request domains as there are currently requests in the system.

request complete request forwarding

After a servlet is processed, it is handed over to the following servlet (JSP) to continue processing. In real development, there is no case where the servlet is forwarded to the servlet. All are forwarded to JSP by servlet. This can achieve the role of division of labor:

servlet: more suitable for business processing.
JSP: More suitable for display functions.
//Get the request forwarder----path is the forwarded address

RequestDispatcher getRequestDispatcher(String path)

//Forward through the transponder object

requestDispathcer.forward(ServletRequest request, ServletResponse response)

for example:

//向request域中存储数据
request.setAttribute("name", "tom");
//servlet1 将请求转发给servlet2
RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet2");
//执行转发的方法
dispatcher.forward(request, response);

Include

Two servlets (jsp) jointly output content to the browser. The effect is that in actual development, multiple pages contain the same content, and the same content is extracted into a jsp, and the extracted jsp is included in the jsp that needs to display this segment of content. It can achieve unified management of the same content.

response.setContentType("text/html;charset=utf-8");
response.getWriter().print("这是正文部分<hr>");
request.getRequestDispatcher("/GServlet").include(request, response);
ServletContext域与Request域的生命周期比较
ServletContext

Creation: server startup
Destruction: server shutdown
Domain scope: the entire web application
request:

Create: Create a request when accessing
Destroy: End the response and destroy the request
Scope of domain:
The difference between forwarding and redirection in a request

  1. Redirect the request twice and forward the request once
  2. The address in the redirection address bar changes, but the forwarding address remains the same
  3. Redirection can access external websites, forwarding can only access internal resources
  4. Forwarding performs better than redirecting

Guess you like

Origin blog.csdn.net/weixin_42838061/article/details/121143910