Java basics-JSP (2), java basics jsp

Source: Internet
Author: User

Java basics-JSP (2), java basics jsp

1. JSP implicit object Overview

To simplify the compilation of jsp expressions and script snippet code, JSP provides a total of nine pre-defined variables, also known as implicit objects or built-in objects.

The Servlet Source code generated by jsp contains the following declaration:

Public void _ jspService (final javax. servlet. http. httpServletRequest request, final javax. servlet. http. httpServletResponse response) throws java. io. IOException, javax. servlet. servletException {// the built-in object final javax is declared here. servlet. jsp. pageContext pageContext; javax. servlet. http. httpSession session = null; final javax. servlet. servletContext application; final javax. servlet. servletConfig config; javax. servlet. jsp. jspWriter out = null; final java. lang. object page = this; javax. servlet. jsp. jspWriter _ jspx_out = null; javax. servlet. jsp. pageContext _ jspx_page_context = null; // some built-in objects are initialized here. try {response. setContentType ("text/html; charset = UTF-8"); pageContext = _ jspxFactory. getPageContext (this, request, response, "err_page.jsp", true, 8192, true); _ jspx_page_context = pageContext; application = pageContext. getServletContext (); config = pageContext. getServletConfig (); session = pageContext. getSession (); out = pageContext. getOut (); _ jspx_out = out; out. write ('\ R'); out. write ('\ n ');....}

Eight built-in objects can be found here, and an exception is returned.

This object is available only on a page dedicated for error handling. Set the page as an error page: <% @ page isErrorPage = "true" %>, in the above _ jspService method, an exception object is added, and Throwable exception = org. apache. jasper. runtime. jspRuntimeLibrary. getThrowable (request );

* A total of nine built-in objects

// Nine built-in objects 1. request // response // pageContext4.application // ServletContext5.session // HttpSession6.page // Object7.out // JspWriter8.exception // Throwable9.config // ServletConfig

1. request object // HttpServletRequest

* Request method for obtaining request Parameters

-- String getParamter (String name)

-- Enumeration getParameterNames (); // obtain the names of all Request Parameters

-- String [] getPrameterValues (String name); // obtain all values with the same name

Public class StrUtil {public static String linkListSql (String [] list) {String str = "("; for (int I = 0; I <list. length; I ++) {if (I <list. length-1) {str + = list [I] + "," ;}else {str + = list [I] ;}} str + = ")"; return str ;}}// in dao: public int delUsers (String [] idList) {String SQL = "delete from userInfo where id in" + StrUtil. linkListSql (idList); System. out. println (SQL); return DBUtil. update (SQL, null );}

-- Map getParameterMap () // obtain a Map

public void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {        Map<String,String[]> map =request.getParameterMap();                                    Set<Map.Entry<String,String[]>> entrySet=map.entrySet();    Iterator<Map.Entry<String, String[]>> it=entrySet.iterator();                while(it.hasNext()){            Map.Entry<String, String[]> item=it.next();            System.out.println(item.getKey()+":");            String [] valueList=item.getValue();            for(int i=0;i<valueList.length;i++){                System.out.println(valueList[i]);            }                System.out.println("--------");            }    }

2. request Method for obtaining the request Header

-- GetHeader (String name) // obtain the content based on the name of the Request Header

-- Enumeration getHeaderNames () // get all request header names

-- Int getIntHeader (String name) // obtain the integer header Based on the name.

-- Cookie [] getCookies () // obtain all cookies related to the Request Header

Enumeration  headList =request.getHeaderNames();    while(headList.hasMoreElements()){    String headerName=headList.nextElement().toString();    System.out.println(headerName+":");    System.out.println(request.getHeader(headerName));    System.out.println("----");        }

* Request

String getContextPath () // obtain the Context path ---/show-admin-mvc

String getMethod () // GET Http method (GET, POST) -- GET

String getProtocol () // obtain the used protocol (HTTP/1.1, HTTP/1.0) -- HTTP/1.1

String getQueryString () // obtain the request's parameter String, but the HTTP method must be GET -- userName = f e = f & password = f e = f

String getRequestSessionId () // obtain the SessionId of the Client

String getRequestURI () // get the request URL, but do not include the parameter String -- UserWeb/Test. jsp

String getRemoteAddr () // It is useful to obtain the user's IP address.

String getRemoteHost () // obtain the user's host name

Int getRemotePort () // obtain the user's host port

String getRemoteUser () // get the user name

Void setCharacterEncoding (String encoding) // sets the encoding format to solve the problem of passing Chinese characters on the page.

3. response object

Return the result of processing jsp data to the client. This object implements the javax. servlet. http. HttpServletResponse interface.

* Method for setting the Response Header

Void addCookie (Cookie cookie)

Void addDateHeader (String name, long date)

Void addHeader (String name, String value );

Void addIntHeader (String name, int value );

Void setHeader (String name, String value );

* How to set the response status code

Void sendError (int SC); pass status code)

