Response
The response object represents the response message returned by the web server to the browser
Developers can use the relevant methods of the response object to set the corresponding information to be returned to the browser
Set response line
void setStatus(int sc) sets the status code
Set response header
void setHeader(String name, String value) sets the specified header name and corresponding value
Set response body
PrintWriter getWriter() character output stream, which does not support Chinese. The default code is ISO-8859-1
ServletOutputStream getOutputStream() byte output stream
Note that in the same servle t, two types of output streams cannot exist at the same time. They are mutually exclusive
redirect
Is the way resources jump
By accessing the browser, the server can redirect to other servlets through the browser
Implementation steps
- Set status code
response.setStatus(302);//302 indicates redirection
- Set response header
response.setHeader("Location", "redirect network address")
- Abbreviated form of the above combination
response.sendRedirect("redirect network address");
Code demonstration
Access / responseRedirect1Servlet through the browser and perform corresponding business functions by redirecting to / responseRedirect2Servlet
@WebServlet("/responseRedirect1Servlet") public class ResponseRedirect1Servlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle the problem of post request garbled code request.setCharacterEncoding("utf-8"); //Set status code /*response.setStatus(302); //Set response header response.setHeader("Location","/responseRedirect2Servlet");*/ //Redirect shorthand response.sendRedirect("/responseRedirect2Servlet"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
@WebServlet("/responseRedirect2Servlet") public class ResponseRedirect2Servlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle the problem of post request garbled code request.setCharacterEncoding("utf-8"); System.out.println("responseRedirect2Servlet Yes"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
Refresh regularly
Visit the current Servlet, stay for 3 seconds and jump to Baidu
@WebServlet("/refreshServlet") public class RefreshServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle the problem of post request garbled code request.setCharacterEncoding("utf-8"); //Set the response header refresh through response response.setHeader("Refresh","3;https://www.baidu.com"); response.setContentType("text/html;charset=utf-8"); response.getWriter().write("The operation is successful. Jump to Baidu home page in 3 seconds"); // Respond to Chinese data //Specifies how the server response is encoded // response.setCharacterEncoding("UTF-8"); //Unified browser and server coding //response.setContentType("text/html;charset=utf-8"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
File download case
directory structure
Front end code:
<body> <a href="/downLoadServlet?filename=demo.docx">word file</a><br> <a href="/downLoadServlet?filename=girl.jpg">Pretty girl</a><br> <a href="/downLoadServlet?filename=Animals.jpg">Animals</a><br> <a href="/downLoadServlet?filename=test.zip">Compressed package</a><br> </body>
Backend code:
@WebServlet("/downLoadFileServlet") public class DownLoadFileServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle the problem of post request garbled code request.setCharacterEncoding("utf-8"); //Set the code of the corresponding data response.setContentType("text/html;charset=utf-8"); //Get file name String filename = request.getParameter("filename"); //Get the true path of the server file ServletContext servletContext = this.getServletContext(); String realPath = servletContext.getRealPath("/download"+filename); //Create local stream read file FileInputStream fis = new FileInputStream(new File(realPath)); //Gets the true type of the file String mimeType = servletContext.getMimeType(filename); //Set response header response.setHeader("content-type",mimeType); //Know what browser users use String userAgent = request.getHeader("user-agent"); filename = DownLoadUtils.getName(userAgent, filename); //Set to open a file as an attachment response.setHeader("content-disposition","attachment;filename="+filename); //Get byte output stream ServletOutputStream os = response.getOutputStream(); //Read characters. Read one byte at a time int len; byte[] bytes = new byte[1024]; while ((len=fis.read(bytes)) != -1){ os.write(bytes,0,len); } //Release resources os.close(); fis.close(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
Tools for solving garbled code
/* Solve the problem of browser Chinese compatibility */ public class DownLoadUtils { public static String getName(String agent, String filename) throws UnsupportedEncodingException { if (agent.contains("Firefox")) { // Firefox browser //BASE64Encoder base64Encoder = new BASE64Encoder(); Base64.Encoder encoder = Base64.getEncoder(); //filename = "=?utf-8?B?" + encoder.encode(filename.getBytes("utf-8")) + "?="; filename = "=?utf-8?B?" + encoder.encodeToString(filename.getBytes("utf-8")) + "?="; } else { // Other browsers filename = URLEncoder.encode(filename, "utf-8"); } return filename; } }
explain
If the jdk installed on your computer is higher than 1.8, you can directly use the above tools
If the jdk is lower than 1.8, you can use the annotated code and annotate its corresponding code
Interview questions
forword VS redirect
redirect
- The browser access address bar changes
- Resources that can access other sites (servers) (cross domain access)
- Redirection is a two-time request, and the request object cannot be used to share data
- The final response to the browser is determined by the last Servlet
- URL redirection cannot access the resources under the WEB-INF directory
forward
- The forwarding address bar path will not change
- Forwarding can only access the resources under the current server
- Forwarding is a request, and you can use the request object to share data
Usage scenario
- Analyze their characteristics
- forward must be used
If you need to share the data in the same request
To access the resources under the WEB-INF directory - If you want cross domain access, you must use redirect