Nine built-in objects of JSP in JavaWeb

Posted by StormTheGates on Wed, 02 Feb 2022 19:10:02 +0100

3, Nine built-in objects of JSP

What are built-in objects?
The built-in objects of JSP refer to the built-in Java objects in the JSP page system by default. These objects can be used without explicit declaration by developers. In JSP pages, you can access each other with JSP pages and Servlet environment by accessing JSP built-in objects. Each internal object has a corresponding Servlet API type.

3.1 out object

  • Function of out object
    The Out object is javax servlet. jsp. An instance of the jspwriter class, which is mainly used to output data to the client browser;
    When using the out object to output data, you can operate on the data buffer, clear the residual data in the buffer in time, and make room for other outputs. After the data is output, you should close the output stream in time.

  • Common methods for out objects

    Method namedescribe
    void print()Output data without line breaks.
    void println()Output data and line feed (but the browser does not recognize this line feed character at present. If you want the browser to display line feed, you should write * * < br > * * to the browser to line feed).
    void newLine()Output a newline character.
    void flush()Data in the output buffer.
    void close()Close the output stream.
    void clear()Clear the contents of the buffer and do not send data to the client.
    void clearBuffer()After sending the data to the client, clear the contents of the buffer.
    int getBufferSize()Gets the size of the buffer.
    void getRemaning()Gets the size of unused space in the buffer.
    public boolean isAutoFlush()Gets the AutoFlush value set with <% @ page is AutoFlush = "true/false"% >.
    <%
        out.print("This is the login page!");
        out.println();//Indicates line feed. Line feed is not displayed in the page, but only line feed 1 is displayed in the source code
        out.print("println()Back page!");
        out.newLine();//Indicates that a newline character is output, and the newline is still in the source code!
        out.print("newLine()Back page");
        out.print("</br>br Page after line break");//At present, only br line breaks work on the page!
        out.print("</br>call clearBuffer front");
        out.flush();
        out.clearBuffer();
        out.print("</br>call clearBuffer after");
        out.print("</br>call clear front");
        out.flush();
        /**
         * flush()Error reporting when used with clear():
         * The reason for the error is that both have the ability to empty the buffer at the same time. When clear() is used after flush(),
         * This will cause the buffer to be emptied twice, resulting in the invalidation of the clear() method, so an error is reported.
         */
        out.clear();//At this point, an error occurs when calling clear()
        out.print("</br>call clear after");
    %>
    

    Tips:

    1. Avoid calling methods that are easy to throw exceptions (close() and flush() followed by clear() method). The reason for the error is that both methods have the ability to empty the buffer at the same time. When clear() or close() is used after flush(), it will cause the buffer to be emptied twice, resulting in the invalidity of clear() or close() methods, so an error is reported.
    2. Before the data is emptied, calling the close() method halfway will cause data loss and cause exceptions. At this time, we need to call the flush() method to force all the data to be output, so as to empty the buffer, and finally call the close() method to close the output stream.

3.2 request object

  • Function of request object

    • The request object is javax servlet. An object of type HttpServletRequest.
    • This object represents the request information of the client and is mainly used to accept the data transmitted to the server through HTTP protocol. (including header information, system information, request mode, request parameters, etc.).
    • The scope of the request object is one request.
  • Common methods of request object

    Method namedescribe
    object getAttribute()Returns the property value of the specified property
    void setAttribute()Set the property value of the property
    String getParameter()Returns the parameter value of the specified parameter
    String getParameterValues()Returns an array of all values containing parameters
    String getMethod()Return submission method
    Enumeration getAttributeNames()Returns an enumeration of all available property names
    Enumeration getParameterNames()Returns the names of all available parameters of the enumeration
  • Use of common methods of request

    <body>
    	Requested URL address: <%=request.getRequestURI() %><br>
    	Agreement name: <%=request.getProtocol() %><br>
    	The path to the server file requested by the client: <%=request.getServletPath() %><br>
    	/**
    	*url The query part of refers to the parameters after this link
    	*http://localhost:8080/ebuy/index.jsp?id=1&&name=z
    	**/
    	URL Query part of: <%=request.getQueryString() %><br>
    	Name of the server: <%=request.getServerName() %><br>
    	Server slogan: <%=request.getServerPort() %><br>
    	Remote client IP address: <%=request.getRemoteAddr()%><br>
    	Get the address of the requesting client: <%=request.getRequestURI()%><br>
    	Submission method: <%=request.getMethod() %><br>
    	Requested URL address: <%=request.getRequestURI() %><br>
    </body>
    

  • Enumeration getAttributeNames(): we can use req The getparameter () method obtains the value in the input box, but when there are countless input boxes, it is obvious that the efficiency of obtaining one by one is very slow. At this time, we can use req Getparametermap () method to get a set of values in the input box, and then traverse the set to get each value.
