6, JSP built-in objects

Source: Internet
Author: User
Tags sessions

JSP has nine built-in objects:

-request--Request Object
-response--Response Object
-pagecontext--Page Context object
-session--Session Object
-application--Application objects
-out--Output Object
-config--Configuration Object
-page--Page objects
-exception--Exception Object

The out built-in object has a println method that wraps the generated HTML source code, rather than the line break in the browser display, and the line feed <br> label on the browser page

Key built-in objects: Request,session,application

1. Request and response

The "Request" object represents a request from a client, such as information that is filled in form forms, and is the most commonly used object. Its approach uses more getparameter, Getparameternames, and getparametervalues, by calling these methods to get the values of the parameters contained in the Request object.
The "Response" object represents a response to the client, which means that the data sent to the client can be organized through the "Response" object. However, because of the lower level of organization comparison, it is not recommended for ordinary readers to use the "out" object directly when sending text to the client.

For request, its GetParameter method is a special case of the Getparametervalues method, indicating that the requested parameter value is only one, and if there are more than one request parameter value, use the Getparametervalues method. In the case of a multiple-selection box, you need to use the Getparametervalues method to get the values of multiple check boxes that are selected by the user.

For the following page:

<body>
    <form action= "result.jsp" method= "POST" >
    
    	username:<input type= "text" name= "username" ><br>
    	password:<input type= "password" name= "password" ><br>
    	age:<input type= "text" Name= "Age" >
    	age1:<input type= "text" name= "age" >
    	<input type= "Submit" value= "Submit" >
    	<input type= "reset" value= "reset" >
     </form>
  </body>


In result.jsp:

<body>
     <% String username = request.getparameter ("username");
     	String Password = request.getparameter ("password");
     	
     	Out.println ("Username:" + username + "<br>");
     	Out.println ("Password:" + password + "<br>");
     	
     	String[] values = request.getparametervalues ("Age");
     	for (String value:values)
     	{
     		System.out.println (value);
     	}
     	
     	String value1 = Request.getparameter ("Age");
     	System.out.println (value1);
     %>
  </body>


Values are an array of strings that print out the contents of age and Age1, value1 only the first value that matches.

The "Response" object represents a response to the client, which means that the data sent to the client can be organized through the "Response" object. However, because of the way the organization is relatively low-level, so do not recommend the use of ordinary readers, the need to send text to the client directly using the "out" object can be. "Response" is generally used in file downloads.

2, Session object: "Sessions" object on behalf of the server and client-established conversation, when it is necessary to keep the customer information in different JSP pages use, such as online shopping, customer tracking, such as track.

-HTTP is a stateless (stateless) protocol; The WEB server has no historical memory for each client request; session is used to save client state information

Three JSP pages demonstrate delivery of session values:

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

3, Application Object--responsible for providing the application in the server runtime some of the global information, commonly used methods are getmimetype and Getrealpath, etc.
4, out: The "Out" object represents the object to send data to the client, unlike the "Response" object, the content sent through the "out" object will be the browser needs to display the content, is the text level, you can through the "out" Object directly to the client to write an HTML file dynamically generated by the program. Common methods include clear, Clearbuffer, flush, getbuffersize, and getremaining, in addition to print and println, because the "Out" object contains a buffer inside. So you need some way to manipulate the buffer.

5, Config Object--provides some configuration information, commonly used methods are Getinitparameter and getinitparameternames, to obtain the servlet initialization parameters.

Page Object-Represents a running class object generated by a JSP file and is not recommended for use by the general reader.

Exception Object-Represents the exception object that is generated by the JSP file runtime, which cannot be used directly in a generic JSP file, but only in a JSP file that uses the "<%@ page iserrorpage=" true "%>".

6, request, session, application comparison

1 Request object: GetAttribute, returns the attribute value of the attribute name in the form of an object. Returns null if the attribute of the given name does not exist; SetAttribute, set

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


For request2.jsp, if you use <a href= "request3.jsp" > click on the link, request3.jsp displays NULL if request2.jsp uses <jsp:forward page= " Request3.jsp> This is a request forwarding, request3.jsp will display the name entered in request1.jsp. Mainly to see if it was in one request.

The request GetParameter is the client requests the information, GetAttribute is the server side previously through setattribute set of information, completely is the server side thing.

GetAttribute and SetAttribute methods generally appear in pairs, first by setting the property and property values by the SetAttribute method, The GetAttribute method is then used to get the value of the object corresponding to the property by the property (after fetching, the property value is converted to a true object) by a downward type conversion. Both the setattribute and GetAttribute methods are executed internally on the server side, and the client does not know whether the server side has executed the two methods;

The purpose of the GetParameter method of request is to obtain the parameter values sent by the client via the form or URL request parameters, which is the interaction between the client and the server, and the server side wants to obtain the data sent by the client, it needs to use the GetParameter method. There is no Setparameter method corresponding to the GetParameter method.

The data within the request object is within the scope of the request object's survival, when the client sends a request to the server, the server returns a response to the client, the request object is destroyed, and when a new request is sent to the server side, The server creates a new request object that has nothing to do with the previous request object and therefore does not have access to any data that existed in the previous request object.

2 The Session object also has the GetAttribute and the SetAttribute method, the data survival scope is the survival scope of the sessions object (as long as the browser does not close, the session object will always exist), So in the same browser window, no matter how many requests are sent to the server side, the session object has only one

3 Application objects also have GetAttribute and SetAttribute methods, Application Application object: The object with the largest survival scope, as long as the server is not closed, the data in the Application object will always exist, During the entire server run,there is only one Application object .

4. Requests, sessions, and application The scope of these 3 objects is increased one after another: request is only within the scope of a claim, the session is within the scope of the browser window, and application is in the process of running the entire server.

Using application to write Web counters:

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


7, about <jsp:formard> conversion to servlet, is the use of the Pagecontext.forward method for request forwarding

Use the servlet to complete the Jsp:forward function:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  


Servlet

Import java.io.IOException;

Import Javax.servlet.RequestDispatcher;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Myforwardservlet extends HttpServlet
{
	@Override
	protected void doget (HttpServletRequest req , HttpServletResponse resp)
			throws Servletexception, IOException
	{
		String username = Req.getparameter (" Username ");
		
		Req.setattribute ("username", username);
		RequestDispatcher rd = Req.getrequestdispatcher ("myresult.jsp");
		Rd.forward (req, resp);
	}


<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 


The main use of setattribute in the servlet is to set the parameters that pass through the client and then query the database for data, and then deliver it to the next page:

Import java.io.IOException;
Import java.util.ArrayList;
Import java.util.List;

Import Javax.servlet.RequestDispatcher;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Myforwardservlet extends HttpServlet
{
	@Override
	protected void doget (HttpServletRequest Req, HttpServletResponse resp)
			throws Servletexception, IOException
	{
		String username = Req.getparameter ("username");
		
		Req.setattribute ("username", username);
		
		list<string> list = new arraylist<string> ();
		for (int i = 0;i < 100;i++)
		{
			List.add (string.valueof (i));
		}
		Req.setattribute ("list", list);
		RequestDispatcher rd = Req.getrequestdispatcher ("myresult.jsp");
		Rd.forward (req, resp);
	}

8, some methods of application (application is ServletContext object): Getmajorversion, Getminorversion, GetResource, getrealpath-- Use more, return the absolute path of the resource

9, about <input type= "hidden" > in the transfer of information between different pages, usually use the hidden tag, rather than using the session to save, because session comparison consumes memory.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.