Introduction to JSP Tutorial (1)

Source: Internet
Author: User
Tags date define comments execution expression html page include stock prices
js| Tutorials | Getting Started Tutorial JavaServer pages (JSP) is a java-based technology for creating dynamic Web pages that support Cross-platform and cross Web servers.

JSP is comparable to Microsoft's active Server Pages (ASP), but the JSP uses HTML-like markup and Java snippets rather than VBScript. When you use a Web server (such as Apache or Netscape server) that does not provide ASP local support, you can consider using JSP. You can also get an ASP add-on software module for these servers, but it's too expensive. Now Sun doesn't charge you for using JSP (although it may be in the future), and components for Solaris, Linux, and Windows systems are easy to get.

Don't confuse the JSP with the server-side JavaScript language. The Web server automatically converts Java snippets generated by JSP into Java fragments (servlets). JSP can also automate many functions, such as using Perl scripts in the past or server-specific APIs such as ASP (application programming interfaces).

We're about to start helping you build an example of a Web site that uses JSP technology.


Prepare your computer to use JSP

You need the JAVA2 Software development Toolbox (J2SDK), formerly called the Java Development Toolbox (JDK), the JavaServer Network Development Toolbox (JSWDK), Tomcat, or other Web servers that support JSP. The company provides free J2SDK and JSWDK for Windows, Solaris, and Linux platforms.

If you want to use JSP on an existing Web server, and the server itself does not support JSP and Java code Snippets, you can try the Allaire company's JRun. It can be used for Netscape's Enterprise server and FastTrack server, Microsoft's Internet Information Server (IIS) and personal Web Server (PWS), Apache and other servers act as attachments to Web servers. You can also use the Java version of the Apache server, which contains the latest JSWDK.

Download and install the required software
Currently, the version number 1.2.2-001 J2SDK downloadable version appears as an installable archive file. This approximately 20MB download software provides a thorough Java development environment that allows you to create any solution that is java-based and leverages the standard core API. In fact, the only condition your Web server uses JSP is to have a Java editor. To have the Web server know the location of the editor, you need to set the JAVA_HOME environment variable to the J2SDK installation directory. If you have already installed in the Windows system and accepted the default directory, add "set java_home=c:1.2.2" to your "Autoexec.bat" File and reboot.

After installing J2SDK, download and install JSWDK or tomcatβ version, the beta version of the java-based Apache Web server. It doesn't matter where you put the JSWDK, as long as you can find it later. In general, place it in the top-level directory so that you do not have to remove another software when replacing JSWDK or JSDK. After installing this file, the preparation is ready, you can start JSP development work.

After you install JSWDK correctly, run the StartServer script to start the Web server so that it listens on port 8080 by default. To see if you have correctly installed the tool after you start the server, 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 the error message in the console window used to start the server, you need to make some changes. The most frequently occurring problem is that the JAVA_HOME environment variable is not set or incorrectly set. To see the current environment variable settings, type the set setting at a DOS prompt.

Begin
Before interpreting the JSP syntax, create a shortcut page that displays the current date and time of the target and then saves it as sample.jsp:

<title>first page</title>
<body>
<%= new Java.util.Date ()%>
</H3>
</body>

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

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

JSP basic syntax
After you finish installing the problem, now go to the JSP syntax. An opportunistic way is to download the grammar card. If you are unfamiliar with Java programming, you may want to take a look at Sun's guidelines. However, web creators do not need to do much Java development. In addition to some method calls, you should use as little Java code as possible in your JSP pages.

With these tips in mind, let's take a look at the JSP directives and the scripting elements, and then we'll explain JavaBeans and suppressed objects. There are five kinds of JSP directives and script elements. In JSP version 1.0, most JSPs are surrounded by a tag that starts with "<%" and ends with "%>." After the updated JSP 1.1 specification was introduced, there was an XML-compatible version.

JSP directives and script elements
Directives <%@ Directive%>
Declarations <%! Declaration%>
Expressions <%= Expression%>
Code fragment/scriptlet <% Code Fragment%>
Comments <%--Comment--%>



