Response object of Servlet

Response object

  • Function: set response message

    1. Set response line
      1. Format: HTTP/1.1 200 ok
      2. Set status code: setStatus (int sc)
    2. Set response header: setHeader (String name, String value)
    3. Set response body
      • Use steps
        1. Get output stream
          • Character output: PrintWrite getWriter()
          • Byte output stream: ServletOutputStream getoutputstream()
        2. Output data to client browser using output stream
  • case

    1. Complete redirection

      1. Redirection: how resources jump

      2. code implementation

          //Mode 1
                //Set status code
                resp.setStatus(302);
                //Set response header location
                resp.setHeader("location","/demo2");
                
                //Mode 2
                resp.sendRedirect("/demo2");
        
      3. Characteristics of redirect

        1. Address bar changed
      4. Redirect resources that can access other sites (servers)

      5. Redirection is two requests. You cannot use the request object to share data

      6. Characteristics of forward

        1. Forwarding address bar path unchanged
        2. Forwarding can only access resources under the current server
        3. Forwarding is a request that can be shared using a request object
      7. Path writing

        1. Path classification
          1. Relative path: a unique resource cannot be determined by relative path
            • For example,. / index.html
            • Path does not start with /
            • Rule: find the relative position relationship between the current resource and the target resource
              • . /: current directory
              • .. /: back one level catalog
          2. Absolute path: unique resources can be determined by absolute path
            • For example: http: //localhost/webServlet Can be omitted as / webServlet
            • Start with /
            • Rule: judge who uses the defined path?
              • For client browser: need to add virtual directory (access path of project)

                • It is recommended to get the virtual directory dynamically: request.getContextPath()

                • a tag and form tag redirection...

              • For servers: no need to add virtual directory

                • Forward
    2. Server output character data to browser

      • step

        1. Get character output stream

          PrintWriter pw = respond.getWriter();

        2. output data

          pw.writer(String s);

      • Random code problem

        1. Printwriter PW = responded. Getwriter(); the default code of the obtained stream is ISO-8895-1
        2. Set the default encoding for the stream
          • response.setCharacterEnconding("utf-8");
        3. Tell the browser the encoding used by the response body
          • response.setHeader("content-type","text/html;charset=utf-8");
        • Simple form setting code: response.setContentType("text/html;charset=utf-8");
    3. Server output byte data to browser

      step

      1. Get byte output stream

        ServletOutputStream sos = response.getOutputStream();

      2. output data

        So. Writer ("hello". getBytes("utf-8"));

      • Random code problem
      1. Set default encoding for streams
        • response.setCharacterEnconding("utf-8");
      2. Tell the browser the encoding used by the response body
        • response.setHeader("content-type","text/html;charset=utf-8");
      • Simple form setting code: response.setContentType("text/html;charset=utf-8");
    4. Verification Code

      1. Nature: Pictures
    5. Purpose: to prevent malicious form registration

      1. Code

        @WebServlet("/Demo3")
        public class CheckCodeServlet  extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                this.doPost(req,resp);
            }
        
            @Override
            protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
                int width = 100;
                int height = 50;
                //1. Create an object and create a picture in memory (captcha picture object)
                BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //        2. Beautify pictures
        //        2.1 fill background color
                Graphics g = image.getGraphics();//Brush object
                g.setColor(Color.PINK);//Set brush color
                g.fillRect(0,0,width,height);
        //        2.2 draw border
                g.setColor(Color.BLUE);//Set brush color
                g.drawRect(0,0,width-1,height-1);
        
                String str = "ABCDEFGHIJKLNMOPQRSTUVWXYZabcdefghijklnmopqrst1234567890";
        //        Generate random angle sign
                Random ran = new Random();
                for (int i = 1; i <= 4; i++) {
                    int index = ran.nextInt(str.length());
        //        Get character
                    char ch = str.charAt(index);
        //        2.3 write verification code
                    g.drawString(ch+"",width/5*i,height/2);
                }
        //        2.4 draw interference line
                g.setColor(Color.GREEN);
        //        Randomly generated interference line
                for (int i = 1; i <= 10; i++) {
                    int x1 = ran.nextInt(width);
                    int x2 = ran.nextInt(width);
        
                    int y3 = ran.nextInt(height);
                    int y4 = ran.nextInt(height);
                    g.drawLine(x1,y3,x2,y4);
                }
        
        
        //        Output pictures to page display
                ImageIO.write(image,"jpg",resp.getOutputStream());
            }
        }
        
        
  • ServletContext object

    1. Concept: represents the whole web application and can communicate with the container (server) of the program

    2. Obtain

      1. Get by request object

        request.getServletContext();

      2. Get through HTTP Servlet

        this.getServletContext();

    3. function

      1. Get MIME type

        • MIME type: a file data type defined in the process of Internet communication
          • Format: large type / small type text / HTML image / jpeg
          • Get: String getMimeType (String file)
      2. Domain objects: sharing data

        1. void setAttribute(String name,Object obj); store data
        2. getAttribute (String name): get value through key
        3. Void renoveaattribute (string name): remove key value pair by key
        • ServletContext object scope: all request data for all users
      3. Get the real (server) path of the file

        • String getRealPath("/b.txt")
    4. Code

      public class ServletContextDemo1 extends HttpServlet {
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //        1. Get by request object
              ServletContext context1 = req.getServletContext();
      //        2. Get through HttpServlet object
              ServletContext context2 = this.getServletContext();
      
              System.out.println(context1);
              System.out.println(context2);
              System.out.println(context1==context2);
              
              //Get MIME type
               String filename = "haha.jpg";
             String mine  =  context1.getMimeType(filename);
              System.out.println(mine);
              //Get the real path of the file
              String realPath1 = context1.getRealPath("/a.txt");//web directory
              System.out.println(realPath1);
              String realPath2 = context1.getRealPath("/WEB-INF/b.txt");//Under the WEB-INF directory
              System.out.println(realPath2);
              String realPath3 = context1.getRealPath("/WEB-INF/classes/c.txt");//Under src directory
              System.out.println(realPath3);
          }
      
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              this.doPost(req,resp);
          }
      }
      
      
    • Case: File Download

      • File download requirements

        1. Page display hyperlink
        2. Click the hyperlink to pop up the download prompt box
        3. Complete picture file download
      • Analysis

        1. If the resources pointed by the hyperlink can be parsed by the browser, they will be displayed in the browser. If they cannot be parsed, a download prompt box will pop up. Unsatisfied demand
        2. Download prompt box must pop up for any resource
        3. Use response headers to set how resources are opened
      • step

        1. Define the page, edit the hyperlink href attribute, point to the Servlet, and pass the resource name filename
        2. Define Servlet
          1. Get file name
          2. Use byte input stream to load file into memory
          3. Specify the response header of the response: content disposition: attachment; filename=xxx
          4. Write the data out to the response output stream
      • problem

        • Problems with Chinese documents
          • Solutions
            1. Get the browser version information used by the client
            2. According to different version information, the encoding method of setting filename is different
      • Code

        package com.creat.test;
        
        import com.creat.Utils.DownLoadUtils;
        
        import javax.servlet.ServletContext;
        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.FileInputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.net.URLDecoder;
        
        @WebServlet("/DownloadServlet")
        public class DownloadServlet extends HttpServlet {
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                String filename = request.getParameter("filename");//Get the file name of the request download
                String decodefilename = URLDecoder.decode(filename, "utf-8");
                //The classes corresponding to the same encoding and decoding rules in java are URLencode and URLdecode
                //Here, the static method decode of URLDecoder class is used to decode the file name (Chinese in the request path has been encoded)
        
                ServletContext servletContext = getServletContext();//Get server domain object
        
                String mimeType = servletContext.getMimeType(decodefilename);//Get the type of transfer file (generally, there are corresponding types in the transfer, and all corresponding relationships are listed in the web.xml configuration file)
                response.setHeader("Content-Type",mimeType);//Set transfer file type
        
                String agent = request.getHeader("User-Agent");//Get the requested browser type
                String encodefilename = DownLoadUtils.getFileName(agent, decodefilename);//The Chinese file name of the download pop-up window will be garbled. Here you can code it in a special way
        
                response.setHeader("Content-Disposition","attachment;filename="+encodefilename);//Set up client browser to process files as attachments
        
                String realPath = servletContext.getRealPath("/"+decodefilename);//Domain object get file real path
        
                FileInputStream inputStream=new FileInputStream(realPath);//Create input stream, load the file to be downloaded into memory
                ServletOutputStream outputStream = response.getOutputStream();//Create output stream and write file to client browser
                byte[]bys=new byte[1024*4];
                int len;
                while ((len=inputStream.read(bys))!=-1){
                    outputStream.write(bys,0,len);
                }
                inputStream.close();
            }
        
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                this.doPost(request,response);
            }
        }
        

Keywords: Java encoding Attribute xml

Added by SoaringUSAEagle on Sun, 03 May 2020 16:18:35 +0300