JSP concise tutorial

Source: Internet
Author: User

1. What is JSP?

JSP is a dynamic web page Technical Standard promoted by Sun Microsystems and jointly established by many companies. Its website is http://www.paioft.com/products/jsp. In the traditional web page HTML file (*. htm ,*. java program snippets (Scriptlet) and JSP tags are added to html to form a JSP webpage (*. jsp ). When the Web server encounters a request to access the JSP webpage, it first executes the program fragment and then returns the execution result to the customer in HTML format. Program snippets can operate databases, redirect webpages, and send emails. This is the function required to build a dynamic website. All program operations are performed on the server, and the results are only obtained after the network is uploaded to the client. The client has the lowest requirements on the client browser and can implement no Plugin, no ActiveX, and no Java Applet, no Frame.
This article describes how to use JSP technology to develop dynamic web pages, and briefly analyzes the differences between JSP technology and Microsoft's ASP technology.

Ii. How to install and start

To experiment with JSP technology, you must first establish a runtime environment. This process is quite simple:
1. Download JDK (Java 2 SDK, Standard Edition, v 1.2.2) at http://java.sun.com/jdk ).
2. Download jswdk (JavaServer Web Development Kit 1.0.1) at http://java.sun.com/products/jsp ). Linux users can download Tomcat 3.0 at http://jakarta.apache.org.

3. Installation

Use Windows environment, modify the system environment parameters, add [x:] jdk1.2.2in to the PATH parameter, and add the new environment parameter CLASSPATH = [x:] jdk1.2.2lib ools. jar, where [x:] is the hard drive letter (c:, d:, etc.) for JDK installation ). Jswdk's installation only needs to release the jswdk1_0_1-win.zip directory to the hard disk root directory (c:, d:, etc.), then you can find the jswdk-1.0.1 directory on the hard disk. If you do not want to retain JSWDK in the future, you can delete this directory without any system file or registry issues. For more details about the installation process and the installation of JDK and Tomcat in Solaris/Unix and Linux, refer to the installation instructions in the downloaded package.

4. Start

Take Windows NT environment as an example, execute startserver. bat in the jswdk-1.0.1 directory, you can start a JSWDK Web server that supports JSP Web technology. To avoid conflicts with existing Web servers (such as IIS and PWS), The JSWDK Web server uses port 8080. After you type http: // localhost: 8080 or http: // 127.0.0.1: 8080 in the address bar of your browser, if you can see the JSWDK welcome page, the JSP experiment environment has been created, you can go to the next lab. To disable the Web server, run stopserver. bat.

Iii. Simple JSP Example
And index. jsp. That is to say, access http: // localhost: 8080is equal to ipvjswdk-1.0.1webpagesindex.html.
Use a text editor, such as Notepad (Notepad) in Windows, to create a text file hi. jsp, saved in the jswdk-1.0.1webpages directory, its content is as follows:


<Html>

<Head>

<Title> Hi-JSP experiment </title>

</Head>

<Body>

<%

String Msg = "This JSP test .";

Out. print ("Hello World! ");

%>

<H2> <% = Msg %>
</Body>

</Html>


In the browser's address bar, type http: // localhost: 8080/hi. jsp, the Web server in JSWDK will execute the Java program statements in the JSP file, including <% and %>, where out. print outputs text to the webpage. The statement <% = variable | expression %> outputs the values of variables or expressions in Java Scriptlet to the webpage.
Assign the Msg variable to a Chinese string and output it with <% = %> or out. print outputs a Chinese string. The experiment runs normally in NT4 and Redhat 6.1 English versions, but garbled characters appear in NT 4.0 and 98 Chinese versions.

Iv. Unified website interface

JSP supports file inclusion on the server, that is, you can insert multiple other files into a JSP file to implement a unified website interface. Modify hi. jsp and save it as mypage. jsp:



<% @ Include file = "top.htm" %>

<%

String Msg = "This JSP test .";

Out. print ("Hello World! ");

%>

<H2> <% = Msg %>
<% @ Include file = "bot.htm" %>


Hidden, the bottom half is saved as bot.htm, the code is shown below:



<Html>

<Head>

<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">

<Title> my homepage </title>

</Head>

<Body>

<Table border = "0" width = "100%" cellpadding = "4" cellspacing = "0" align = "center">

<Tr>

<Td width = "100%" colspan = "2" bgcolor = "#837ED1" align = "center"> <font face = "" color = "# FFFF00" size = 5> homepage title </font>

</Td>

</Tr>

<Tr>

<Td bgcolor = "#837ED1" width = "15%" valign = "top" align = "center"> <br>

<Font color = "# FFFFFF"> options </font> <p> <font color = "# FFFFFF"> options </font> </p>

<P> <font color = "# FFFFFF"> options </font> </p>

<P> <font color = "# FFFFFF"> ...... </font> </p>

<P> </p>

</Td>

& Lt; td width = "85%" valign = "top" & gt;

Bytes ----------------------------------------------------------------------------------------------------------------

</Td>

</Tr>

</Table>

</Body>

</Html>