/**
* We can use req The getparameter () method gets the value in the input box, but!
* When there are countless input boxes, it is obvious that the efficiency of acquiring one by one is very slow. At this time, we can
* req.getParameterMap()Method to get the value set in an input box, and then traverse the set to get each value.
*/
Map<String,String[]> map = req.getParameterMap();
for (String key:map.keySet()){
   System.out.println(key+"-------"+req.getParameter(key));
}

  • Forwarding and redirection

    • Forwarding: page Jump by the server.
    req.getRequestDispatcher("/address").forward(req,resp): 
    


    Forwarding features:

    1. The address bar does not change and displays the address of the previous page;
    2. Number of requests: only one request;
    3. Root directory: http://localhost:8080/ Project address /, including the access address of the project;
    4. Data in the request domain will not be lost.
    • Redirection: page Jump by browser.
    response.sendRedirect("/address");
    


    Features of redirection:

    1. The address bar displays the new address;
    2. Number of requests: twice;
    3. Root directory: http://localhost:8080/ No project name;
    4. Data in the request domain is lost because two requests have occurred.

    Difference between redirection and forwarding:

    differenceforward()Redirect sendRedirect()
    root directoryInclude project access addressNo project access address
    Address barWill not changeWill change
    Where to jumpServer side jumpJump on browser side
    Request data in domainNot lostWill be lost

    Tips:

    1. When to use forwarding and redirection?
      If it is required to retain the data in the request domain in the future, use forwarding, otherwise use redirection;
      In the future, access the database, add, delete, change, use redirection, and query, use forwarding.
    2. Will the subsequent code forwarded or redirected still run?
      Subsequent code is executed regardless of forwarding or redirection.
  • Chinese garbled code in request

    • Submit data in get mode
    <%
    	//Read user name and password
    	String name = request.getParameter("name");
    	//Character encoding of request data
    	name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
    %>
    
    • Submit data by post
    //Set the character encoding of the read request information to utf-8
    request.setCharacterEncoding("utf-8");
    //Read user name and password
    String name = request.getParameter("name");
    String pwd = request.getParameter("pwd");
    

3.3 response object

  • response object
    The response object is used to respond to customer requests and return information to the client. Response is a servlet A parameter of the service method, of type javax servlet. http. HttpServletResponse. When the client sends out each request, the server will create a response object and pass it to the servlet service() method. The response object is used to respond to the client, which shows that using the response object in the service () method can complete the response to the client.

  • Function of response object

    Method namedescribe
    void addCookie()Add a Cookie object.
    void setContentType()Change the property value of contentType.
    void addHeader()Add http header.
    boolean containsHeaderDetermine whether the http file header exists.
    void flushBuffer()Force the contents of the current buffer to be sent to the client.
    void setHeader()Set its value according to the name of the http header file.
    void setIntHeader()Set its value according to the name of the http file header.
    void sendError()Transmit status code and error message.
    void sendRedirect()Page redirection is used to realize page Jump.
    //Corresponding header file type
    resp.setContentType("text/html;charset=utf-8");
    resp.setContentType("application/json;charset=utf-8");
    PrintWriter out = resp.getWriter();
    //Only Firefox browser can directly recognize json data format
    out.println("{\"id\":\"1\",\"name\":\"zs\"}");
    
  • JSON data format

    public static void main(String[] args) {
        /**
         * map aggregate
         */
        Map<Object,Object> map = new HashMap<>();
        map.put("id","1");
        map.put("name","zs");
        System.out.println("map Set:"+JSON.toJSON(map));
        /**
         * list aggregate
         */
        List list = new ArrayList();
        list.add("1");
        list.add("2");
        System.out.println("list Set:"+list);
        /**
         * object
         */
        User user = new User();
        user.setUserId("1");
        user.setUserName("Zhang San");
        user.setPassword("123654");
        user.setEmail("15234152@qq.com");
        System.out.println("User Object:"+JSON.toJSON(user));
        /**
         * Add multiple objects to the collection and output them in json format
         */
        User user2 = new User();
        user2.setUserId("2");
        user2.setUserName("Li Si");
        user2.setPassword("74589654");
        user2.setEmail("74585965@163.com");
        list.add(user);
        list.add(user2);
        System.out.println("For multiple objects JSON Output:"+JSON.toJSON(list));
    }
    

