How to learn more about JSP? JSP learning method | tutorial

Source: Internet
Author: User
Tags html page tag name

Common JSP

JSP pages are used by containers to generate Servlet classes. For example, Tomcat containers generate JSP Servlet classes in the work directory. Therefore, a lot of simplified syntax can be used in JSP for containers. This article will help you sort it out.

JSP syntax

Scriptlet: <%>
You can write Java code in it, such as <% out. print ("27"); %>;
Command: <% @ %>
You can give a special indication to the container during page conversion. It has three commands: page, include, and taglib, and the command has many attributes, such as "import" is the property of page: <% @ page import = "foo. *, java. util. * "%>;
Expression: <% = %>
The expression will be an out. println () or out. print () parameter, so <% = 27%> is equivalent to <% out. print (27); %>;
Declaration: <%! %>
Is the declaration of converting JSP to Servlet class, so class variables (static variables), instance variables, methods, and so on can be declared;
Note: <% -- %>
Like annotations in Java code, annotations are removed when JSP is converted to Servlet;

Implicit object

JSP's implicit objects include not only out, but also some other:

Final javax. servlet. jsp. PageContext pageContext;
Javax. servlet. http. HttpSession session;
Final javax. servlet. ServletContext application;
Final javax. servlet. ServletConfig config;
Javax. servlet. jsp. JspWriter out;
Final java. lang. Object page = this;
Final javax. servlet. http. HttpServletRequest request;
Final javax. servlet. http. HttpServletResponse response;

Servlet generated by JSP

In the Tomcat work Directory, we can see the Servlet class generated by JSP, which inherits org. apache. jasper. runtime. HttpJspBase, which has the following three methods:

_ JspInit ()
_ JspDestroy ()
_ JspService ()

They are called by the init (), destroy (), and service () methods of the parent class respectively. They both carry the "_" sign, indicating that we cannot overwrite them, the underline means "don't touch me! ". For example, if Tomcat 7 is used, in JSP:

<%! Public void _ jspDestroy (){
Int I = 5;
} %>

An exception is reported:

Org. apache. jasper. JasperException: Unable to compile class for JSP:

Initialize JSP

Generally, we allocate initialization parameters to individual servlet or JSP pages. The specified servlet or JSP page reads these parameters through the getInitParameter method of ServletConfig. However, in some cases, initialization parameters within the system need to be provided. Any servlet or JSP page can read these initialization parameters through the getInitParameter method of ServletContext. However, this is not recommended. It is usually based on the MVC architecture and is suitable for C.

Configuring initialization parameters for JSP is to add a <jsp-file> element to the <servlet> tag.

<! DOCTYPE web-app PUBLIC
"-// Sun Microsystems, Inc. // DTD Web Application 2.3 // EN"
Http://java.sun.com/dtd/web-app_2_3.dtd>
    
<Web-app>
<Display-name> Archetype Created Web Application </display-name>
<Context-param>
<Param-name> qq </param-name>
<Param-value> 38602359 </param-value>
</Context-param>
<Servlet>
<Servlet-name> index </servlet-name>
<! -- Unlike Servlet, jsp-file and URL are used -->
<Jsp-file>/index. jsp </jsp-file>
<Init-param>
<Param-name> email </param-name>
<Param-value> kevin@oseye.net </param-value>
</Init-param>
</Servlet>
</Web-app>

And index. jsp

<% @ Page import = "java. util. Enumeration" %>
<Html>
<Body>
<H2> Hello World! </H2>
<% = Config. getInitParameter ("email") %> <br>
<% = GetServletConfig (). getInitParameter ("email") %> <br>
<% = Application. getInitParameter ("qq") %> <br>
<% = GetServletContext (). getInitParameter ("qq") %>
</Body>
</Html>

However, the output

Hello World!
Null
Null
38602359
38602359

Visible and retrieved JSP initialization parameters, but if I set <servlet-mapping> in web. xml

<Servlet-mapping>
<Servlet-name> index </servlet-name>
<Url-pattern>/index. jsp </url-pattern>
</Servlet-mapping>

Why? I don't understand. Keep it first!

JSP attributes

JSP has one more scope than a common Servlet and has four scopes in total.

The setAttribute and getAttribute of pageContext are both overloaded, so an int-type scope setting is added.

Public static final int PAGE_SCOPE = 1;
Public static final int REQUEST_SCOPE = 2;
Public static final int SESSION_SCOPE = 3;
Public static final int APPLICATION_SCOPE = 4;

Only attributes of the corresponding scope can be obtained. However, pageContext also has a findAttribute method, which starts from the strictest scope, and gradually changes to a less rigorous scope, that is, first searches in the request scope, search for the session scope, and finally find the application scope. It is stopped as long as it is found in a specific role. For example

