The path of the Java Siege Master--Review the Java Web JSP Getting started _el expression _jstl Tag Library

Source: Internet
Author: User
Tags html comment ranges throwable tld java web

JSP Technology
Mastering: JSP syntax + EL + JSTL

Why is Sun launching JSP technology?
Servlet generated Web page is more complex, itself does not support HTML syntax, HTML code needs to be output stream through response, JSP support HTML syntax, generate HTML convenience.

What is the difference between JSP technology and servlet technology?
JSP and servlet technology are used to dynamically generate Web pages, servlet does not support HTML syntax, generate Web page trouble, JSP support HTML syntax, generate Web pages convenient, JSP runtime translation servlet execution. A JSP is a Servlet.

What is the principle of JSP operation?
Client Access writes a JSP file, the server reads the JSP file, generates a servlet from the JSP, and the servlet compiles to run the generated Web page.

JSP <%! %> <%=%> <%%>
<%! %> declaration: Defines the global variables or global methods, internal classes of the servlet program after translation
<%=%> expression output to browser effect Out.print
<%%> script code block, embedded Java Run code----not translated

JSP translation servlet holds tomcat/work directory
* JSP translation servlet page all current HTML translated to out.write output

JSP annotations support three types of annotations
1, JSP comments: <%----%> only exists in the JSP file source code, in the JSP translation servlet, this kind of comment disappears
* This type of comment cannot be executed

2. Java Comment: /** */Document COMMENT,/* */Multiline comment,//single line comment
Document Comments/** */Generate Javadoc is primarily used to annotate packages, classes, member variables, Member methods------code feature consumer
Multiline comments and single-line comments do not generate Javadoc, and note code implementation logic is used to------the programmer itself within a method, to read the code for comment
* Java annotations exist when a JSP is translated into a servlet, which is ignored when the servlet program executes, and does not exist in the HTML page source code.
* Ignored during servlet execution

3. html comment <!---->
* The JSP is translated as a servlet when translated Out.print in the source code of the generated HTML page that kind of comment also exists

Conclusion: JSP annotations disappear during translation, Java annotations disappear during servlet run, HTML annotations do not disappear

Study Questions
<%
String s = "ABCD";
%>
<!--annotate JSP or Java code with HTML comments <%=s%>
In the page results <!--annotate the JSP or Java code with HTML comments ABCD---
Conclusion: HTML annotations cannot prevent JSP or Java code from executing

JSP directive (JSP Directive)
Page directive
Include directives
TAGLIB directive

Syntax: <%@ directive Name attribute = Value Property = value ...%>

The page directive is used to define the global properties of the JSP file <% page property = value%>
1, language only for Java
2, extends JSP translation after the servlet inherits the parent class, this property is generally not set, if not to set, the inheriting class must be the servlet implementation class
3, session defines whether the JSP can directly use the session implicit object
If the property is set to True, the following two lines of code are generated when the JSP translates the servlet
HttpSession session = NULL;
Session = Pagecontext.getsession ();
* If you want to use the HttpSession object in your JSP, use the Session property default value True
4, import complete JSP translation after the Servlet guide package
JSP is translated to the servlet default guide package
Import javax.servlet.*;
Import javax.servlet.http.*;
Import javax.servlet.jsp.*;
JRE Import Java.lang By default
* In JSP if the use of the class does not belong to the above four packages, need to guide the package
5. Buffer AutoFlush set out suppressed object properties
Buffer size Set
AutoFlush set when the buffer is full, automatically brush out
6. Iselignored sets whether the JSP executes the EL expression
Iselignored= "false" does not ignore---execution parsing
Iselignored= "true" ignores----not resolved
* General is the default value false

7. Set JSP page encoding via contenttype and pageencoding
Pageencoding is a JSP file source code on the hard disk encoding set
ContentType in servlet-generated HTML delivery browser with encoding

