Java/jsp good introductory articles to share

Source: Internet
Author: User
Tags execution expression functions getmessage iis connect odbc stmt
JS Building Dynamic Web site with JSP Sun-yi Cuckoo

First, what is JSP JSP (JavaServer Pages) is initiated by the Sun Microsystems Company, a number of companies involved in the establishment of a dynamic Web page technology standards, its Web site for the http://www.javasoft.com/products/jsp. Adding Java program Fragments (scriptlet) and JSP tags (tag) to the traditional Web page HTML file (*.htm,*.html) forms the JSP Web page (*.jsp). When a Web server encounters a request to access a JSP Web page, it first executes the program fragment in it, and then returns the execution results to the customer in HTML format. Program fragments can manipulate databases, redirect Web pages, and send emails, and so on, which is the functionality required to build dynamic Web sites. All programs operate on the server side, the network sent to the client is only the result of the minimum requirements for customer browsers, can be achieved without plugin, no ActiveX, no Java applets, even without frame. This article will introduce the method of using JSP technology to develop dynamic Web pages, and will briefly analyze the differences between JSP technology and Microsoft's ASP technology.
Second, how to install and start in order to experiment JSP technology, the first need to establish a running environment, the 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 ttp://jakarta.apache.org/.
3, installation in the Windows NT environment for example, the JDK installation is to run the downloaded Jdk1_2_2-win.exe first, and then modify the system environment parameters, in the path parameter to add [X:]\jdk1.2.2\bin and add new environment parameters classpath= [X:]\jdk1.2.2\lib\tools.jar, where [x:] is the hard drive character (c:, D:, and so on) where the JDK is installed. JSWDK installation only needs to release the Jswdk1_0_1-win.zip with directory to the hard disk root (C:\, d:\ And so on), and then you can find the \jswdk-1.0.1\ directory on your hard disk. If you do not want to keep JSWDK in the future, you can delete this directory, without any system files and registry legacy problems. More detailed installation procedures, as well as installation of JDK and Tomcat under Solaris/unix and Linux, can refer to the installation instructions in the downloaded packages.
4, starting with the Windows NT environment for example, in the \jswdk-1.0.1\ directory to perform Startserver.bat, you can start a JSWDK Web server support JSP Web technology. To not conflict with existing Web servers (such as IIS, PWS, and so on), the JSWDK Web server uses port 8080. In the browser's address bar type http://localhost:8080 or http://127.0.0.1:8080, if you can see the JSWDK Welcome page on the JSP experimental environment has been completed, you can enter the next experiment. To close the Web server, run Stopserver.bat.
Third, the JSP simple example JSWDK the document directory of the Web server contained in the default state is \jswdk-1.0.1\webpages, and the main document is index.html and index.jsp by default. That is to say, access to http://localhost:8080 equals access \jswdk-1.0.1\webpages\index.html. With a text editor, such as Notepad in Windows, create a text file hi.jsp, saved in the \jswdk-1.0.1\webpages\ directory, which reads as follows:
&LT;TITLE&GT;HI-JSP Experiment </title>
<body>
<%
String MSG = "This JSP test.";
Out.print ("Hello world!");
%>
</body>

Typing the Web server in Http://localhost:8080/hi.jsp,JSWDK in the address bar of the browser executes the Java program statements enclosed in <% and%> in the JSP file. Where Out.print is to output text to Web pages, statements <%= variables | The function of an expression%> is to output the value of a variable or expression in a Java scriptlet to a Web page, performing the result as shown in Figure 1. Figure 1 To assign the variable msg as a Chinese string, with <%=%> output, or with Out.print output Chinese string, then in the English version NT4 and Redhat 6.1 under the normal results of the experiment, and in the Chinese NT 4.0 and Chinese 98, it will appear garbled.
Four, the unified Web site interface JSP support server-side file contains, that is, you can insert multiple other files in a JSP file, to achieve a unified Web site interface. Modify the above hi.jsp and save as mypage.jsp:
<%@ include file= "top.htm"%>
<%
String MSG = "This JSP test.";
Out.print ("Hello world!");
%>
<%@ include file= "bot.htm"%>

With the visual HTML editor, such as FrontPage, Dreamweave, and other design Web site framework structure, the design of the frame structure file divided into two parts, the upper half of the above save as top.htm, the following half saved as bot.htm, the code as follows:
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<title> my homepage </title>
<body>
<table border= "0" width= "100%" cellpadding= "4" cellspacing= "0" align= "center" >
<tr>
&LT;TD width= "100%" colspan= "2" bgcolor= "#837ED1" align= "center" ><font face= "Official script"
Color= "#FFFF00" size=5> homepage title </font>
</td>
</tr>
<tr>
&LT;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" >
--------------------------------------------------------------------------------------------------------------- -
</td>
</tr>
</table>
</body>

