JavaWeb——Response

1.HTTP agreement

请求消息: The client sends data to the server side
响应消息: a server sends data to the client

1.1. Data Format

Request message: request line, a request header, the request blank line, the request body
response message: response line, in response to the first, in response to a blank line, response body

1.2 In response to the data format

  • 响应行

1. Composition: Protocol / version 响应状态码Status Code Description
2. Response status codes: The server tells the client browser status of this request and response: ? Https://baike.baidu.com/item/HTTP state code / 5053660 fr = aladdin

2.1 status codes are three digits
2.2 Category:

  • 1XX: the server receives the client message received but not completed, after a period, the transmission status code 1XX client asks whether there are data not finished
  • 2XX: 成功, Representative: 200
  • 3XX: 重定向, Representative: 302 (redirect), 304 (cache access)
  • 4XX: Client Error representative: 404 (there is no corresponding resource request path), 405(embodiment not corresponding to the request doXXX method) `
  • 5XX: server-side error, representatives: 500 (internal server abnormal)
  • 响应头

1. Format: Name Value first
2. Common response header:

  • Context-Type: body server tells the client data format, and encoding format in response to this
  • Context-disposition: server tells the client to open the body in response to what data format
  • in-line: defaults, the page opens in the current
  • attachment; filename-XXX: Open Response body, an attachment file downloads
  • 响应空行:Blank line
  • 响应体: Data transmission

2.Response objects

2.1.Response Object function

Features:设置响应消息

  • Setting response line

Set Status Code: setStatus (int sc)

  • Setting response header

Set response header: setHeader (String name, String value)

  • Setting response member

Use steps:
1. Get the output stream

  • Character-output stream: PrintWriter getWriter ()
  • Output stream of bytes: ServletOutputStream getOutputStream ()

2 using the output data stream to output to the client browser wherein

2.2.Response objects related cases

2.2.1 Complete redirection

//ResponseDemo1
package xpu.edu.web.servlet.response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 重定向
 */
@WebServlet("/ResponseDemo1")
public class ResponseDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo1.....");
        //访问ResponseDemo1会自动跳转到ResponseDemo2资源
        //1.设置状态码为302
        response.setStatus(302);
        //2.设置响应头location
        response.setHeader("location","/untitled/ResponseDemo2");
        //简单的重定向方法
        response.sendRedirect("/untitled/ResponseDemo2");}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

//ResponseDemo2
package xpu.edu.web.servlet.response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ResponseDemo2")
public class ResponseDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo2.....");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
  • 重定向的特点

Interview questions: Forward (forward) and redirect (redirect) the difference
1. The forwarding features:

  • Forwarding address bar unchanged
  • Forwarding can only access resources at the current server
  • Forwarding is a request,可以使用request对象来共享数据

2. Redirect features

  • Redirection address bar changes
  • Redirect may access the resources of other sites
  • Redirection is two requests,不可以使用request对象来共享数据
  • Wording path

1. Classification path

  • Relative path: can not determine the unique resources relative path

Rules: 找到当前资源和目标资源之间的相对位置关系"./" represents the current directory, "... /" Back on behalf of the parent directory
. Do not start with / to the beginning of the path, such as ./index.html

  • Absolute path: the only resource can be determined by absolute path

A path beginning with / as / untitled / ResponseDemo1
rule: 判断定义的路径是给谁用的determining where the request is issued from

  • To the client browser to use: 加虚拟目录such as redirection, the proposed acquisition of dynamic virtual directory: request.getContextPath ()
  • Server to use: 不需要加虚拟路径such as forward

Dynamic access to the virtual directory, bring a lot of modifications to prevent operation of the virtual path to change:
Here Insert Picture Description

2.2.2 Server character data output to the browser

  • Get the character stream output
  • Output Data

!!!注意乱码问题: PrintWriter writer = response.getWriter () Gets the default encoding stream is ISO-8859-1, in order to prevent distortion, 要设置该流的默认编码(获取流之前设置)telling the browser encoder should be used: response.setContentType ( "text / html; charset = UTF-8 ");

@WebServlet("/ResponseDemo3")
public class ResponseDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取流对象之前设置流的默认编码(也可以不设置)
        response.setCharacterEncoding("GBK");
        //告诉浏览器,服务器发出的消息体数据的编码,建议浏览器使用该编码解码
        response.setHeader("content-type","text/html;charset=UTF-8");

        //****简单的形式设置编码****
        response.setContentType("text/html;charset=UTF-8");

        //获取字符输出流
        PrintWriter writer = response.getWriter();
        //输出数据
        writer.write("hello response");
        //可以识别标签
        writer.write("<h1>hello response</h1>");
        //中文会乱码说明编解码不一致,浏览器默认字符集和操作系统有关
        writer.write("你好 response");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

2.2.3 server output byte data to the browser

@WebServlet("/ResponseDemo4")
public class ResponseDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        //获取字节输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //输出数据
        outputStream.write("你好".getBytes("UTF-8"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

2.2.4. Verification code

Is a picture on the nature of the verification code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>
        /**
         * 点击超链接或者图片,需要换一张
         * 1.给超链接和图片绑定单击事件
         * 2.重新设置图片的src属性值
         */
        window.onload = function () {
            //获取图片对象
            var img = document.getElementById("Check");
            //绑定单击事件
            img.onclick = function () {
                //加时间戳,防止路径一样直接访问缓存,那样图片没有变化
                var date = new Date().getTime();
                img.src = "/untitled/CheckCode?" + date;
            }

            //获取超链接对象
            var img1 = document.getElementById("Change");
            //绑定单击事件
            img1.onclick = function () {
                //加时间戳,防止路径一样直接访问缓存,那样图片没有变化
                var date = new Date().getTime();
                img.src = "看不清换一张?" + date;
            }
        }


    </script>


</head>
<body>
<img id = "Check" src = "/untitled/CheckCode" />

<a id = "change" href = "">看不清换一张?</a>
</body>
</html>
/**
 * 验证码
 */
@WebServlet("/CheckCode")
public class CheckCode extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 图片的宽、高
         */
        int width = 100;
        int height = 50;

        //1.创建一个对象,在内存中代表一张图片(代表验证码的图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//RGB表示三原色的图片

        //2.美化图片
        //2.1.填充背景色
        //获取画笔对象
        Graphics graphics = image.getGraphics();
        //设置画笔颜色
        graphics.setColor(Color.PINK);
        //填充颜色
        graphics.fillRect(0,0,width,height);

        //2.2.画边框
        graphics.setColor(Color.BLUE);
        //边框有一个像素宽度
        graphics.drawRect(0,0,width - 1,height - 1);

        //2.3.生成随机内容
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random ran = new Random();
        for (int i = 1; i < 5; i++) {
            //生成随机角标
            int index = ran.nextInt(str.length());
            //获取字符
            char c = str.charAt(index);
            //写验证码
            graphics.drawString(c + "",width / 5 * i,height / 2);
        }

        //2.4.画干扰线
        for (int i = 0; i < 6; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            graphics.setColor(Color.GREEN);
            graphics.drawLine(x1,y1,x2,y2);
        }

        //3.将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

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

3.ServletContext objects

The concept: ServletContext object represents the entire Web application,可以和程序的容器(服务器)来通信

3.1. Getting ServletContext object

  • 通过request对象获取:request.getServletContext()
  • 通过HttpServlet获取:this.getServletContext()
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //ServletContext对象的获取
        //1.通过request
        ServletContext servletContext = request.getServletContext();
        //2.通过HttpServlet获取
        ServletContext servletContext1 = this.getServletContext();

        System.out.println(servletContext == servletContext1);//true
    }

3.2. Function

  • 获取MIME类型
  • MIME type definition: a definition file in Internet communication process data type
  • Format: Large type / small type, eg: text / html
@WebServlet("/ServletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //ServletContext对象功能
        //获取ServletContext对象,通过HttpServlet获取
        ServletContext servletContext1 = this.getServletContext();
        //定义一个文件名称(实际应用中是动态获取的)
        String filename = "a.jpg";
        //获取MIME类型
        String mimeType = servletContext1.getMimeType(filename);
        System.out.println(mimeType);//image/jpeg

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
  • 域对象:共享数据
  • setAttribute(String name,Object value)
  • getAttribute(String name)
  • removeAttribute(String name)
  • ServletContext域对象的范围: All users in all the requested data, large-scale, as the life cycle,要谨慎使用
  • 获取文件的真实(服务器)路径

方法:String getRealPath(String path)

@WebServlet("/ServletContextDemo3")
public class ServletContextDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取ServletContext对象,通过HttpServlet获取
        ServletContext servletContext1 = this.getServletContext();
        //获取文件的服务器路径
        String realPath = servletContext1.getRealPath("/b.txt");//Web目录下资源访问
        System.out.println(realPath);
        //File file = new File(realPath);
        String realPath1 = servletContext1.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下的资源访问
        System.out.println(realPath1);

        String realPath2 = servletContext1.getRealPath("/WEB-INF/classes/a.txt");//src目录下访问资源
        System.out.println(realPath2);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Guess you like

Origin blog.csdn.net/LiLiLiLaLa/article/details/90382128