8, through ErrorPage and Iserrorpage control JSP page error when the jump
Set the error-friendly page----When an error occurs on the page, the user should not see a page with a code error and see a friendly page
Specify which page to jump to on page error by errorpage
* Internet Explorer default Friends page, if you want to see yourself writing a friendly page, close ie default friendly page
IE Toolbar---Internet Options-----Advanced-----Display friendly HTTP error messages remove hooks

In the error-friendly page, you can get the cause of the error by setting the Iserrorpage property

* In the actual development, generally do not use the above to explain the error handling method

Error page The second way: not only can handle 500, can also handle 404
Configure Web. xml
<error-page>
<error-code>500</error-code>
<location>/demo5/500.jsp</location>
</error-page>


Include directives, which are used to statically include pages-----Extract the common parts of the page and complete the page layout with include
Syntax: <%@ include file= "file path"%>

Include contains the entire content of the target page, contains the page, does not need to be a full HTML, as long as the HTML fragment can be written

Static include principle
* When a JSP is translated into a servlet, the included action is completed, the servlet program is not executed, the containing path cannot be used, cannot contain a parameter, the target file must exist
* There is a special case: there is an error in the included page, as long as there is no error in the included servlet, you can execute

Taglib directives for referencing tag library files on JSP pages
* Define label function in order to simplify JSP page development
* Introduction of JSTL Tag Library via taglib instruction, Syntax: <%taglib uri= "prefix=" "%>
URI----Define label unique namespace
Prefixt----Namespace Prefixes

When referencing Jstl, in import Jstl.jar meta-inf/c.tld
<short-name>c</short-name>--------is the prefix property
<uri>http://java.sun.com/jsp/jstl/core</uri>-----is the URI attribute

What are the nine built-in objects of a JSP?
What is a built-in object? When a JSP is translated into a servlet code, some objects are created by default, such objects can be used directly in the JSP, built-in objects

page, request, session, application, response, PageContext, out, config, exception
Request HttpServletRequest----Requested Object
Responsehttpservletresponse----Response Object
Session HttpSession-------Conversation object
Application servletcontext------Web App Global Unique object
Config servletconfig------initialization data
Page This (httpservlet)
PageContext PageContext
Exception Throwable (all exception parent Class)-----When the page is an error page, get exception information with exception
* Throwable is the exception class parent class
Out JspWriter

Page generates a Servlet object on behalf of the current JSP
* page is an object type and can only be used in object method----This object is not recommended in development
* You can cast the page to the HttpServlet object's

How many data ranges does a servlet have? Three kinds: request, session, ServletContext
JSP three data range based on servlet, new add page data range----JSP Four kinds of data range: page request session Application
* Page data range holds data only valid within the current JSP

PageContext represents the current page context
1. Access data to page range
Findattribute Data Lookup in page, request, session, application four data ranges in turn
EL in ${name} calls Findattribute to find data in four scopes in turn

2, PageContext used to obtain the other eight hidden objects
* PageContext package eight hidden object meaning: framework written, get PageContext object equivalent to get JSP nine built-in objects

Out Object
The Out function outputs information to the browser, which is the JspWriter type, implemented internally using PrintWriter, and has a separate buffer.
Out created, the out object is obtained through the PageContext object, when the PageContext object is created, the out buffer size is specified and whether auto flush
* set out buffer size and auto flush via page instruction Buffer AutoFlush

Out to the browser output content, response.getwriter to the browser output content, the difference?
Out.println ("AAA");
Response.getwriter (). println ("BBB");
Out.print ("CCC");
Response.getwriter output, before output content

Page request session application Response out config PageContext exception


JSP directives and JSP tags are distinguished?
JSP Directive Directive
JSP Tag Action

Six action tags in JSP
<jsp:useBean> <jsp:setProperty> <jsp:getProperty>-----related to JavaBean operation tomorrow study
<jsp:include> <jsp:forward> <jsp:param >

<jsp:include> effect is equivalent to Request.getrequestdispatcher (). Include
The <jsp:forward> effect is equivalent to Request.getrequestdispatcher (). Forward

The <jsp:include> tag function is equivalent to <%@ include%>
Principle: Dynamic Inclusion
Syntax: <jsp:include page= "file path"/>