Type http://localhost:8080/mypage.jsp in the address bar of the browser, and get the results as shown in Figure 2. Figure 2 This site interface can be unified, and designers can focus on the functional modules to deal with user login, connect the database, send email and so on. Each JSP file has the following structure:


<%@ include file= "top.htm"%>
<%
Implement some features
%>
<%@ include file= "bot.htm"%>

Maintaining the site's interface is also relatively easy, as long as you modify top.htm and bot.htm, you can affect all pages.

Five, server parameter setting
The JSWDK Web server parameter is saved in \jswdk-1.0.1\webserver.xml, and the default setting value can be modified by opening and editing the file with Windows WordPad. This section focuses on a slightly different setting for Tomcat under Jswdk,linux.
JSWDK The default document directory is \jswdk-1.0.1\webpages, where subdirectories, such as \jswdk-1.0.1\webpages\test, can be created in a browser http://localhost/ Test access to this directory, in order to enable this subdirectory to execute JSP program, must also be included in the Webserver.xml <Service></Service> section:
<webapplication id= "test" mapping= "/test" docbase= "Webpages/test"/>
Also, you must create a \jswdk-1.0.1\webpages\test\web-inf directory and copy it from the \jswdk-1.0.1\webpages\web-inf directory: Mappings.properties, Mime.properties, Servlets.properties and Webapp.properties. Complete these procedures to notify the JSWDK Web server of executing JSP programs in Http://localhost/test.

VI. JavaBean
One of the attractions of JSP Web pages is the ability to combine JavaBean technology to expand the functionality of programs in a Web page.
JavaBean is a Java class (class) that encapsulates properties and methods to become an object that has some functionality or that deals with a business. JavaBean is organized into package (packets) for management, in effect, is to put a group of JavaBean together in a certain directory, the definition of each class plus package So-and-So, in this case, test. Directory test must be placed in the directory contained in the system environment classpath, the system can find the JavaBean. JSWDK adds \jswdk-1.0.1\webpages\web-inf\jsp\beans\ to Classpath in default state. It is also an easy way to set up your own JavaBean and package in this directory.
A simple JavaBean framework is described below. Create a text file Helloworld.java with a text editor and save it in the \jswdk-1.0.1\webpages\web-inf\jsp\beans\test directory, which reads as follows:
Package test;
public class HelloWorld {
Public String name = ' My name ';
Public String Gethi ()
{
Return "Hello from" + name;
}
}

Helloworld.java edited, in DOS, into the directory \jswdk-1.0.1\webpages\web-inf\jsp\beans\, with JDK javac command compiled Helloworld.java as follows:

Javac Helloworld.java

Note that Java is case-sensitive, and in a program, the letters in the compilation command line cannot be written in a wrong case.
The success of compilation means that a JavaBean is established. Here's how to use this JavaBean in a JSP. Create a text file hi-bean.jsp with a text editor and save it in the \jswdk-1.0.1\webpages\test directory, which reads as follows:

<title>javabean Test </title>
<body>
<jsp:usebean id= "Hellobean" scope= "session" class= "Test.helloworld"/>
<%= Hellobean.gethi ()%>
<%
Hellobean.name = "JSP";
Out.print (Hellobean.gethi ());
%>
</body>

In the JSP Web page, use the <jsp:usebean .../> syntax to create the JavaBean object and name it Hellobean. The reader can see from this simple example the setting, getting the JavaBean property, and invoking the JavaBean method. Type http://localhost:8080/test/hi-bean.jsp in the address bar of the browser, and get the results as shown in Figure 3.
Note that if you modify and recompile the JavaBean program, the results of the modified Web server that need to shut down and restart the JSWDK will not be effective. If you only modify the JSP file, you do not have to restart the JSWDK Web server.

Although, this only completes a very simple JavaBean framework, but follow this framework can design a variety of javabean. For example, accessing data from a JSP is usually done through JavaBean.

