Basic JSP learning materials

Source: Internet
Author: User
Tags stock prices

I. JSP technology Overview

After Sun officially released JSP, this new web application development technology soon attracted people's attention. JSP provides a unique development environment for creating highly dynamic web applications. According to Sun, jsp can adapt to 85% of server products on the market, including Apache webserver and iis4.0. Even if you are interested in ASP, we believe that it is still necessary to focus on the development of JSP.

(I) simple comparison between JSP and ASP

JSP is very similar to Microsoft's ASP technology. Both are provided in HTMLCodeMixProgramThe ability of the language engine to interpret and execute program code. In an ASP or JSP environment, HTML code describes the display style of information, while program code describes the processing logic. Common HTML pages only depend on Web servers, while ASP and JSP pages require additional language engines to analyze and execute program code. The execution result of the program code is re-embedded into the HTML code and sent to the browser together. ASP and JSP are both web server-oriented technologies, and client browsers do not require any additional software support.

ASPProgramming LanguageIt is a script language such as VBScript. jsp uses Java, which is the most obvious difference between the two. In addition, there is a more essential difference between ASP and JSP: the two language engines process the program code embedded in the page in a completely different way. In ASP, the VBScript Code is interpreted and executed by the ASP engine. In JSP, the code is compiled into a Servlet and executed by the Java Virtual Machine. This compilation operation only occurs during the first request to the JSP page.

(Ii) runtime environment

Sun's JSP home page is in http://www.javasoft.com/products/jsp/index.html, where JSP specifications can also be downloaded, which define some of the rules that suppliers must follow when creating JSP engines.

To execute JSP code, you must install the JSP engine on the server. Here we use sun's assumerver Web Development Kit (jswdk ). For ease of learning, this software package provides a large number of examples that can be modified. After jswdk is installed, run the startserver command to start the server. In the default configuration, the server listens on port 8080 and uses http: // localhost: 8080 to open the default page.

Before running the JSP Sample Page, pay attention to the jswdk installation directory, especially the content in the "work" subdirectory. When executing the sample page, you can see how the JSP page is converted into a Java source file and then compiled into a class file (servlet ). The sample pages in the jswdk package are divided into two types: JSP files, HTML files containing a form, which are processed by JSP code. Like ASP, Java code in JSP is executed on the server. Therefore, JSP cannot be viewed using the "View Source File" menu in the browser.Source codeOnly HTML code is displayed. The source code of all examples is provided through a separate "Examples" page.

(Iii) JSP page example

Next we will analyze a simple JSP page. You can create another directory in the examples directory of jswdk to store this file. The file name can be arbitrary, but the extension must be. jsp. From the code list below, we can see that JSP pages have the same structure except Java code more than ordinary HTML pages. Java code is added to the HTML code through the <% and %> symbols. Its main function is to generate and display a string from 0 to 9. The front and back of this string are some text output through HTML code.

<HTML>
<Head> <title> JSP page </title> <Body>
<% @ Page Language = "Java" %>
<%! String STR = "0"; %>
<% For (INT I = 1; I <10; I ++ ){
STR = STR + I;
} %>
Before JSP output.
<P>
<% = STR %>
<P>
After JSP output.
</Body>
</Html>

This JSP page can be analyzed in several parts.

The first is the JSP command. It describes the basic information of the page, such as the language used, whether to maintain the session status, and whether to use buffering. JSP commands start with <% @, and end with %>. In this example, the command "<% @ page Language =" Java "%>" only briefly defines the Java language used in this example (currently, java is the only supported language in JSP specifications ).
The following is the JSP declaration. The JSP declaration can be seen as a place where variables and methods at the class level are defined. JSP declaration by <%! Start, %> end. In this example, "<%! String STR = "0"; %> "defines a string variable. Each declaration must be followed by a semicolon, just like declaring a member variable in a common Java class.
The code block between <% and %> is the Java code that describes the JSP page processing logic, as shown in the for loop in this example.
Finally, the Code between <% = and %> is called a JSP expression, as shown in "<% = STR %>" in this example. JSP expressions provide a simple method to embed JSP-generated values into HTML pages.

Ii. session Status Management
Author: Cactus Studio

Session status maintenance is a must for Web application developers. There are multiple ways to solve this problem, such as using cookies, hiding form input fields, or directly attaching status information to a URL. Java Servlet provides a continuously Valid Session object between multiple requests, which allows users to store and extract session status information. JSP also supports this concept in servlet.

Many descriptions of implicit objects can be seen in Sun's JSP Guide (the implicit meaning is that these objects can be directly referenced and do not need to be explicitly declared, no special code is required to create its instance ). For example, the request object is a subclass of httpservletrequest. This object contains all information about the current browser request, including cookies, HTML form variables, and so on. The Session object is also such an implicit object. This object is automatically created when the first JSP page is loaded and associated with the request object. Similar to session objects in ASP, session objects in JSP are very useful for applications that want to complete a transaction through multiple pages.

