JSP Learning and Understanding (I.)

Source: Internet
Author: User
Tags tomcat server

I. Application of JSP


1). Why
JSP is a technique written by Jane Servlet, which mixes Java code and HTML statements in the same file, writes only the content that is generated in the Web page in Java code, and writes the static content with static HTML pages.

Java Server Page:java Server Web page, writing Java code on HTML page


2). Create a new JSP page, <%%> within the body node to write Java code

<body>  <%     Date Date=new  date ();     SYSTEM.OUT.PRINTLN (date);    %></body>



3). In any directory other than Web-inf and its subdirectories that can be placed in the Web application, the access path to the JSP page and the access path of the normal HTML are exactly the same.



4). How JSP works: JSP is essentially a servlet
Each JSP page is accessed for the first time. The JSP engine translates it into a servlet source program, and then compiles the servlet source program into a servlet class file. The Web container (servlet engine) is then loaded and interpreted in the same way that the common servlet program is called to execute the servlet program translated by the JSP.


5) implied variables for JSP pages:

void _jspservice (HttpServletRequest request,httpservletreponse reponse) throws Java.io.ioexception,servletexception {       PageContext pagecontext=null;       HttpSession session=null;       ServletContext application=null; ServletConfig config=null; JspWriterout =null, object page=this;
//...
Code written using <%%> in this location, you can use the Request,reponse,pagecontext,session
Application,config,out,page these 8 hidden objects. (You can actually use an implicit object called exception.)
}

An object of the 1.request:httpservletrequest.
2.reponse:httpservletrepomse an object (almost no method in the JSP page that calls Reponse. )
3.pageContext: The context of the page, which is an object of PageContext. You can get the other 8 hidden objects from the object, or you can get additional information from the current page. (Use it when learning custom labels)
4.session: A session representing the browser and the server, which is an object of httpsession.
5.application: Represents the current web app, which is a ServletContext object.
6.config: The ServletConfig object for the servlet that the current JSP corresponds to (hardly used). If you need to access the initialization parameters of the current JSP configuration, you need to pass the mapped address.


Map JSP:

<servlet>    <servlet-name>hellojsp</servlet-name>    <jsp-file>/hello.jsp</ jsp-file>    <init-param>       <param-name>test</param-name>       <param-value> testvalue</param-value>    </init-param></servlet><servlet-mapping>     < Servlet-name>hellojsp</servlet-name>     <url-pattern>/hellojsp<url-pattern>< Servlet-mapping>


The 7.out:jspwriter object, called Out.println (), can print the string directly to the browser.
8.page: Reference to the Servlet object corresponding to the current JSP, which is rarely used when developing.
9.exception: When you declare the iserrorpage= "true" of the page directive, you can use the

<%@ page iserrorpage= "true"%>


Pagecontext,request,session,application (range of scope of the property from small to large)
Out,config,page,reponse

Two. JSP basic syntax


1). JSP template elements: static HTML content in a JSP page


2). The JSP expression provides a simplified way of outputting the results of a Java variable or expression to the client, and it encapsulates the variables or expressions that will be output directly in <%= and%>.



3). JSP script fragment (scriptlet) refers to one or more Java program code nested between <% and%>
Code in multiple script fragments can access each other



<%     String agestr=request.getparameter ("Age");     Integerage =Integer.parseint (agestr);      if (age>=18) {         out.println ("Adult:") );     } Else {         out.println ("underage ...");     }    %>



4). JSP declaration: JSP declarations encapsulate Java code in <% and%>, and the code inside it will be inserted outside the servlet's _jspservlet method (almost unused in JSP pages)


5). Format of JSP annotations
<%--JSP Annotations--%> <!--HTML comments--
Difference: JSP annotations can prevent Java code from running


and Property-related methods:
1).
Object getattribute (String name): Gets the specified property
enumeration Getattributenames (): Gets all the names of the properties of the enumeration object
Removesttribute (String name): Removes the specified property
void Serattribute (String name,object o): Set properties


2). Pagecomtext,request,session,application objects have these methods
These four objects are also known as domain objects.

PageContext: The scope of the property is limited to the current JSP page

Request: The scope of the property is limited to the same request.
Session: The scope of the property is limited to one session only, and the browser opens to close called a session (during which sessions are not invalidated.) )
Application: The scope of the property is limited to the current Web application. is the scope of the largest range of properties, used only in one place to set the property, in other parts of the JSP or servlet can be obtained


6. Forwarding and redirection of requests