Vii. Database Connection
A database connection is the most important part of a dynamic web site, and the technology for connecting to the database in Java is JDBC (Java Database Connectivity). Many database systems have JDBC drivers, and Java programs connect to the database through the JDBC driver, executing queries, fetching data, and so on. Sun also developed JDBC-ODBC Bridge, which uses Java programs to access databases with ODBC drivers, and most database systems now have ODBC drivers, so Java programs can access Oracle, Sybase, MS SQL Databases such as server and MS Access. Here's how to implement a Dynamic FAQ (FAQ and Answer) Web site with access.
First, create an Access database Faq.mdb, where the table FAQs has a field ID (AutoIncrement, and set as the primary key), subject (type, length 200), Answers (memo type). This table can contain some common questions and answers about programming knowledge, as shown in Figure 4.
Figure 4

Then, add system DSN to the ODBC DataSource module in Control Panel, name the FAQ, and point to Faq.mdb.
Create a JavaBean, named Faq.java, and save it in the \jswdk-1.0.1\webpages\web-inf\jsp\beans\test directory. The contents of Faq.java are as follows:

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.executequery (SQL);
}
catch (SQLException ex) {
System.err.println ("Aq.executequery:" + ex.getmessage ());
}
Return RS;
}
}
After compiling Faq.java with the method described in the previous section, create a JSP file faq.jsp under the \jswdk-1.0.1\webpages\test directory, which reads as follows:

<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<title> My FAQ!</title>
<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.executequery ("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 ();
%>
Type http://localhost:8080/test/faq.jsp,faq.jsp call JavaBean in the address bar of the browser, read the content from the database and output, and get the results as shown in Figure 5.

Limited to space, this article cannot enumerate the complex examples of the jsp-javabean-jdbc/odbc-database, which readers can find and download to the database connection paradigm from the URLs recommended at the end of this article.

VIII. Technical Analysis
Microsoft's ASP technology is also a dynamic web development technology. JSP and ASP form very similar, ASP programmer at a glance can recognize <%%> and <%=%>. But there are a lot of differences that can be found in deep exploration, the main one being the following three points:
1, JSP efficiency and security is higher
ASP to the source form storage, to explain the way to run, each ASP Web page calls need to explain the source code, running efficiency is not high. In addition, the IIS vulnerability has caused many web site source program exposure, including the author of the previous use of ASP developed Web site, the ASP program has been downloaded to the people.
JSP before execution is compiled into the bytecode (byte code), bytecode by the Java Virtual machine (Java Machine) Interpretation of the execution, more efficient than the source interpretation, the server also has bytecode cache mechanism, can improve the access efficiency of bytecode. The first call to the JSP Web page may be a bit slow because it is compiled into a cache and is much faster later. At the same time, the JSP source program is not likely to be downloaded, especially the JavaBean program can be placed in the wrong directory.
2, the JSP component (Component) way is more convenient
ASP extends complex functions through COM, such as file uploads, sending emails, and separating business processing or complex computing into independent reusable modules. JSP achieves the same function expansion through JavaBean.
In the development aspect, the development of COM is far more complex and tedious than JavaBean, it is not difficult to learn ASP, but it is not easy to learn to develop COM. And JavaBean is much simpler, from the above examples in this article can see that the development of JavaBean is very convenient.
In terms of maintenance, COM must be registered on the server, and if the COM program is modified, it must be registered or even shut down and restarted. JavaBean do not need to register, put in the classpath contained in the directory on the line. If JavaBean is modified, then JSWDK and Tomcat now need to shut down and rerun (but not shut down), but the developer has promised to do so in later versions without shutting down the server.
In addition, JavaBean is a complete oop, can easily set up a reusable object library for different business processing functions, such as user Rights control, email automatic reply and so on.
3, the JSP adapts the platform to be more extensive
ASP is currently available only for NT and IIS. Although there are chilisoft Plug-ins under UNIX to support ASP, the ASP itself has limited functionality and must be augmented by a combination of asp+com, which is difficult to implement under UNIX.
JSP is different, almost all platforms are supported Java,jsp+javabean can be all over the platform to the unimpeded. NT under IIS can support 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 has been able to support JSP. Because Apache is widely used on NT, UNIX, and Linux, JSP has a wider operating platform. Although the NT operating system now occupies a large market share, but the advantages of UNIX in the server is still very large, and the new rise of Linux is not small.
Porting from one platform to another, JSP and JavaBean don't even have to recompile because Java bytecode is standard and platform-independent. The author will be in the NT under the experiment JSP page intact to get Linux under the run up, feel very satisfied.
Ix. Conclusion
To sum up, JSP is a dynamic site to build a sharp weapon, so recommended to the reader, wish you master JSP, to develop excellent website. ASP programmer also Please try, JSP also has session, request, response/out and other objects, try how to personally.

Attached text
Here is an important reference for JSP, interested readers can read 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.