To illustrate the specific application of the session object, we use three pages to simulate a multi-page web application. The first page (q1.html) only contains an HTML form that requires the user name to be entered. The Code is as follows:

<HTML>
<Body>
<Form method = post action = "q2.jsp">
Enter your name:
<Input type = text name = "thename">
<Input type = submit value = "Submit">
</Form>
</Body>
</Html>

The second page is a JSP page (q2.jsp). It extracts the thename value from the q1.html form through the request object, stores it as the name variable, and then saves the name value to the session object. The Session object is a set of name/value pairs. Here, the name in the name/value pair is "thename", and the value is the value of the name variable. Because the session object remains valid during the session, the variables saved here are also valid for subsequent pages. Another task of q2.jsp is to ask the second question. The following is its code:

<HTML>
<Body>
<% @ Page Language = "Java" %>
<%! String name = ""; %>
<%
Name = request. getparameter ("thename ");
Session. putvalue ("thename", name );
%>
Your name is: <% = Name %>
<P>
<Form method = post action = "q3.jsp">
What do you like?
<Input type = text name = "food">
<P>
<Input type = submit value = "Submit">
</Form>
</Body>
</Html>

The third page is also a JSP page (q3.jsp). The main task is to display the Q & A result. It extracts the value of thename from the session object and displays it to prove that although the value is input on the first page, it can be retained through the session object. Another task of q3.jsp is to extract user input from the second page and display it:

<HTML>
<Body>
<% @ Page Language = "Java" %>
<%! String food = ""; %>
<%
Food = request. getparameter ("food ");
String name = (string) Session. getvalue ("thename ");
%>
Your name is: <% = Name %>
<P>
You like to eat: <% = food %>
</Body>
</Html>

3. Reference JavaBean Components
Prepared by: Cactus studio Compilation

Javabean is a Java-based software component. JSP provides comprehensive support for the integration of JavaBean components in Web applications. This support not only shortens the development time (you can directly use tested and trusted existing components to avoid repeated development), but also brings more scalability to JSP applications. The JavaBean Component can be used to execute complex computing tasks, interact with databases, and extract data. If we have three JavaBean that display news, stock prices, and weather conditions, you can create a web page that contains all these three functions to instantiate the three beans, you can use HTML tables to locate them in sequence.

To illustrate the application of JavaBean in the JSP environment, we created a bean named taxrate. It has two attributes: product and rate ). The two set methods are used to set these two attributes respectively, and the two get methods are used to extract these two attributes. In practical applications, such beans should generally extract tax rates from the database. Here we simplify this process and allow any tax rate setting. The following is the code list of this bean:

Package tax;
Public class taxrate {
String product;
Double rate;
Public taxrate (){
This. Product = "a001 ";
This. Rate = 5;
}
Public void setproduct (string productname ){
This. Product = productname;
}
Public String getproduct (){
Return (this. Product );
}
Public void setrate (double ratevalue ){
This. Rate = ratevalue;
}
Public double getrate (){
Return (this. rate );
}
}

The <JSP: usebean> tag is used to apply the preceding bean On the JSP page. Depending on the specific JSP engine used, where to configure and how to configure bean may be slightly different. In this article, we put the. Class file of this bean under the C: jswdk-1.0examplesWEB-INFjspbeanstax directory, where tax is a directory dedicated to storing this bean. The following is an example page that applies the above bean:

<HTML>
<Body>
<% @ Page Language = "Java" %>
<JSP: usebean id = "taxbean" Scope = "application" class = "tax. taxrate"/>
<% Taxbean. setproduct ("a002 ");
Taxbean. setrate (17 );
%>
Method 1: <p>
Product: <% = taxbean. getproduct () %> <br>
Tax Rate: <% = taxbean. getrate () %>
<P>
<% Taxbean. setproduct ("a003 ");
Taxbean. setrate (3 );
%>
<B> Method 2: </B> <p>
Product: <JSP: getproperty name = "taxbean" property = "product"/>
<Br>
Tax Rate: <JSP: getproperty name = "taxbean" property = "rate"/>
</Body>
</Html>

Several attributes are defined in the <JSP: usebean> tag. The ID is the ID of the bean on the entire JSP page, and the scope attribute defines the survival time of the bean, the class attribute specifies the class file of the bean (starting from the package name ).

This JSP page uses not only the set and get methods of bean to set and extract attribute values, but also the second method to extract bean attribute values, that is, the <JSP: getproperty> tag. The name attribute in <JSP: getproperty> is the ID of the bean defined in <JSP: usebean>. Its Property Attribute specifies the name of the target property.

It turns out that Java Servlet is an ideal framework for developing web applications. JSP is based on Servlet technology and has been improved in many aspects. The JSP page looks like a common HTML page, but it allows embedding and executing code. At this point, it is very similar to ASP technology. Using the cross-platform running JavaBean Component, JSP provides an excellent solution for separating processing logic and display styles. JSP will surely become a powerful competitor of ASP technology.

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.