Response object
-
Function: set response message
- Set response line
- Format: HTTP/1.1 200 ok
- Set status code: setStatus (int sc)
- Set response header: setHeader (String name, String value)
- Set response body
- Use steps
- Get output stream
- Character output: PrintWrite getWriter()
- Byte output stream: ServletOutputStream getoutputstream()
- Output data to client browser using output stream
- Get output stream
- Use steps
- Set response line
-
case
-
Complete redirection
-
Redirection: how resources jump
-
code implementation
//Mode 1 //Set status code resp.setStatus(302); //Set response header location resp.setHeader("location","/demo2"); //Mode 2 resp.sendRedirect("/demo2");
-
Characteristics of redirect
- Address bar changed
-
Redirect resources that can access other sites (servers)
-
Redirection is two requests. You cannot use the request object to share data
-
Characteristics of forward
- Forwarding address bar path unchanged
- Forwarding can only access resources under the current server
- Forwarding is a request that can be shared using a request object
-
Path writing
- Path classification
- 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
- 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
-
- Relative path: a unique resource cannot be determined by relative path
- Path classification
-
-
Server output character data to browser
-
step
-
Get character output stream
PrintWriter pw = respond.getWriter();
-
output data
pw.writer(String s);
-
-
Random code problem
- Printwriter PW = responded. Getwriter(); the default code of the obtained stream is ISO-8895-1
- Set the default encoding for the stream
- response.setCharacterEnconding("utf-8");
- 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");
-
-
Server output byte data to browser
step
-
Get byte output stream
ServletOutputStream sos = response.getOutputStream();
-
output data
So. Writer ("hello". getBytes("utf-8"));
- Random code problem
- Set default encoding for streams
- response.setCharacterEnconding("utf-8");
- 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");
-
-
Verification Code
- Nature: Pictures
-
Purpose: to prevent malicious form registration
-
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
-
Concept: represents the whole web application and can communicate with the container (server) of the program
-
Obtain
-
Get by request object
request.getServletContext();
-
Get through HTTP Servlet
this.getServletContext();
-
-
function
-
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)
- MIME type: a file data type defined in the process of Internet communication
-
Domain objects: sharing data
- void setAttribute(String name,Object obj); store data
- getAttribute (String name): get value through key
- Void renoveaattribute (string name): remove key value pair by key
- ServletContext object scope: all request data for all users
-
Get the real (server) path of the file
- String getRealPath("/b.txt")
-
-
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
- Page display hyperlink
- Click the hyperlink to pop up the download prompt box
- Complete picture file download
-
Analysis
- 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
- Download prompt box must pop up for any resource
- Use response headers to set how resources are opened
-
step
- Define the page, edit the hyperlink href attribute, point to the Servlet, and pass the resource name filename
- Define Servlet
- Get file name
- Use byte input stream to load file into memory
- Specify the response header of the response: content disposition: attachment; filename=xxx
- Write the data out to the response output stream
-
problem
- Problems with Chinese documents
- Solutions
- Get the browser version information used by the client
- According to different version information, the encoding method of setting filename is different
- Solutions
- Problems with Chinese documents
-
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); } }
-
-