3.4 session object

  • Role of session object
    Session is used to store the session between the user and the web server, that is, the storage space opened up by the server for the client.

    • What is conversation?
      A session is a call between the browser and the server.

    • Why use session?
      In order to make up for the shortcomings of HTTP protocol. HTTP protocol is stateless. It cannot save the user who visited the page last time. Of course, it cannot conduct one-to-one communication with the user. The session can save the user's information and interact with IE.

  • Principle of session object
    The principle of session object is that the server can create and maintain a session object for the client to store data. When creating a session object, the server will generate a unique number sessionID for the object. The server stores the sessionID in the client as a cookie. When the browser accesses the server again, it will bring the sessionID to the server as Cookie information. The server can retrieve and access the previous session object through the sessionID.

    be careful:
    Only one session ID is saved in the cookie, while relatively more session data is saved in the session object corresponding to the server and maintained by the server. This ensures the security of session data to a certain extent, but increases the memory overhead of the server.

  • Lifecycle of session object

    The session is stored in the memory of the server (for high-speed access).

    • When does the session take effect?
      Session is created when the user accesses the server for the first time. It should be noted that only JSP, Servlet and other programs will create a session. Accessing only static resources such as HTML and IMAGE will not create a session. You can call request Getsession (true) forces the generation of a session.

    • When does the session expire?
      1. The server will clear the session that has not been active for a long time from the server memory. At this time, the session will become invalid. The default expiration time of session in Tomcat is 20 minutes.
      2. Call the invalidate method of the session.

      HttpSession session = request.getSession();
      session.invalidate();//Log off all session s of the request
      
    1. When is the expiration time of the session calculated? Is it calculated from the moment you log in or from the moment you stop activity?
      The expiration time of a session is calculated from the time when the session is inactive. If the session is always active, the session will never expire;
      The timing starts when the session is not accessed. Once the session is accessed, the timing is cleared.

    2. Set the expiration time of the session
      (1) web. In XML

      <session-config>
      	<session-timeout>30</session-timeout>
      </session-config>
      

      (2) Set manually in the program

      session.setMaxInactiveInterval(30*60);//Set the unit to seconds and - 1 to never expire
      request.getSession().setMaxInactiveInterval(-1);//Set never to expire
      

      (3) tomcat can also modify the session expiration time in the server When defining context in XML, the following definitions are adopted:

      <Context path="/livsorder" 
      docBase="/home/httpd/html/livsorder"   defaultSessionTimeOut="3600" 
      isWARExpanded="true"   
      isWARValidated="false" isInvokerEnabled="true"   isWorkDirPersistent="false"/>
      

      Tip: in one of the following four cases, the session will fail

      1. The user closes the browser currently in use;
      2. Shut down the web server;
      3. The user does not make a request to the server for more than the preset time;
      4. Run the program to end the session.
        Note: when the browser is closed, it will not send information to the server. All session data associated with this session will not be deleted immediately. It will be deleted only when the session supermarket is known. When the user opens the browser again, the server cannot associate the new request with the previous session, and will create a new session at a time.
  • Common methods of session object

    Method namedescribe
    String getId()Returns the unique ID number when the session was created
    long getCreationTime()Return the session creation time
    long getLastAccessedTime()Returns the last request time of this session
    void invalidate()Cancel the session and make the session unavailable
    object getAttribute()Extracts the specified object from the session object
    void setAttribute()Add object to session object
    void removeAttribute()Deletes the specified object from the session object
    void setMaxInactiveInterval()Set the living space of the session object
    boolean isNew()Determine whether it is a new user
    /**
    * Servlet Request page
    */
    protected void login(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
        HttpSession session = req.getSession();
        String username = req.getParameter("userName");
        String password = req.getParameter("passWord");
        session.setAttribute("username",username);
        session.setAttribute("password",password);
        resp.sendRedirect("index.jsp");
    }
    /**
    * index.jsp page
    */
    <%
        out.println("</br>");
        out.println("</br>");
        out.println("user name:"+session.getAttribute("username"));
        out.println("password:"+session.getAttribute("password"));
        out.println("</br>");
        out.println("return session Unique when created ID: "+session.getId());
        out.println("</br>");
        out.println("return session Created on:"+session.getCreationTime());
        out.println("</br>");
        out.println("Return to this session Last request time:"+session.getLastAccessedTime());
        out.println("</br>");
        out.println();
    %>
    


