9 built-in objects for JSPs

Source: Internet
Author: User

9 built-in objects for JSPs

The JSP script contains 9 built-in objects, all of which are instances of the servlet API, which have been initialized by default (the _jspservice () method of the JSP object's servlet to create these instances) and can be directly used

9 built-in objects are
    1. Application
    2. Session
    3. Page
    4. PageContext
    5. exception
    6. Request
    7. Response
    8. Out
    9. Config
The client sends a request to the Web server, and the server requires roughly the following steps:

1. Start a separate thread

2. Using I/O stream to read user request data

3. Parsing parameters from the request data

4. Handling User Requests

5. Generating response data

6. Send the response data to the client using IO

1.2.6 steps can be done by the Web server

3.4.5 There is a difference: The request parameters contained in the different requests are different. So the way users request is handled differently, and the resulting response is different

The Web server invokes the servlet's Jspservice () method to perform the 3.4.5 step, the static content in the JSP page, and the JSP script is converted to the execution code of the Jspservice (), which is responsible for parsing the parameters, processing the request, Response to business functions, the Web server mainly completes the multi-threading, network communication and other underlying functions.

After running to step 3rd, after parsing to the user parameter, you need to create objects such as HttpServletRequest and httpservletresponse with these parameters as arguments to call the _jspservice () method

Both JSPs and Servlets are invoked through a Web server, and JSPs and servlets do not usually call each other, and how do you exchange data between JSPs and Servlets?

So the Web server provides 4 classes similar to the map structure: allowing JSPs and servlets to access data into these 4 classes

    1. Application
    2. Session
    3. Request
    4. Page
The scope of the 4 classes is different

Application: Valid for the entire Web application, the data being stored can be accessed in any JSP or servlet under this application

Request: Valid for this application

Session: Valid for one conversation

Page: Valid for the current page

Application

An instance of Application:javax.servlet.ServletContext that represents the Web application itself that the JSP belongs to

Application usually have two functions:

    • Web App sharing data
    • Accessing configuration parameters for Web Apps

      String Driver = applicatoin.getinitparameter ("Driver");

Config in Web. xml

<context-param>  <param-name>driver</param-name>  <param-value>com.mysql.jdbc.driver</param-value></context-param>
Config object

The Config object is an instance of ServletConfig, which is used to get configuration parameters by Getinitparameter (String paramname)

config.getInitParameter("name");

The Config object represents the configuration information for the current JSP page, but the JSP page generally does not have configuration information because the servlet needs to be configured in Web. XML, so

<servlet>  <init-param>    <param-name>name</param-name>    <param-value>哈哈哈</param-value>  </init-param></servlet>
Exception Object

is an instance of the Throwable object that represents the errors and exceptions generated in the JSP

In a JSP, set this JSP to the exception fetch page iserrorpage= "true" in the command

You can use the exception object:

    • Get exception type Exception.getclass ()
    • Get exception information Exception.getmessage ()
Out Object

The Out object is a page output stream

Pagecontex Object

This object represents the page context and, as long as it is used to access shared data between JSPs, use the PageContext object to access variables of the session,request,page,application scope.

PageContext is an instance of the PageContext class and provides the following two methods to access variables of the Session,request,page,application range

    1. GetAttribute (String name): Gets the Name property of the page range
    2. GetAttribute (String name,int scope): Gets the Name property of the specified range, which can be the following value
      • Pagecontext.page_scope: corresponding PAGE range
      • Pagecontext.request_scope: corresponding REQUEST range
      • Pagecontext.session_scope: corresponding SESSION range
      • Pagecontext.applicatoin_scope: Corresponding application range
    3. Getrequest (): Get Request Object
    4. GetResponse (): Or missing Response object
    5. Getservletconfig (): Get Config Object
    6. Getservletcontext (): Get Application Object
    7. GetSession (): or Missing Session object
Request Object

Reqeust is an example of httpservletrequest

Each Request object encapsulates the user's requests, and all request parameters are encapsulated in the requestor object

以下几个常用方法来获取请求参数:getParameter(String paramName):获取paramName请求参数的值getParameterMap():获取所有的请求参数名和值组成的map对象getParameterNames():获取所有请求参数名所组成的Enumeration对象以下几个常用方法来获取请求头的值:getHeader(String name) :获取指定请求头的值getIntHeader(String name) :获取指定请求头的值并转换成int型

Both the request header and the request parameters are data sent by the user to the server, and the general request header is automatically added by the browser, so a request always contains a number of request headers: The request parameters are usually added by developer control, so the client sends the request parameters in two general cases:

    • Get method Request:

      When you enter a request for an access address directly in the address bar of the browser or submit a form to send a request, the form element of the Forms object does not have the method property set or is set to get. A GET request appends the name and value of a parameter to a URL after a string, and the amount of data transferred by a GET request is generally less than 2KB

    • Post-mode request:

      Usually used to submit a form, you need to set the form element of the method's property value is post, the general post transfer data size is limited by the server, post transfer request parameters and values are placed in the HTML header, in the address bar can not see

Get method Request if non-western characters, such as Chinese, how to obtain:

//获取原始的请求参数String rawName = request.getParameter("name");//将请求参数值使用iso-8859-1字符串分解成字节数组byte[] rawBytes = rawName.getBytes("ISO-8859-1");//将字节数组重新解码成字符串String name = new String(rawBytes,"UTF-8");

If the Post method request contains Chinese:

//设置解码方式,用于中文request.setCharacterEncoding("UTF-8");//下面就可以获得请求参数了
Response Object

For situations where non-character responses need to be produced, you need to use response to respond to client requests. Response is an instance of the HttpServletResponse interface that provides a Getoutputstream () method that returns the output byte stream of the response.

Cases:

通过发送Http头,控制浏览器禁止缓存有多种方式,对应于不同的浏览器器可能会采用不同的方式设定,可以同时使用,达到对所有浏览器都产生作用response.setHeader("pragma","no-cache");response.setHeader("cache-control","no-cache");response.setDateHeader("expires",-1);  //设置有效时间,数字为一个代表时间的long型整数在Servlet中要想操作响应正文,需要通过response对象获取到输出流进行操作response.getWriter();-----ServletOutputStreamresponse.getOutputStreaam();----PrintWriter

Two features of the print stream: Automatic refresh can be set to output information as is

如果操作自定义信息,这时使用字符流 Servlet获取输出流在使用时注意事项:同一时候,只能选择字符流或字节流一种,互相排斥;可以不关闭,由服务器关闭

The servlet can complete the display operation

   代码片段:   response.setHeaader("Content-type","text/html;charset=utf-8");   out.println("<form action="#" method=‘post‘>");响应信息的乱码response.setCharacterEncoding(String code);  //设置响应正文编码 response.setContentType(String mimeType);   //设置响应正文编码,同时告诉浏览器怎样解析response.setHeader("content-Type","text/html;charset=utf-8");

Response redirection

Redirection will lose all of the request parameters and requests range properties because the redirect will produce a second request, not within the same request scope as the previous one HttpServletResponse provides a sendredirect (String path) method, which is used to redirect to the path resource, that is, to redirect the path resource to send the request.

Cookies

To add cookies, you can use the Response object to complete

response.addCookie(Cookie cookie);

Before adding a cookie, you must first create a cookie object:

    • Create a cookie instance, the cookie's constructor is a cookie (String name,string value);
    • Set the life cycle of a cookie
    • Write a cookie to the client

Example://Create a Cookie object cookie cookie = new Cookie ("username", "haha"); Set the life cycle of the cookie cookie.setmaxage (24 * 3600); Add Cookie Object Response.addcookie (cookie) to client;

This cookie will not disappear from the client machine until his life is over, and the cookie must be set to the lifetime of the cookie, or it will disappear as the browser shuts down.

A cookie that wants to access the client can use the request's GetCookie () method, which returns an array of all the cookie elements of the client, traversing each element of the array, and finding the cookie that you want to access.

Cases:

Cookie[] cookies = request.getCookies();for(Cookie c : cookies){    if(c.getName().equals("username")){        out.println(c.getValue());    }}

The cookie value is not allowed to be Chinese characters, if necessary, you can use the Java.net.URLEncoder to encode the string, the encoded result is set to the cookie value.

Cases:

//编码String name = java.net.URLEncoder.encode("猪八戒","utf-8");//创建一个cookie对象Cookie cookie = new Cookie("username",name);//设置cookie的生命周期cookie.setMaxAge(24 * 3600);//向客户端增加cookie对象response.addCookie(cookie);
Session Object

The Session object represents a single user session. A user session means: Starting from the client browser connection to the server, the process is a session until the client browser disconnects from the server. Common terms to determine whether the user login, shopping cart, etc.

Properties within the session range can be shared across multiple page jumps, and once the browser is closed, the seesion ends. The properties in the session will also disappear

The session object is an instance of HttpSession and has two common methods:

setAttribute(String attName,Object attValue):设置session范围内attName属性的值为attValuegetAttribute(String name):返回session范围内attName属性的值

The session mechanism is typically used to hold the client's state information, which needs to be saved to the Web server's hard disk, so the attribute values in the session must be serializable, otherwise the non-serializable exception will be thrown.

The session's property value can be any serializable Java object

9 built-in objects for JSPs

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.