Home > Java > javaTutorial > javaweb learning and finishing--HttpServletResponse object

javaweb learning and finishing--HttpServletResponse object

php是最好的语言
Release: 2018-08-09 10:40:39
Original
1825 people have browsed it

1. Common applications of HttpServletResponse - generating verification codes

1.1. Generate random pictures to be used as verification codes

Generation The picture mainly uses a BufferedImage class,

 javaweb learning and finishing--HttpServletResponse object

Generate a random picture example:

package gacl.response.study;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseDemo03 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setHeader("refresh", "5");//设置refresh响应头控制浏览器每隔5秒钟刷新一次
        //1.在内存中创建一张图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //2.得到图片
        //Graphics g = image.getGraphics();
        Graphics2D g = (Graphics2D)image.getGraphics();
        g.setColor(Color.WHITE);//设置图片的背景色
        g.fillRect(0, 0, 80, 20);//填充背景色
        //3.向图片上写数据
        g.setColor(Color.BLUE);//设置图片上字体的颜色
        g.setFont(new Font(null, Font.BOLD, 20));
        g.drawString(makeNum(), 0, 20);
        //4.设置响应头控制浏览器浏览器以图片的方式打开
        response.setContentType("image/jpeg");//等同于response.setHeader("Content-Type", "image/jpeg");
        //5.设置响应头控制浏览器不缓存图片数据
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        //6.将图片写给浏览器
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    /**
     * 生成随机数字
     * @return
     */
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999)+"";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length(); i++) {
            sb.append("0");
        }
        num = sb.toString()+num;
        return num;
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
Copy after login

The running results are as follows : javaweb learning and finishing--HttpServletResponse object

2. Common applications of HttpServletResponse - setting response headers to control browser behavior

2.1. Setting http response headers to control browsers from caching the current document content

 response.setDateHeader("expries", -1);
 response.setHeader("Cache-Control", "no-cache");
 response.setHeader("Pragma", "no-cache");
Copy after login

2.2. Set the http response header to control the browser to refresh the web page regularly (refresh)

response.setHeader("refresh", "5");//设置refresh响应头控制浏览器每隔5秒钟刷新一次
Copy after login

2.3. Implement request redirection through response

Request redirection refers to: a After the web resource receives the client request, it notifies the client to access another web resource. This is called request redirection.

Application scenario: User logs in. The user first visits the login page. After successful login, he will jump to a certain page. This process is a process of request redirection

Implementation Method: response.sendRedirect(String location), that is, calling the sendRedirect method of the response object to implement request redirection
The internal implementation principle of sendRedirect: Use response settings302 status code and settings Location response header implements redirection

For example:

package gacl.response.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseDemo04 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * 1.调用sendRedirect方法实现请求重定向,
         * sendRedirect方法内部调用了
         * response.setHeader("Location", "/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
         * response.setStatus(HttpServletResponse.SC_FOUND);//设置302状态码,等同于response.setStatus(302);
         */
        response.sendRedirect("/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
        
        //2.使用response设置302状态码和设置location响应头实现重定向实现请求重定向
        //response.setHeader("Location", "/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
        //response.setStatus(HttpServletResponse.SC_FOUND);//设置302状态码,等同于response.setStatus(302);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
Copy after login

3. Recommended way to write URL address in web project

In JavaWeb development, as long as it is When writing a URL address, it is recommended to start with "/", that is, use an absolute path. So what does this "/" represent? You can remember "/" in the following way: If "/" is used for the server, it represents the current web project. If "/" is used for the browser, it represents the webapps directory.

3.1, "/" represents the common application scenarios of current web project

① .ServletContext.getRealPath(String path) gets the absolute path of the resource

/**
* 1.ServletContext.getRealPath("/download/1.JPG")是用来获取服务器上的某个资源,
* 那么这个"/"就是给服务器用的,"/"此时代表的就是web工程
 * ServletContext.getRealPath("/download/1.JPG")表示的就是读取web工程下的download文件夹中的1.JPG这个资源
* 只要明白了"/"代表的具体含义,就可以很快写出要访问的web资源的绝对路径
*/
this.getServletContext().getRealPath("/download/1.JPG");
Copy after login

②. Forward to other pages on the server side

 /**
 * 2.forward
  * 客户端请求某个web资源,服务器跳转到另外一个web资源,这个forward也是给服务器用的,
 * 那么这个"/"就是给服务器用的,所以此时"/"代表的就是web工程
 */
 this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
Copy after login

③. Use the include directive or the tag to introduce the page

 <%@include file="/jspfragments/head.jspf" %>
Copy after login
<jsp:include page="/jspfragments/demo.jsp" />
Copy after login

At this time, "/" represents the web project.

3.2, "/" represents common application scenarios of webapps directory

①.Use sendRedirect to implement Request redirection

response.sendRedirect("/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
Copy after login
Copy after login

The server sends a URL address to the browser. After the browser gets the URL address, it then requests the server, so this "/" is for the browser to use. At this time" /" represents the webapps directory, "/JavaWeb_HttpServletResponse_Study_20140615/index.jsp" this address refers to "webapps\JavaWeb_HttpServletResponse_Study_20140615\index.jsp"

 response.sendRedirect("/project name/folder Directory/Page");This way of writing is to write the project name firmly in the program. It is inflexible. If the project name changes one day, the program will have to be changed at this time, so it is recommended to use the following flexible writing method. :

Change

response.sendRedirect("/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
Copy after login
Copy after login

This way of writing is changed to

response.sendRedirect(request.getContextPath()+"/index.jsp");
Copy after login

The content obtained by request.getContextPath() is "/JavaWeb_HttpServletResponse_Study_20140615", which is more flexible. Use request.getContextPath() instead of "/project name", it is recommended to use this method, it is flexible and convenient!

②.Use hyperlink to jump

<a href="/JavaWeb_HttpServletResponse_Study_20140615/index.jsp">跳转到首页</a>
Copy after login

This is the hyperlink jump used by the client browser. This "/" is for the browser to use. At this time "/" represents the webapps directory.

Use hyperlinks to access web resources. It is recommended to use the following writing method to improve the absolute path:

<a href="${pageContext.request.contextPath}/index.jsp">跳转到首页</a>
Copy after login

This way you can avoid the name of the project appearing in the path. Use ${pageContext.request.contextPath}Replaces "/JavaWeb_HttpServletResponse_Study_20140615"

③.Form form submission

<form action="/JavaWeb_HttpServletResponse_Study_20140615/servlet/CheckServlet" method="post">    
         <input type="submit" value="提交">
 </form>
Copy after login

This It is the client browser that submits the form to the server, so this "/" is used by the browser. At this time, "/" represents the webapps directory.

Regarding the writing of the absolute path of the action attribute in form form submission, it is also recommended to use the following method to improve:

<form action="${pageContext.request.contextPath}/servlet/CheckServlet" method="post">
          <input type="submit" value="提交">
 </form>
Copy after login

 ${pageContext.request.contextPath} gets "/JavaWeb_HttpServletResponse_Study_20140615"

  ${pageContext.request.contextPath}的效果等同于request.getContextPath(),两者获取到的都是"/项目名称"

④.js脚本和css样式文件的引用

<%--使用绝对路径的方式引用js脚本--%>
  <script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"></script>
  <%--${pageContext.request.contextPath}与request.getContextPath()写法是得到的效果是一样的--%>
  <script type="text/javascript" src="<%=request.getContextPath()%>/js/login.js"></script>
  <%--使用绝对路径的方式引用css样式--%>
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/index.css" type="text/css"/>
Copy after login

综合范例:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>



  
    "/"代表webapps目录的常见应用场景
    <%--使用绝对路径的方式引用js脚本--%>
    
    <%--${pageContext.request.contextPath}与request.getContextPath()写法是得到的效果是一样的--%>
    
    <%--使用绝对路径的方式引用css样式--%>
      
  
  
  
      <%--form表单提交--%>
       
<%--超链接跳转页面--%> <a href="${pageContext.request.contextPath}/index.jsp">跳转到首页</a>
Copy after login

 四、response细节问题

  getOutputStream和getWriter方法分别用于得到输出二进制数据、输出文本数据的ServletOuputStream、Printwriter对象。
  getOutputStream和getWriter这两个方法互相排斥,调用了其中的任何一个方法后,就不能再调用另一方法。  
  Servlet程序向ServletOutputStream或PrintWriter对象中写入的数据将被Servlet引擎从response里面获取,Servlet引擎将这些数据当作响应消息的正文,然后再与响应状态行和各响应头组合后输出到客户端。 
  Serlvet的service方法结束后,Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果没有,Servlet引擎将调用close方法关闭该输出流对象。

相关推荐:

strust2 获取HttpServletResponse对象

菜菜菜鸟学习之JavaWeb 入门1(自己的学习理解,不对之处请大神们多多指教啊)

The above is the detailed content of javaweb learning and finishing--HttpServletResponse object. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template