<Html>
<Body>
<H2> Hello World! </H2>
<% PageContext. setAttribute ("name", "kevin", PageContext. REQUEST_SCOPE); %>
PageContext: <% = pageContext. getAttribute ("name") %> <br>
Session: <% = session. getAttribute ("name") %> <br>
Application: <% = application. getAttribute ("name") %> <br>
Request: <% = request. getAttribute ("name") %> <br>
Find: <% = pageContext. findAttribute ("name") %> <br>
</Body>
</Html>

Output

Hello World!
PageContext: null
Session: null
Application: null
Request: kevin
Find: kevin

Page command

The attributes of the page Command include import, contentType, isThredSafe, Sessioin, buffer, autoflush, extends, info, errorpage, isErrorPage, language, and pageEncoding. Format:

<% @ Page page_directive_attr_list %>

The import attribute specifies the package imported by the Servlet.

<% @ Page import = "package. class" %>

The isThreadSafe attribute controls whether the Servlet generated from the JSP page implements the SingleThreadModel interface. The isThreadSafe attribute uses one of the following two formats. The former is default:

<% @ Page isThreadSafe = "True" %>
<% @ Page isThreadSafe = "false" %>

The session attribute controls whether the page participates in an HTTP session.
-The default value is true, indicating that an HTTPsession is added to the page;
-If it is set to false, it indicates that no session is automatically used;
The buffer attribute specifies the buffer size of JspWriter. The buffer attribute uses one of the following two formats:

<% @ Page buffer = "sizekb" %>
<% @ Page buffer = "none" %>

The autoFlush attribute is used together with the buffer attribute of the output buffer. Controls whether the output buffer should be cleared when it is full or whether to handle exceptions when the buffer overflow occurs.
The extends attribute specifies the Servlet superclass generated by the JSP page.

<% @ Page extends = "package. class" %>

The info attribute defines a string that can be retrieved from the Servlet through the getServletInfo method.

<% @ Page info = "some infomation" %>

The isErrorpage attribute specifies whether the current page can act as an error page for other JSP pages. The default value is false.
The errorpage attribute indicates the URL to which the error is handled if an exception is thrown and the exception is not captured.
The contentType attribute specifies the MIME type of the character encoding and JSP response. The default value of the contentType property is text/html; the default value of the charset property is ISO-8859-1

<% @ Page contentType = "TYPE" %>
<% @ Page contentType = "TYPE; charset = CHARSET" %>

The pageEncoding attribute defines the page encoding characters. The default value is ISO-8859-1 unless the page directive's contentType attribute is specified.
The language attribute specifies the programming language to be used.

No script JSP

Using scriptlet, expressions, and declarations is not only difficult to maintain code mixing, but also not conducive to the division of labor between page designers and server developers. Therefore, we will introduce EL (expression language), standard actions, and JSTL.

Standard action

JSP actions are in the following format: <jsp: Tag name>. You can use the tag in XML syntax to control the behavior of the Servlet engine. These jsp tag action elements are executed in the user request phase. These standard action elements are embedded in the jsp file, so they can be directly used. Has the following action elements

<Jsp: useBean> // defines the jsp page to use a JavaBean instance;
<Jsp: setProperty> // Set the attribute value in a JavaBean;
<Jsp: getProperty> // Obtain a property value from JavaBean;
<Jsp: include> // The JSP page contains an external file;
<Jsp: forward> // clear the buffer to forward the incoming requests to another page for processing;
<Jsp: param> // used to pass the parameter value;
<Jsp: plugin> // specifies the attributes of the Plug-In inserted in the client browser;
<Jsp: params> // used to pass parameter values to the HTML page plug-in;
<Jsp: fallback> // specifies how to handle cases where the client does not support plug-ins;

Here we will explain the concept of JavaBean. What is the bean rule?

Is to follow the rules of the "old" JavaBeans norms. We are talking about JavaBean, not the Enterprise JavaBean (EJB). These two things are completely irrelevant (to be clear ). The general non-Enterprise JavaBean specification defines how a class can be regarded as a JavaBean. Although this specification is indeed complicated, you only need to know the following rules when using beans in combination with JSP and servlet (only the rules related to using servlet and JSP are listed ):

There must be a public constructor without parameters;
The public obtaining method and setting method must be named according to naming conventions. The first is "get" (or if it is a Boolean property, the prefix of obtaining method is "is ") and "set", such as getName and setName. To obtain a property name, first remove get and set and lowercase letters.
The parameter type of the set method must be the same as the return type of the GET method, for example, String getName () and void setName (String name ).
The property name and type are derived from the get and set methods, rather than from a member in the class.
In combination with JSP, the property type must be String or a basic type. If this is not the case, even though it may be a valid bean, you may have to use a script.

For example, I have a JavaBean

Package net. oseye;
    
Public class Person {
Private String name;
Private int age;
Public String getName (){
Return name;
    }
Public void setName (String name ){
This. name = name;
    }
Public int getAge (){
Return age;
    }
Public void setAge (int age ){
This. age = age;
    }
    }