Instructions
JSP directives are designed for the JSP engine. They don't directly produce any visible output, but just tell the engine how to handle the rest of the JSP pages. These directives are always enclosed in the "<%@?%>" tag. The two most important directives are "pagepage" and "Include". The "Taglib" directive is not in the discussion column, but it can be used to create a custom tag with JSP1.1.

"Page" instructions are seen almost at the top of all JSP pages. Although not necessary, it allows you to specify:
Where to find the supported Java categories:
<%@ page import= "Java.util.Date"%&GT;

Where to turn on the Web surfers when there is a Java run problem:
<%@ page errorpage= "errorpage.jsp"%&GT;



and whether you need to manage the user's session-level information, which may come from multiple pages (further in the JavaBeans section below):
<%@ page session= "true"%&GT;.



The include directive can divide your content into more manageable elements, such as an element that includes a normal page header or footer. The included web page can be a fixed HTML page or more JSP content:
<%@ include file= "filename.jsp"%>

Statement
JSP declarations allow you to define page-level variables to hold information or to define the support methods that may be required for the remainder of the JSP page. If you find that there are too many code, it is often best to write them in a separate Java class. Declarations are generally in the "<%!?%>" tag. Be sure to end the variable declaration with a semicolon (;) because any content must be a valid Java statement:
<%! int i=0; %>.

An expression
With a JSP expression, the expression evaluation result is converted to a string and is directly included in the output page. The JSP expression is contained in the "<%=?%>" tag without a semicolon unless the semicolon is used in the quoted string part.


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

Code fragment/Script fragment
The code fragment/script fragment (Scriptlets) JSP code fragment or script fragment is embedded in the "<%?%>" tag. This Java code runs when the Web server responds to the request. There may be raw HTML or XML statements around the script fragment, where code snippets can allow you to create conditional execution code or code that uses another piece of code. For example, the following code combination uses expressions and snippets to display the string "Hello" in the H1, H2, H3, and H4 tags. Code snippets are not limited to one line of source code:

<% for (int i=1; i<=4; i++) {%>
<H<%=i%>>Hello</H<%=i%>>
<%}%>

Comments
The last major JSP element is an embedded annotation. Although you can always add HTML comments to a file, users will see the comments when they view the page source code. If you don't want the user to see it, you should embed it in the "<%--?--%>" tag:

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

JSP with JavaBean
While you can put large chunks of code in a script fragment (scriptlet), most Java code is a reusable component called Javabea. JavaBean are similar to ActiveX controls: they all provide common functionality and can be reused.

JavaBean values are obtained by using properties that you can use to access JavaBean settings. To use a person as an analogy, this person is a javabean, the person's name, ID number and address is its attribute. In the JSP website, you basically is by playing "Connect the beans" to make your website dynamic.

Assuming that JavaBean is created before the site, the first thing you need to do is tell the JSP page that it will use a "Bean". You can do this with the "<jsp:useBean>" tag:
<jsp:usebean id= "LocalName" class= "Com.jguru.Person" scope= "Application"/>.