Included pages do not require full HTML, only HTML fragments are required

Jsp:include and @include differences
@include include directives, statically included, when a JSP is translated into a servlet, the containing action is executed, including the result is the target page translation servlet source code, translated into a servlet to execute
The JSP include tag, which is dynamically included, completes the include action when the index servlet executes, including the result that the target JSP translation servlet generates the HTML page results, each of which contains JSP translations that are executed by a separate servlet

<jsp:forward page= "/demo11/b.jsp" ></jsp:forward> equivalent to Request.getrequestdispatcher ("/demo11/b.jsp"). Forward (Request,response);

<jsp:forward page= "/demo11/b.jsp" >
<jsp:param value= "Itcast" name= "name"/>
</jsp:forward>
The above is used in JSP to pass a parameter, with JSP if the parameters passed directly through the setattribute

El expression language, from folk, Servlet2.4 after El was incorporated into the official norm
Function:
1, EL get JSP four scope to save data (Access JavaBean properties)
2. EL Expression Support operation
3, EL built-in 11 objects---web development common objects
4, EL call Java method

El is included in the specification, javaee1.3 and previous versions from the javaee1.4 version, which is not parsed by default on El
* If you want to javaee1.3 and previous version resolution EL------Set page Property Iselignored = False

1. Use El to get JSP four range of data
Use El to specify to find four range data ${pagescope. Property name} ${requestscope. Property name} ${sessionscope. Property name} ${applicationscope. Property name}
If you do not set the lookup data range ${property name}----Call Pagecontext.findattribute to find in four ranges
If the lookup attribute does not exist, the return is an empty string instead of NULL

There are cases when getting arrays, lists, and maps use [] to get property values
. and [] What is the difference?
Answer:. and [] can be used to obtain the El attribute value,. can be implemented function [] all can!
For example: ${pagescope.user.name} can also be written as ${pagescope.user["name"} (after obtaining an object, you can use [] instead to access the object properties.)
[] Special identification information can be used, however. No
For example:
Pagecontext.setattribute ("0", "itcast");
Pagecontext.setattribute ("Aa.bb", "Spring-born Tektronix");
Accessible only through []-----Note: When using [] to take a property value, add "", do not add "" is considered a variable

When using El for value, use [] if the Special Envoy character attribute is included, otherwise use. You can do it.

2. Perform arithmetic, comparison, and logic operations in El
The operation statement must be written to ${} while the EL performs the operation
* Perform arithmetic operations on El get attribute value, automatic type conversion----perform arithmetic operations, the operation parameters must be numeric
${"a" + "B"}----A number formatting error occurred

Empty operator
1) Determine if a property exists, usually the empty operator is used in conjunction with C:IF
2) Use empty to determine if list or map is empty (size==0)

Binary expression: ${user!=null?user.name: ""}-----Ternary operator

3, EL 11 built-in objects
Pagescope Requestscope sessionscope applicationscope Four data range, used to take a value

PageContext Current JSP context-----${pagecontext.request.contextpath}

${param.name} equivalent to Request.getparameter ("name")
${paramvalues.hobby} equivalent to Request.getparametervalues ("hobby")
${header.referer} equivalent to Request.getheader ("Referer")
${headervalues["Accept-encoding"} is equivalent to Request.getheaders ("accept-encoding")

${initparam.name} is equivalent to Getservletcontext (). Getinitparamter ("name")

Must master the wording of the cookie implied object
cookie[] cookies = request.getcookies ();
if (cookies==null) {
OUT.PRINTLN ("Cookie does not exist! ");
}else{
for (Cookie cookie:cookies) {
if (Cookie.getname (). Equals ("Address")) {
Out.println (Cookie.getvalue ());
}
}
}

Using el: ${cookie.address.value}

4, El obtains the data value, often needs to obtain the data value to handle-----the EL function
Steps:
First step: Writing Java classes, providing a static method
Step two: Write the TLD file and define the function in the TLD file

Sun provides a set of El libraries in Jstl that can be used directly after importing the Jstl jar package.
1) Import Jstl.jar
2) within the JSP page, introduce the function library name space
<%@ taglib uri= "http://java.sun.com/jsp/jstl/functions" prefix= "FN"%>
* The EL function library is defined in Jstl.jar presence Meta-inf/fn.tld
3) Sun provides the El function library primarily to operate on strings to provide 16 functions
Syntax: ${fn:touppercase (' Asdasdsfsdf ')}