In the servlet doGet (),

Person p = new Person ();
P. setName ("kevin ");
P. setAge (22 );
    
Request. setAttribute ("person", p );
    
RequestDispatcher view = request. getRequestDispatcher ("/index. jsp ");
View. forward (request, response );

The script in index. jsp may be like this.

<%
Person p = (Person) request. getAttribute ("person ");
If (p! = Null ){
Out. print (p. getName ());
} Else {
Out. print ("null ");
    }
%>

If the JSP standard action is used

<Jsp: useBean id = "person" class = "net. oseye. Person" scope = "request"/>
<Jsp: getProperty property = "name" name = "person"/>

A little explanation of the standard action (it is better to view the java file generated by the Tomcat/work directory for better understanding ):

<Jsp: useBean id = "person" class = "net. oseye. Person" scope = "request"/>

Id is the attribute name, class is the type of the attribute value, and scope is the attribute scope;
If the property does not have a person, a new property is created, which is an example object of the class. Therefore, it can also have a body to set the property value.

<Jsp: useBean id = "person2" class = "net. oseye. Person" scope = "request">
<Jsp: setProperty property = "name" name = "person2" value = "kevin2"/>
</Jsp: useBean>
<% = (Person) request. getAttribute ("person2"). getName () %>

A bucket is created only when the corresponding attribute cannot be found.
If a multi-state JavaBean is created, the type attribute is used.

Type id = new class ();

Type is a reference type, while class is an object type. Therefore, type can be an interface, abstract class, or parent class. If no type is used, the default type is the same as the class type. If there is only type but no class, the attribute bean must exist.
Scope is "page" by default ".

<Jsp: param>

Param is a parameter used to receive form submission. If the form element name and the JavaBean attribute name are different, you need to use param, such as form

<Form method = "get" action = "http: // localhost: 8080/mytest/Index">
<Input name = "username" type = "text" value = "Anders"/>
<Input type = "submit" name = "Submit" value = "submit"/>
</Form>

In index. jsp

<Jsp: useBean id = "person" class = "net. oseye. Person" scope = "request">
<Jsp: setProperty property = "name" name = "person" param = "username"/>
</Jsp: useBean>

If the element name of the form is the same as the name of the JavaBean, you can omit the param parameter. If the element of the form matches the nature of the JavaBean completely, you can also use wildcards in the property.

<Jsp: useBean id = "person" class = "net. oseye. Person" scope = "request">
<Jsp: setProperty property = "*" name = "person"/>
</Jsp: useBean>

EL
For example, in the actions in the table, if the type of the JavaBean is not String, you still need to use the script even though it is a legal JavaBean, in fact, another way is EL (express language ). EL syntax is quite simple. The format is:

$ {FirstThing. secondThing}

FirstThing can be an implicit object: pagination, requestScope, sessionScope, applicationScope, pageContext, param, paramValues, header, headerValues, cookie, initParam, or attribute.
Pagination attributes, requestScope attributes, sessionScope attributes, and applicationScope attributes.
You can use the period (.) when accessing the ing value or nature (.), however, in addition to the nature and ing value, there are many other special features, such as brackets ([]).

Person p = new Person ();
P. setName ("kevin ");
P. setAge (22 );
Request. setAttribute ("person", p );
RequestDispatcher view = request. getRequestDispatcher ("/index. jsp ");
View. forward (request, response );

In JSP

<% @ Page isELIgnored = "false" %>
<Html>
<Body>
$ {Person. name} <br>
$ {Person ["name"]} <br>
${10 + 10}
</Body>
</Html>

PS: due to different versions, EL may be enabled by default, or EL is disabled by default. If EL is not enabled by default, you need to manually enable EL. Therefore, the first line must not be fewer, you can also configure it in the DD file. Besides, EL can also customize functions, which is not in-depth.
JSTL
The full name of JSTL is assumerver Pages Standard Tag Library. The JSLT tag library is frequently used in daily development and has the best performance among many tags. JAR package of JSTL to be added

<Dependency>
<GroupId> jstl </groupId>
<ArtifactId> jstl </artifactId>
<Version> 1.2 </version>
</Dependency>

Then add the declaration in the JSP document

<% @ Taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

Then you can use JSTL.

<C: out value = "dddd"> </c: out>

Common tags: such as <c: out>, <c: remove>, <c: catch>, and <c: set>;
Condition tags: such as <c: if> <c: when>, <c: choose>, and <c: otherwise>;
URL tags: such as <c: import>, <c: redirect>, and <c: url>;
XML tags: such as <xml: out>;
International output tags: such as <fmt: timeZone>;
SQL labels: such as <SQL: query>, <SQL: update>, and <SQL: transaction>;

Of course, if JSTL is not enough, you can also customize some JSTL, which is not in-depth at the moment.

PS: include command, <jsp: include> standard action, and JSTL are different: the former is copied during compilation, and the latter is copied during execution.

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.