In the browser's address bar, type http: // localhost: 8080/mypage. jsp.
In this way, the website interface can be unified, and designers can focus on the functional module to process user logon, connect to the database, and send emails. Each JSP file has the following structure:



<% @ Include file = "top.htm" %>

<%

// Implement certain functions

%>

<% @ Include file = "bot.htm" %>


The boundaries of the website are also relatively easy. You only need to modify top.htmand bot.htm to influence all webpages.

V. Server parameter settings

The Web server parameters of JSWDK are saved in the jswdk-1.0.1webserver.xml, And you can modify the default settings by opening and editing the file with a Windows wordpad. This section focuses on JSWDK. The setting methods for Tomcat in Linux are slightly different.
The default document directory of JSWDK is a jswdk-1.0.1webpages, under which sub-directories can be created, such as jswdk-1.0.1webpages est, you can access this directory with http: // localhost/test in the browser, to make this sub-directory executable JSP program, you must also. add the <Service> </Service> section in xml:
<WebApplication id = "test" mapping = "/test" docBase = "webpages/test"/> and you must create the jswdk-1.0.1webpages estWEB-INF directory, and copy the following four files from the jswdk-1.0.1webpagesWEB-INF Directory: mappings. properties, mime. properties, servlets. properties and webapp. properties. After these processes are completed, the JSWDK Web server can be notified to execute the JSP program in http: // localhost/test.

Vi. JavaBean

One of the most attractive aspects of JSP web pages is the ability to expand the functions of programs on the Web page with the JavaBean technology. JavaBean is a Java class that encapsulates attributes and methods to become objects with certain functions or processing services. JavaBean is organized into a package for management. In fact, a group of JavaBean is put together in a directory named XX. Add package XX before the definition of each class. In this example, test is used. The directory test must be placed in the Directory included in the System Environment CLASSPATH before the system can find the JavaBean. JSWDK adds the jswdk-1.0.1webpagesWEB-INFjspeans to CLASSPATH by default. When creating your own JavaBean and package, it is also a simple method to put it in this directory.
The following describes a simple JavaBean framework. Create a text file helloWorld. java in the text editor and save it in the jswdk-1.0.1webpagesWEB-INFjspeans est directory with the following content:



Package test;

Public class helloWorld {

Public String name = "My first bean ";

Public String getHi ()

{

Return "Hello from" + name;

}

}






After editing helloWorld. java, in the DOS state, enter the directory jswdk-1.0.1webpagesWEB-INFjspeans, compile helloWorld. java with JDK javac command as follows:
Javac helloWorld. java
Note that Java is case-sensitive. In a program, letters in the compiled command line cannot be written incorrectly. After successful compilation, A JavaBean is created. The following describes how to use this JavaBean in JSP. Create a text file hi-bean.jsp in the text editor and save it in the jswdk-1.0.1webpages est directory with the following content:



<Html>

<Head>

<Title> test JavaBean </title>

</Head>

<Body>

<Jsp: useBean id = "helloBean" scope = "session" class = "test. helloWorld"/>

<% = HelloBean. getHi () %>

<Hr>

<%

HelloBean. name = "JSP ";

Out. print (helloBean. getHi ());

%>

</Body>

</Html>




On the JSP page, use the <jsp: useBean.../> syntax to create a JavaBean object and name it helloBean. You can see from this simple example how to set and obtain the JavaBean attribute and call the JavaBean method. Type http: // localhost: 8080/test/hi-bean.jsp in the address bar of the browser, as shown in result 3. Note: If you modify and re-compile the JavaBean program, you need to disable and restart the JSWDK Web server before the modification will take effect. If you only modify the JSP file, you do not need to restart the JSWDK Web server.
Although this completes a very simple JavaBean framework, you can follow this framework to design a variety of JavaBean. For example, data access from JSP is usually implemented through JavaBean.

VII. Database Connection

Database connection is the most important part for dynamic websites. The connection technology in Java is JDBC (Java Database Connectivity ). Many database systems have JDBC drivers. The Java program connects to the database through the JDBC driver and performs operations such as querying and extracting data. Sun also developed JDBC-ODBC bridge, with this technology Java program can access the database with ODBC driver, currently most database systems with ODBC driver, therefore, Java programs can Access databases such as Oracle, Sybase, ms SQL Server, and MS Access. The following describes how to use Access to implement a dynamic FAQ (FAQs and answers) website. First, create an Access database faq. mdb, where the table faqs has the field id (automatic incremental type, and set as the primary keyword), subject (text type, length 200), and answers (Remarks type ). This table stores some common programming knowledge questions and answers,
Then, add System DSN to the ODBC Datasource module of the Control Panel, name the faq, and point to faq. mdb. Create a JavaBean named faq. java and save it under the jswdk-1.0.1webpagesWEB-INFjspeans est directory. Faq. java:



Package test;

Import java. SQL .*;