Outsourced projects, JSP internal does not allow the definition of script elements <%%>-----must be implemented in the tag library and expression language <%%> code effects
Using the Jstl step
1, go to the official Web download JSTL Jar 1.0 1.1 1.2
1.1 and 1.2 basically the same as Servlet2.4 (javaee1.4) later proposed
1.0 proposed before javaee1.3
* El in javaee1.4 This version is included in the specification, jstl1.0 when El is not included in the specification, all 1.0 tags are not supported by default El

2. Jar Package Import
jstl1.1 two jar Jstl.jar standard.jar-----Jstl.jar Interface API Standard.jar code implementation
Copy the two jar packages in the project/webroot/web-inf/lib directory

3, in the JSP page through the TAGLIB directive introduced the JSTL tag library corresponding URI
Jstl is divided into five categories: core core tag FMT internationalization tag SQL database tag XML action XML tag fn is the El function library
Because of database operations and XML operations, the code is written in a servlet, so the SQL tag library and XML tag library do not learn

Each tag library corresponds to a TLD file in the jar/meta-inf/
For example: C.tld is the jstl1.1 version of C-1_0.tld is the jstl1.0 version of the tag library

<% @taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%> import 1.1
<% @taglib uri= "/http/ Java.sun.com/jstl/core "prefix=" C "%> Import 1.0 does not support El
<% @taglib uri=" Http://java.sun.com/jstl/core_rt "prefix=" C "%> Import 1.0 support El
*/jstl/demo.jsp (15,0) according to TLD or attribute directive in tag file, attribute test does no T accept any expressions

12 Core Tag Library tags
1. C:out is used to output the content to the page-------output El value, provide default value, HTML escape output function
2. C:set is used to set a variable or property----save a data to four data ranges, and modify its property values for an already existing object of four data ranges
3. C:remove for removing data from four data ranges
4. C:catch equivalent to a try-catch block-----Catch exception, save the exception object in the page specified property
5, C:if replace the page if condition judgment
6, C:choose C:when c:otherwise Implement IF--else if--else effect---implement switch effect
7, C:foreach implementation of the ForEach loop effect-----Traversal array, List, MAP, control the specified number of loops sum, in a special number of operations
8, C:fortokens complete string cutting
9, C:param can not be used alone, usually with the URL-related tags used in conjunction with the C:url to complete the Chinese code
10, C:import Import the target page, save the content of the target page, and then use it.
11, C:url complete URL rewrite (client disable cookies, URL rewrite stitching jsessionid), combined with param to the Chinese URL encoding
The c:redirect tag is used to implement request redirection

Commonly used: C:set c:if c:foreach c:url for Chinese URL encoding c:redirect

Summarize:
1. JSP and servlet relationships
2. JSP operating principle
3, JSP script element three kinds of <%! %> <%=%> <%%>
4, JSP three kinds of comments
5. Page directive ContentType and pageencoding Difference
6. Error friendly page web. XML configuration
7, <% @include%> and <jsp:include> principle difference
8. <jsp:forward> Forwarding <c:redirect> redirection
9, EL data acquisition. [] Usage
10, empty not use
11, ${pagecontext.request.contextpath} get the project name/day08-----${cookie.name.value} Fast access to cookie value
12, El uses Jstl to provide the El function library
13, JSTL distinguish between 1.0 and 1.1
14. Common Core Label
C:set, C:if, C:foreach, C:url and c:param codes, C:redirect

The path of the Java Siege Master--Review the Java Web JSP Getting started _el expression _jstl Tag Library

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.