3.5 application object

  • Role of application object

    • Application object: when the Web server starts, the Web server will automatically create an application object. Once the application object is created, it will exist until the Web server is shut down.
    • A Web server usually has multiple Web service directories (websites). When the Web server starts, it automatically creates an application object for each Web service directory. These application objects are independent and correspond to the Web service directory one by one.
    • Customers accessing the same website share an application object. Therefore, the application object can realize data sharing among multiple customers and store global variables. Customers visiting different websites have different application objects.
  • Lifecycle of application object
    Start from the Web server until the Web server shuts down.

    be careful:
    After a Web application is started, an application object will be automatically created, and there is only one application object during the operation of the whole application, that is, all customers accessing the website share one application object.

  • Scope of application object
    Application object is an application level object, which acts on the current Web application, that is, the current website. All customers accessing the current website share an application object.
    Specifically, no matter which customer visits website A or which page file under website A, the application object of website A can be operated, because all customers visiting website A share one application object.
    Therefore, when data is stored in the application object, all customers visiting website A can access it, realizing data sharing among multiple customers.

  • Common methods of application object

    Method namedescribe
    Object getAttribute()Get the specified object from the application
    void setAttribute()Save the specified object in the application
    String getRealPath()Returns the real path of the specified virtual path
    void removeAttribute()Delete the specified object from the application
    String getServerInfo()Return JSP(SERVLET) engine name and version number
    <body>
    	JSP(SERVLET)Engine name and version number:
    	<%=application.getServerInfo()%><br>
    	Server supported Server API Maximum version number of:
    	<%=application.getMajorVersion ()%><br>
    	Server supported Server API Minimum version number of:
    	<%=application.getMinorVersion ()%><br>
    	Specify the of resources (files and directories) URL route:
    	<%=application.getResource("index.jsp")%><br>
    	return Test.jsp Real path of virtual path:
    	<%=application.getRealPath("index.jsp")%>
    </body>
    

  • Application simple application - site counter

    <body>
    <%
        //Get the value of num object
        Object num = application.getAttribute("num");
        //The initial value is set to 0
        if (num == null){
            application.setAttribute("num","0");
        }
        String nums = (String) application.getAttribute("num");
        //Increment the value of num by 1 for each access
        int n = Integer.parseInt(nums)+1;
        //Assign the accumulated value to the num object
        application.setAttribute("num",String.valueOf(n));
    %>
    The number of visits is:<%=n%>
    </body>
    



3.6 page object

page is Java An instance of lang.Object class, which refers to the instance of JSP implementation class, that is, it is JSP itself. It is equivalent to this object of servlet class after JSP compilation generates servlet, which is rarely used in practice.
Page scope refers to the scope of this JSP page.

3.7 pageContext object

pageContext object provides access to all objects of JSP page. The method of pageContext object can access 8 JSP internal objects except itself. pageContext object is equivalent to the integrator of all object functions in JSP program. However, the other eight built-in objects can also be accessed directly, so pageContext objects are rarely used.

3.8 config object

The config object represents the current JSP configuration information, but JSP pages usually do not need to be configured, so there is no configuration information. This object is rarely used in JSP pages, but it is relatively useful in servlets. Because the servlet needs to be configured on the web XML file, you can specify configuration parameters.

3.9 exception object

  • Function of exception object
    The exception object hi is specially responsible for handling the exception problems that occur during the execution of JSP. However, it should be noted that the exception object should generally be used together with the page instruction. It can only be used in the exception handling page (the page with isErrorPage=true in the page instruction). All errors and exceptions occurring during the execution of JSP files are concentrated in the exception handling page. This not only improves the unity of the system, but also makes the program flow simpler and clearer.

  • Common methods of exception object

    Method namedescribe
    String getMessage()Returns a message describing the exception
    String toString()Returns tip description information about the exception
    void printStackTrace()Display exceptions and their stack tracks
    Throwable FillInStackTrace()Rewrite the execution stack trace of the exception
  • be careful

    <%@ page import="cn.ebuy.pojo.User" isErrorPage="true" errorPage="error.jsp" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <body>
    	<%
    	    User user = (User) session.getAttribute("users");
    	    if(user == null){
    	        response.sendRedirect("login.jsp");
    	    }
    	%>
    	
    	user name=<%=user.getUserName()%>
    </body>
    

    be careful:
    When users do not log in, they can directly access index JSP page
    Null pointer error will be reported when: isErrorPage = "true" errorPage = "error.jsp" is not added to the page!
    If it is not added, the error handling file will be treated as a normal file. In this case, if the server side makes an error, the returned status code should be "500". However, because the error goes to the error handling page and returns the error page to the client side as a normal page, the returned http status code becomes 200, In this way, the client can't find the problem.
    After adding isErrorPage="true", the error handling page will be treated as an error page, and the returned status code "500" will be returned to the client intact, which is conducive to the client to find problems.

Topics: Java Session request application response