Void sendError (int SC, String msg) Transfer status code and error message // response. sendError (404, "Haha, error, active gai ");

Void setStatus (int SC) Status Code

* Redirection Method

SendRedirect (String url );

4. session Object

Implement the javax. servlet. htt. HttpSession Interface

SetAttribute (String name, Object obj );

Long getCreationTime () indicates the time when the Session is generated, in milliseconds, starting from on January 1, January 1, 1970.

String getId () // obtain the Session Id

Long getLastAccessedTime () is the last time the Session is sent.

Void invalidate () cancels the session object and releases the content it stores

Boolean isNew () determines whether the Session is new (generated by the server, but not used by the client)

Void setMaxInactiveInterval (int interval) expiration time, in seconds

5. application Object

Implement the javax. servlet. ServletContext Interface

After the server is started, it generates

* Container-related information

Int getMajorVersion () // get the main Servlet API version of the iner -- 2

Int getMinorVersion // get version

String getServerInfo () // obtain the name and version of the Container.

* Methods for server paths and files

String getMimeType (String file) gets the MIME type of the specified file

ServletContex getContext (String uripath) gets the Application context of the specified Local URL

String getRealPath (String path) gets the absolute path of the local path

Example: <% out. println (application. getRealPath ("Login. jsp"); %> // C: \ Program Files \ Tomcat 6.0 \ webapps \ UserWeb \ Login. jsp

* Log record Methods

Void log (String msg) writes information to the log file

Void log (String msg, Throwable throwable) writes the exception information generated by stack trace to the log file.

6. pageContext object // PageContext

Provides methods to return other implicit objects on the JSP page.

GetPage ()

GetRequest ()

GetResponse ()

GetServletConfig ()

GetServletContext () // returns the applaction implicit object.

GetSession ()

GetException ()

GetOut ()

The pageContex object is obtained by calling the JspFactory. getPageContext method.

Describes the running environment of the JSP document and provides access to all other implicit objects and their attributes.

Void forward (path) // jump, which belongs to the request forwarding // pageContext. forward ("login. jsp ");

ServletConfig getServletConfig () // return the servlet configuration object (that is, the config object)

/// Example public void test (PageContext context) {context. getRequest (). setAttribute ("requestKey", "this is something to put in the request"); context. getSession (). setAttribute ("sessionkey", "this is something for the session"); context. getServletContext (). setAttribute ("applicationKey", "this is the application ");}

7. exception object // Throwable

To use it, you must set it on the current page... IsErrorPage = "true" %>

Set errorPage = "ErrProcess. jsp" %>

8. page Object

Object page = this indicates the jsp page itself

9. config object // ServletConfig

The Servlet configuration object is an instance of the javax. servlet. servletConfig interface.

Important methods:

Enumeration getInitParameterNames ()

String getInitParameter (name)

10. out object JspWriter

It is used to send text entity content to jsp pages. It is obtained by calling the getOut () method of pageContext and the previously learned ServletResonse. the PrintWriter object returned by the getWriter method is often similar, but the two are different objects. The out type in JSP is JspWriter, which is equivalent to a PrintWriter with the cache function and the packaging class of PrintWriter.

11. Access attributes in various domains

In pageContext, request, session, and appaction objects, you can call the setAttribute and getAttribute methods to set and retrieve attributes within their respective domains. Their differences are as follows:

-- In appaction, it can be accessed by all the servlets and JSP pages of the same web application.

-- In the session, it can be accessed by all the servlets and JSP pages of the same session.

-- In the request, it can be accessed by all Servlet and js pages in the same request.

-- In pageContext, it can only be accessed by each component called in the response of the current JSP page

The pageContext class also provides a method for unified management of attributes of various domains. Its setAttribute method has the following heavy load:

* Public void setAttribute (String name, Object value); // page range

* Pbulic void setAttribute (String name, Object value, int scope) // scope specifies the domain range

Constants corresponding to scope: PageContext. // These constants are defined in the PageContext class.

APPLICATION_SCOPE,

SESSION_SCOPE,

REQUEST_SCOPE,

PAGE_SCOPE

// Example pageContext. setAttribute ("key", value, PageContext. SESSION_SCOPE) // equivalent to placing a value in the session

12. Mime Type

No matter what data the browser receives, it is actually a binary data of 0 and 1. the browser does not know it and receives images, common webpages, or Excel documents, because of this, the web server must tell the browser in a certain way which format the received object content represents before the browser can correctly process the data. There are multiple common data formats in computer applications, people define a name for each common data format, called MIME (Mutipurpose Internet Mail Extension Multi-purpose Internet Mail Extension) the Content-Type header field specifies the Mime Type of the object Content. Most Web servers can set the correspondence between the file extension and the Mime Type. In tomcat, you can find a large number of corresponding settings for this Mime type in C: \ Tomcat6.0 \ conf \ web. xml.

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.