The "<jsp:useBean>" tag requires you to identify the bean using the "id" attribute. Here you provide a name for the rest of the JSP page of the Bean. In addition to the ID attribute, you must tell the page where to look for the bean, or what its Java class alias is. This category property provides the ability to confirm the bean, and some other methods can do the same. The last required element is the scope attribute. With the help of the scope attribute, you can tell the bean to make a single page (by default) [scope= ' page], a request for [scope= requests] as a session [scope=], or an entire application [scope= ' Application "] Keep the message. With a session range, you can easily maintain items such as shopping carts on JSP Web pages.

Once you have a javabean, you can access its properties to customize it. To get the property value, use the "<jsp:getProperty>" tag. With this tag, you can specify the name of the bean to use (from the Usebean "id" field) and the attribute you want to get its value. The actual values are placed in the output:
<jsp:getproperty id= "LocalName" property= "name"/>.

To change the JavaBean property, you must use the "<jsp:setProperty>" tag. For this tag, you need to recognize the bean and attributes again to modify and provide additional new values. If the name is correct, these values can be obtained directly from a submitted table: parameters are obtained:
<jsp:setproperty id= "LocalName" property= "*"/>;

Can be obtained from one parameter, but you must directly name the attributes and parameters:
<jsp:setproperty id= "LocalName" property= "SerialNumber" value= "string"/>

or directly by a name and value to set: <jsp:setproperty id= "LocalName" property= "serialnumber" value= <%= expression%>/>.

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

JSP implied object
The last element associated with the JSP syntax is something called an "implied object." In the JSP code fragment, you can use these hidden objects to interact with the code snippet execution Environment of the JSP page. You should try to access these built-in hidden objects as little as possible. However, in some cases, access to the implied object is acceptable. To take full advantage of the hidden objects, you need to know the latest Java Servlet APIs.
The following table lists the available suppressed object collections.

Implied Object description
Request client requests, including parameters passed from the Get/post request
Response Web page Returns the response of the client
PageContext Manage Page Properties here
Session associated with Request
Application the operating environment of the code fragment
Output stream of Out transfer response
Config code fragment Configuration object
Page JSP pages themselves
Exception exceptions that are not captured in Web pages with errors



What do you use them for? Basically, in your script snippet, you can use them to enter the code snippet that executes the JSP code. Instead of delving into too many servlet API details, let's look at some of the things we can do with them:


Instead of using an expression, you can go directly to the "out" implied object and output some content to the response:
<% out.println ("Hello"); %>.
Instead of sending a parameter directly to JavaBean, you can get the parameter value from the Request object:
<% String name=request.getparameter ("name"); OUT.PRINTLN (name); %>.

In the process of developing your JSP, you need to create a supporting Java Class (Class), if you create a JavaBeans or find a JSP file that adds too much Java source code. It can help you reuse the source code and reduce the JSP page compile time. When you need to create a Java classification file, you must:


Add the Jdswk installationin directory to the path. At the end of the path line of the Autoexec.bat file, add "C:1.2.2/bin".
Use this command to copy the jar file to the "Jrelibext:" Directory: Copy C:jswdk-1.0.1libservlet.jar c:jdk1.2.2jrelibext.

Create a JSP web site
Now it's time to put all these JSP grammars in handy. We'll create a Web page that has an input form that allows the user to enter a stock symbol to get the current stock price (20 minutes). If the input is incorrect, the error page is displayed.

quote.jsp
First, use this code to create a quote.jsp Web page and save it in a Web page directory under the JSWDK installation directory. Most Web pages are standard HTML, which is dotted with JSP code. Line six is a Web page indicating that all errors will be sent to the "errorpage.jsp" text. Line 13th to 15th is a script fragment that shows the table only if the "symbol" argument is supplied. The "If" code snippet ends at 32 to 34 lines. Line 17th defines the JavaBean to use, and line 18th loads the JavaBean symbol attributes from the parameter. Lines 27th through 29 show the Bean's properties. In addition to the "if" snippet, no other Java code is actually involved.

errorpage.jsp
Next, save the following JSP source code in the "errorpage.jsp" file in the Web page directory. "This is an error page" prompts for the first line, which sets the Iserrorpage page hint property to True. The previous page said the location of the error page, this page indicates that this is the error page. JSP-specific code in other JSP files is only used if the implied exception object is accessed. The page displays only its values:

<%@ page iserrorpage= "true"%>

<title>error page</title>
<body>


<!--Print Exception-->
We got ourselves an exception:
<%= Exception%>
<a href= "quote.jsp" >Restart</a>
</body>

Quotes.java
Quotes JavaBean Use yahoo resources to get stock prices. This resource needs to be saved to the "Quotes.java" file in the "Classescomjguru" directory in the JSWDK installation directory. Please edit it here using the Javac editor in JSDK.


Your first JSP page.
After creating the two JSP files, building the JavaBean resource file and editing it, you can load the "quote.jsp" file from http://localhost:8080/quote.jsp to see the results, assuming you haven't changed the JSWDK installation settings, Instead, use a different port. This page can certainly be done more beautifully, but it has achieved the functionality that needs to be implemented, and has shown the functionality of the JSP 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.