Public class faq {

String sDBDriver = "sun. jdbc. odbc. JdbcOdbcDriver ";

String sConnStr = "jdbc: odbc: faq ";

Connection conn = null;

ResultSet rs = null;



Public faq (){

Try {

Class. forName (sDBDriver );

}

Catch (java. lang. ClassNotFoundException e ){

System. err. println ("faq ():" + e. getMessage ());

}

}



Public ResultSet executeQuery (String SQL ){

Rs = null;

Try {

Conn = DriverManager. getConnection (sConnStr );

Statement stmt = conn. createStatement ();

Rs = stmt.exe cuteQuery (SQL );

}

Catch (SQLException ex ){

System. err. println ("aq.exe cuteQuery:" + ex. getMessage ());

}

Return rs;

}

}

After compiling faq. java with the method introduced in the previous section, create JSP file faq. jsp in the jswdk-1.0.1webpages est directory, the content is as follows:



<Html>

<Head>

<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">

<Title> my FAQ! </Title>

</Head>

<Body>

<P> <B> This Is My FAQ! </B> </p>

<% @ Page language = "java" import = "java. SQL. *" %>

<Jsp: useBean id = "workM" scope = "page" class = "test. faq"/>

<%

ResultSet RS = workM.exe cuteQuery ("SELECT * FROM faqs ");

String tt;

While (RS. next ()){

Tt = RS. getString ("Answer ");

Out. print ("<LI>" + RS. getString ("Subject") + "</LI> ");

Out. print ("<pre>" + tt + "</pre> ");

}

RS. close ();

%>




In the address bar of the browser, type http: // localhost: 8080/test/faq. jsp. The faq. jsp calls JavaBean to read and output the content from the database.
Due to space limitations, this article does not list complex examples of JSP-JavaBean-JDBC/ODBC-database. You can find and download the database connection examples from the URL recommended at the end of this article.

VIII. Technical Analysis
Microsoft's ASP technology is also a dynamic web page development technology. JSP and ASP are very similar in form. ASP programmers can recognize <%> and <% = %> at a glance. However, further exploration will reveal many differences, including the following three main points:

1. JSP is more efficient and secure
ASP is stored as the source code and run as an interpreter. The Source Code must be interpreted for each ASP Web page call, which is inefficient. In addition, the IIS vulnerability has exposed many website source programs, including the websites developed by the author using ASP before. All ASP programs have been downloaded.
JSP is compiled into byte code before execution. bytecode is interpreted and executed by Java Virtual Machine (Java Virtual Machine), which is more efficient than source code interpretation; the server also has the bytecode Cache mechanism, which can improve the access efficiency of bytecode. The first time you call a JSP page, it may be a little slow because it is compiled into a Cache, and it will be much faster in the future. At the same time, JSP Source programs are unlikely to be downloaded, especially the JavaBean program can be placed in a non-External directory.

2. More convenient JSP components (Component)
ASP expands complex functions through COM, such as file uploading, sending emails, and separating business processing or complex computing into independent Reusable Modules. JSP implements the same function expansion through JavaBean.
In terms of development, the development of COM is far more complex and complex than that of JavaBean. Learning ASP is not difficult, but learning to develop COM is not easy. JavaBean is much simpler. From the above examples, we can see that it is very convenient to develop JavaBean.
In terms of maintenance, COM must be registered on the server. If the COM program is modified, it must be re-registered, or even shut down and restarted. JavaBean does not need to be registered and can be placed in the directory contained in CLASSPATH. If the JavaBean is modified, JSWDK and Tomcat still need to be shut down and re-run (but not shut down), but the developer has promised not to shut down the server in future versions.
In addition, JavaBean is fully OOP. You can easily create a set of reusable object libraries for different service processing functions, such as user permission control and automatic email reply.

3. A Wider JSP adaptation platform
ASP currently only applies to NT and IIS. Although there are ChiliSoft plug-ins in Unix to support ASP, ASP itself has limited functions and must be expanded through the combination of ASP + COM. It is very difficult to implement COM in Unix.
JSP is different. Almost all platforms support Java, and JSP + JavaBean can be accessible on all platforms. IIS under NT supports JSP through a plug-in, such as JRUN (http://www3.allaire.com/products/jrun/) or ServletExec (http://www.newatlanta.com. The famous Web server Apache already supports JSP. Because Apache is widely used in NT, Unix, and Linux, JSP has a wider operating platform. Although the NT operating system has a large market share, the Unix advantage in the server is still great, and the new Linux is not small.
Porting from one platform to another, JSP and JavaBean do not even need to be re-compiled, Because Java bytecode is standard and platform-independent. I am very satisfied with the fact that the JSP page of the experiment under NT is running in Linux without being blocked.

IX. Conclusion
To sum up, JSP is a powerful tool for building dynamic websites. Therefore, we recommend it to readers and wish you master JSP and develop excellent websites. ASP programmers can also give it a try. JSP also contains session, request, response/out and other objects.



Appendix

This is an important reference for JSP. If you are interested, you can read it further.



Http://java.sun.com/products/jsp/faq.html

Http://www.esperanto.org.nz/jsp/jspfaq.html

Http://www.zdnet.com/pcweek/stories/news/0,4153,410709,00.html

Http://developer.netscape.com/viewsource/kuslich_jsp/kuslich_jsp.html

Http://web2.java.sun.com/products/jsp/jsp-asp.html

Http://www.asptoday.com/articles/19991022.htm

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.