Forwarding of requests:
1. Call HttpServletRequest's Getrequestdispatcher () method to get the RequestDispatcher object
Calling Getrequestdispatcher () requires an incoming forwarding address

String path= "Testservlet"; RequestDispatcher requestdispatcher=request.getrequestdispatcher ("/" +path);


2. Call HttpServletRequest's forward (request,reponse) for request forwarding
Requestdispatcher.forward (Request,reponse);


2). redirect Code for the request:
To perform a request redirection, call the Reponse.sendredirect (path) method directly
Path redirects the address
String path= "Testsetvlet";
Reponse.sendredirect (path);
1). Essential difference: The forwarding of the request only made one request, while the redirect sent two requests


Specific:
1. The Address bar is the address of the initial request;
REDIRECT requested: Address bar is no longer the initial address, address bar is the address of the last response

2. Request forwarding: In the final servlet, the request object and the requested request in transit are the same object.
Request redirection: In the final servlet, the request object and the requested request in transit are not the same object.

3. Request forwarding: A resource that can only be forwarded to the current web App
REDIRECT requested: can be directed to any resource.

4. Request Forwarding:/represents the root directory of the current web App
Requested redirection:/represents the root directory of the Web site.

Three. JSP directives

JSP directives: JSP directives are designed for the JSP engine, and they do not directly produce any visible output, but rather tell the engine how to handle the rest of the JSP page .

Common with Page,include,taglib
Page directive:
The page directive is used to define the various properties of the JSP page, regardless of where the page directive appears on the JSP page, it is the entire JSP page, in order to maintain the readability of the program and follow good programming habits, the page instruction is best placed in the entire JSP page in the beginning.


2) The properties commonly used by page directives:
1import Properties: Specifies the class to be imported by the servlet corresponding to the current JSP page;

<% @page import= "Java.text.DateFormat"%>


2.session property: Evaluates to True or FALSE, specifies whether the session hidden variable of the current page is available, or whether accessing the current page is bound to generate a HttpSession object.

<%page session= "false"%>


1.errosPage and Iserrorpage:


>errorpage Specifies if the actual response page of the current page is incorrect. where/represents the root directory of the current web App.

<% page errorpage= "/error.jsp"%


>ISERRORPAGE Specifies the error handling page of the current page to indicate whether the current page can use exception to hide variables, note that iserrorpage= "true", and use the exception method, It is generally not recommended to have direct access to this page
> How do I make a customer unable to access a page directly? Duyu Tomcat server, files under Web-inf cannot be accessed by direct input in the browser, but can be forwarded by request.


4.contentType: Specifies the type of response for the current JSP page. The actual call is Reponse,setcontenttype= "text/html; Charset=utf-8 "
Typically, for a JSP page, its value is text/html;chaeset=utf-8.charset specifies what the character encoding of the returned page is. It's usually UTF-8.


5.pageEncoding: Specifies the character encoding of the current JSP page, which is typically consistent with charset in ContextType.


3.include command:
1). The include directive is used to inform the JSP engine that when translating the current JSP page, other content is merged into the servlet source file converted into the current JSP page, which is introduced at the source file level in a way called static ingestion. The current JSP page is tightly combined with a static-introduced page as a servlet
2). The setting value of the file property must use a relative path. If you start with "/", it represents the root of the current Web application (note that it is not the site root), otherwise, it is relative to the current file.


4.jsp:include Label
1). <jsp:include page= "b.jsp" ></jsp:include>
2). Dynamic Introduction: Instead of generating a servlet civilization like the include directive, it was scolded, generating two servlet source files and then including the target page in a way.
Org.apache.jasper.runtime.JspRuntimeLibrary.include (Request,reponse, "b.jsp", out,flase);


5.include directives and Jsp:include tags:
1) .<jsp:include>


Jsp:forward:

1). <jsp:forward page= "/include/b.jsp" ></jsp:forward><%request.getrequestdispatcher ("/include/ B.jsp "). Forward (Request,response)%>


2). However, using Jsp:forward can use the Jsp:param word tag to pass some parameters to the b.jsp, and Jsp:include can also use the Jsp:param tag

<jsp:forward page= "/include/b.jsp" ></jsp:forward><jsp:param value= "ABCD" name= "username"/>  Or<jsp:forward page= "/include/b.jsp" ></jsp:forward><jsp:param value= "ABCD" name= "username"/> </jsp:include> The b.jsp page can be Huqiu to incoming request parameters via Request.getparameter ("username"). 

JSP Learning and Understanding (I.)

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.