JSP getting started tutorial (1)

Source: Internet
Author: User
Tags stock prices

 
Assumerver Pages (JSP) is a Java-based technology used to create dynamic webpages that support cross-platform and cross-Web servers.

JSP is comparable to Microsoft's Active Server Pages (ASP), but JSP uses HTML-like tags and Java code snippets instead of VBScript. When you use a Web server (such as Apache or Netscape Server) that does not provide local ASP support, you can consider using JSP. Although you can add an ASP software module to these servers, it is too expensive. At present, Sun will not charge you for using JSP (although it may be charged in the future). Moreover, components used for Solaris, Linux, and Windows systems are easy to obtain.

Do not confuse JSP with the JavaScript language on the server. The Web server automatically converts the Java code snippets generated by JSP into Java snippets (servlets ). JSP can also automatically control many functions, such as using Perl scripts to write functional programs or server-specific APIs such as ASP (application programming interfaces ).

We are about to help you build a website Example Using JSP technology.


Prepare the computer to use JSP

You need Java2 Software Development Toolkit (J2SDK), formerly known as Java Development Toolkit (JDK), JavaServer Network Development Toolkit (JSWDK), Tomcat, or other Web servers that support JSP. Shengyang provides free J2SDK and JSWDK for Windows, Solaris, and Linux platforms.

If you want to use JSP on an existing Web server that does not support JSP and Java code snippets, you can try Allaire's Jrun. It can act as Web Server attachments for Enterprise Server and Fasttrack Server of Netscape, Microsoft Internet Information Server (IIS), Personal Web Server (PWS), Apache, and other servers. You can also use the Java version of the Apache server, which includes the latest JSWDK.

Download and install the required software
Currently, the downloadable J2SDK version 1.2.2-001 is available in the form of an installed archive file. This 20 mb download package provides a thorough Java development environment that allows you to create any solutions based on Java and Utilize standard core APIs. In fact, the only condition for your Web server to use JSP is to have a Java editor. To let the Web server know the editor location, set the JAVA_HOME environment variable to the J2SDK installation directory. If you have installed and accepted the default directory in Windows, add "set JAVA_HOME = C: 1.2.2" to your "autoexec. bat file, and then restart.

After J2SDK is installed, download and install JSWDK or Tomcat beta version, that is, Java-based Apache Web Server beta version. It doesn't matter where you put JSWDK, as long as you can find it later. Usually, place it in the top-level directory so that you do not need to delete another software when replacing JSWDK or JSDK. After this file is installed, the preparation is ready. You can start JSP development.

After JSWDK is correctly installed, run the "startserver" script to start the Web server and enable it to listen to port 8080 by default. To check whether the tool is correctly installed after the server is started, load a JSP sample file (http: // locahost: 8080/examples/jsp /). If you can successfully run these sample files, you have installed the software correctly. If you see an error in the console window used to start the server, you need to modify it. The most common problem is that the JAVA_HOME environment variable is not set or incorrect. To view the current environment variable settings, type "set" at the DOS prompt.

Start
Before interpreting JSP syntax, create a shortcut page to display the current date and time of the project, and save it as sample. jsp:

<Html>
<Head>
<Title> First Page </title>
</Head>
<Body>
<H3> Today is:
<% = New java. util. Date () %>
</H3>
</Body>
</Html>.

Put this file and all your HTML and JSP pages in the webpage directory under the JSWDK installation directory. You can load this webpage from http: // localhost: 8080/sample. jsp. When the Web page is accessed for the first time, the Web server will compile the JSP into a Java code segment so that you can see the current date and time.

You have downloaded, installed, and configured the development environment. You can start to learn JSP syntax and create your own JSP-based solution.

JSP basic syntax
After talking about the installation, we will now discuss the JSP syntax. A opportunistic solution is to download the syntax card. If you are not familiar with Java programming, you may want to take a look at Sun's guide. However, web page creators do not need to perform much Java development. In addition to some method calls, you should use Java code as little as possible in your JSP webpage.

Remember the above prompts. Let's first take a look at JSP commands and script elements, and then we will explain JavaBeans and implicit objects. There are five JSP commands and script elements. In JSP 1.0, most JSPs are enclosed by a tag starting with "<%" and ending with "%>. After the updated JSP 1.1 specification is introduced, a version compatible with XML is available.

JSP commands and script elements
Directives <% @ directive %>
Declarations <%! Declaration %>
Expressions <% = expression %>
Code Fragment/Scriptlet <% code fragment %>
Comments <% -- comment -- %>



Command
JSP commands are designed for the JSP Engine. Instead of directly generating any visible output, they just tell the engine how to process other JSP pages. These commands are always included in "<% @? %> "Marked. The two most important commands are "pagePage" and "Include ". The "Taglib" command is not discussed, but can be used to create a custom tag using JSP1.1.

The "Page" command is displayed on the top of almost all JSP pages. Although not required, it allows you to specify:
Where to find the supported Java categories:
<% @ Page import = "java. util. Date" %>,

Where will the Internet surfers be directed when a Java running problem occurs:
<% @ Page errorPage = "errorPage. jsp" %>,



Whether you need to manage the user's session-level information, which may come from multiple webpages (this will be further described in the following JavaBeans Section:
<% @ Page session = "true" %>.



The "Include" command can divide your content into more manageable elements, such as an element that includes a common page header or footer. The contained webpage can be a fixed HTML page or more JSP content:
<% @ Include file = "filename. jsp" %>

Statement
The JSP Declaration allows you to define page-level variables to save information or define the support methods that may be required for the rest of the JSP page. If you find that there are too many codes, you 'd better write them into an independent Java class. The statement is generally in the "<%! ? %> "Marked. You must end the variable declaration with a semicolon (;), because any content must be a valid Java statement:
<%! Int I = 0; %>.

Expression
With a JSP expression, the expression evaluation result is converted into a string and directly included in the output page. The JSP expression is contained in "<% =? "%>" Indicates that there is no semicolon, unless you use a semicolon in the string section with quotation marks.


<% = I %>
<% = "Hello" %>.

Code snippets/script snippets
Code snippets/Scriptlets JSP code snippets or script snippets are embedded in "<%? '%>. This Java code runs when the Web server responds to the request. The script fragment may be surrounded by original HTML or XML statements. In these cases, the code fragment allows you to create conditional Execution Code or use code of another piece of code. For example, the following code combines expressions and code snippets to display the string "Hello" in the H1, H2, H3, and H4 tags ". Code snippets are not limited to a single line of source code:

<% For (int I = 1; I <= 4; I ++) {%>
<H <% = I %> Hello </H <% = I %>
<% }%>.

Note
The last major JSP element is embedded comments. Although you can always add HTML comments to the file, the comments are displayed when you view the page source code. If you don't want users to see it, you should embed it into "<% --? -- %> "Marked:

<% -- Comment for server side only -- %>.

JSP with JavaBean
Although you can place a large segment of code in a script segment (scriptlet), the vast majority of Java code is a reusable component named JavaBea. JavaBean is similar to ActiveX Controls: they provide common functions and can be reused.

The value of JavaBean is obtained through some attributes. You can access the JavaBean settings through these attributes. For example, a person is a JavaBean, whose name, ID number, and address are attributes. On the JSP website, you basically make your website dynamic by playing "Connect the beans.

Suppose that the JavaBean is created before the website. The first thing you need to do is to tell the JSP page that it will use a "Bean ". You can use the <jsp: useBean> mark to do this:
<Jsp: useBean id = "localName" class = "com. jguru. Person" scope = "application"/>.

The "<jsp: useBean>" tag requires that you use the "id" attribute to identify the Bean. Here you provide a Bean named for the rest of the JSP page. In addition to the "id" attribute, you must also tell the webpage where to find the Bean or its Java class name. This type attribute provides the Bean validation function. Other methods can also do this. The last required element is the "scope" attribute. With the help of the "scope" attribute, you can tell the Bean to be a single page (default) [scope = "page"], [scope = "request"] the request is a session [scope = "session"], or leave information for the entire application [scope = "application. With the session range, you can easily maintain items such as shopping carts on the JSP page.

Once you become a JavaBean, you can access its attributes to customize it. To obtain the property value, mark it with <jsp: getProperty>. With this tag, you can specify the name of the Bean to be used (obtained from the "id" Field of useBean) and the attribute of the Bean value you want. The actual value is put in the output:
<Jsp: getProperty id = "localName" property = "name"/>.

To change the JavaBean attribute, you must use the <jsp: setProperty> tag. For this tag, you need to identify the Bean and attributes again to modify and provide additional values. If the name is correct, these values can be obtained directly from a submitted table: parameter:
<Jsp: setProperty id = "localName" property = "*"/>;

It can be obtained from a parameter, but you must directly name the attributes and parameters:
<Jsp: setProperty id = "localName" property = "serialNumber" value = "string"/>

You can also directly set the value using a name and value: <jsp: setProperty id = "localName" property = "serialNumber" value = <% = expression %>/>.

The last thing about JavaBean: In order for the Web server to find JavaBean, You need to place its category files in a special location. With JSWDK, the most convenient location is the class directory under the installation directory, such as the jswdk-1.0.1classes.

JSP implicit object
The final element related to JSP syntax is something called an implicit object. In JSP code snippets, you can use these hidden objects to interact with the execution environment of JSP page code snippets. Access these built-in hidden objects as little as possible. However, in some cases, access to the implicit object is acceptable. To make full use of implicit objects, you need to understand the latest Java Servlet API.
The following table lists the available hidden object sets.

Implicit Object Description
Request client requests, including parameters passed from GET/POST requests
Response from the response webpage to the client
PageContext manages webpage properties here
Session associated with the request
Runtime Environment of application code snippets
Output stream for sending response from out
Config code snippet configuration object
Page JSP page itself
An exception that is not captured in a webpage with a wrong exception



What are these functions for? How do you use them? Basically, in your script snippets, you can use them to enter the code snippets that execute JSP code. You don't need to know too much details about Servlet APIs. Let's take a look at some things you can do with them:


You can directly enter the "Out" implicit object without an expression and output some content to the response:
<% Out. println ("Hello"); %>.
You do not need to send a parameter directly to JavaBean. You can obtain the parameter value from the request object:
<% String name = request. getParameter ("name"); out. println (name); %>.

When you use JSP for development and more development, If you create a JavaBeans or find that too many Java source code is added to the JSP file, you need to create a supported Java class to help you reuse the source code and reduce the JSP page Compilation Time. To create a Java classification file, you must:


Add the JDSWK installationin directory to PATH. Add "C: 1.2.2/bin" to the end of the PATH row of the autoexec. bat file ".
Copy the JAR file to the "jrelibext:" Directory: copy c: jswdk-1.0.1libservlet.jar c: jdk1.2.2jrelibext.

Create a JSP website
Now it is time to use all these JSP languages. We will create a webpage with an input form that allows users to enter a stock code to get the current stock price (20 minutes ). If the input is incorrect, an error page is displayed.

Quote. jsp
First, use this code to create a quote. jsp webpage and save it to the webpage directory under the JSWDK installation directory. Most Web pages are standard HTML, and JSP code is scattered. The sixth line is a Web page indicating that all errors will be sent to the "errorPage. jsp" text. Lines 13th to 15 are a script fragment. It mainly indicates that the table is displayed only when the "symbol" parameter is provided. The "If" code segment ends in lines 32 to 34. The 17th rows define the JavaBean to be used, and the 18th rows load the symbol attribute of the JavaBean from the parameter. The Bean attributes are displayed in rows 1 to 29. Except for the "if" code segment, it does not actually involve other Java code.

ErrorPage. jsp
Next, save the following JSP source code to the "errorPage. jsp" file in the webpage directory. The prompt "this is an error webpage" is the first line. It sets the isErrorPage webpage prompt attribute to true. The previous page indicates the location of the incorrect webpage. This page indicates that this is the incorrect webpage. JSP code in other JSP files can only be used to access hidden exception objects. The webpage only displays its value:

<% @ Page isErrorPage = "true" %>

<Html>
<Head>
<Title> Error Page </title>
</Head>
<Body>

<H1> Our Error Page
<! -- Print Exception -->
We got ourselves an exception:
<% = Exception %>
<A href = "quote. jsp"> Restart </a>
</Body>
</Html>.

Quotes. java
Quotes JavaBean uses Yahoo resources to obtain stock prices. You need to save the resource to the quotes. java file in the "classescomjguru" directory under the JSWDK installation directory. Please use the Javac editor in JSDK to edit it here.


Your first JSP webpage.
After these two JSP files are created, the JavaBean resource file is created, and edited, you can start from http: // localhost: 8080/quote. jsp load "quote. jsp file to view the results, assuming you did not change the JSWDK installation settings, instead use another port. Of course, this web page can be more beautiful, but it has implemented the functions that need to be implemented, and shows the JSP functions well.

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.