JSP tutorial

xiaoxiao2021-03-06  203

JSP tutorial

JSP view 450 times

First, what is JSP JSP (JavaServer Pages) advocated by Sun Microsystems, a dynamic web technology standard established together with many companies, and its URL is http://www.javasoft.com/products/jsp. Jet Java Programs (Scriptlet) and JSP Tag (TAG) in traditional web html files (* .htm, *. Html), the JSP page (* .jsp) is constituted. When the web server encounters a request to access the JSP page, perform the segment of the program, and then return the execution result in the HTML format to the customer. The program clip can operate the database, reordering the web, and send email, etc., which is the functions required to establish a dynamic website. All program operations are executed on the server side. Only the result of the client is transmitted to the client, the lowest requirements for the customer browser, can achieve no PLUGIN, no ActiveX, no java applet, no frame. This article will introduce the method of developing dynamic web pages using JSP technology, and will briefly analyze the difference between JSP technology and Microsoft's ASP technology. Second, how to install and start to experiment JSP technology, first need to establish a running environment, this process is quite simple: 1, download JDK at http://java.sun.com/jdk/ (Java 2 SDK, Standard Edition, v 1.2 .2). 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. Installing the Windows NT environment as an example, JDK installation is first running the downloaded JDK1_2_2_2-win.exe, then modify the system environment parameters, add [x:] / jdk1.2.2 / bin in the PATH parameter and add new Environmental parameter classpath = [x:] / jdk1.2.2 / lib / Tools.jar, where [x:] is a hard disk that installs JDK (C:, D:, etc.). JSWDK installation requires JSwDK1_0_1-win.zip with directory to the root directory (C: /, D: /, etc.), and then you can find /jswdk-1.0.1/ directory on your hard drive. If you don't want to keep JSWDK, you can delete this directory, no system files and registry legacy issues. More detailed installation process and the JDK under Solaris / Unix and Linux, the Tomcat installation can refer to the installation instructions in the obtained file package. 4. Starts the Windows NT environment as an example, execute StartServer.bat in /jswdk-1.0.1/ directory, you can start a web server that supports JSP web technology in JSWDK. In order not to conflict with existing web servers (such as IIS, PWS, etc.), JSWDK's web server uses an 8080 port. After typing http: // localhost: 8080 or http://127.0.0.1:8080, if you can see the JSWDK's welcome page, the JSP experiment environment has been built, and you can enter the next experiment. To turn off the web server, run StopServer.bat. Third, the document directory of the web server included in JSP simple example JSWDK is /jswdk-1.0.1/webpages in the default state, the main document is index.html and index.jsp.jsp in the default state. That is to say, HTTP: // localhost: 8080 is equal to access /jswdk-1.0.1/webpages/index.html.

Create a text file hi.jsp, save a text file hi.jsp, saved in /jswdk-1.0.1/webpages/ directory, its contents are as follows: Hi-JSP Experiment </ Title> </ head> <body> <% string msg = "this JSP test."; Out.print ("Hello World!");%> <H2> <% = msg%> < / h2> </ body> </ html> Type http: // localhost: 8080 / hi.jsp, the web server in JSWDK in JSWDK is enclosed in <% and%> in the JSP file in the address bar of the browser. The Java program statement, where output is output to the web page, the function <% = variable | expression%> is to output the value of variables or expressions in the Java scriptlet to the web page, and the results are shown in Figure 1. Figure 1 assigns the variable MSG to the Chinese string, outputs the Chinese string with <% =%>, or outputs the Chinese string in the English version NT4 and RedHat 6.1, and in Chinese NT 4.0 and Chinese 98, then there will be garbled. 4. Unified website interface JSP support server-side files contain, you can insert multiple other files in a JSP file to implement a unified website interface.</p> <p>Modify the above Hi.jsp and save it as mypage.jsp: <% @ include file = "top.htm"%> <% string msg = "this JSP test."; Out.print ("Hello World!");%> <h2> <% = msg%> </ h2> <% @ include file = "bot.htm"%> Designing the frame structure of the design website, such as FrontPage, Dreamweave, etc., will design a frame structure file Split into two parts, half of the top is saved as top.htm, and half of the following is stored as bot.htm, the code as shown below: <html> <head> <meta http-equiv = "content-type" content = "text / HTML; Charset = GB2312 "> <title> My Home </ 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 =" # fff00 "size = 5> Home title </ font> </ td> </ tr> <tr> <TD bgcolor = "# 837ed1" width = "15%" valign = "TOP" align = "center"> <br> <font color = "# ffffff "> Option </ font> <p> <font color =" # ffffff "> option </ font> </ p> <p> <font color =" # ffffff "> option </ font> </ p> < P> <font color = "# fput>> <p> </ font> </ p> <td width =" 85% "Valign =" TOP "> -------------------------------------------------- -------------------------------------------------- --- --------- </ td> </ tr> </ table> </ body> </ html></p> <p>Type http: // localhost: 8080 / mypage.jsp in the browser's address bar, resulting in Figure 2. Figure 2 The interface of the website can be unified, and the designer can concentrate on handling the user login, connect the database, send Email, etc. on the function module. Each JSP file has the following structure: <% @ include file = "top.htm"%> <% // implement some function%> <% @ include file = "bot.htm"%> Maintenance website interface It is relatively easy to modify top.htm and bot.htm, you can affect all web pages. 5. Server parameter settings JSWDK Web server parameters Save in /jswdk-1.0.1/webserver.xml, open and edit this file with Windows Word board and edit this file. You can modify the default setting value. This section is primarily different for JSWDK, the setting method of Tomcat under Linux is slightly different. Jswdk default document directory is /jswdk-1.0.1/webpages, you can build subdirectories in this directory, such as /jswk-1.0.1/webpages/test, you can use http: // localhost / Test Access this directory, in order to enable this subdirectory to execute the JSP program, you must also join: <service> </ service> section in Web Server.xml: <WebApplication ID = "TEST" mapping = "/ test" docBase = "WebPages / Test "/> and must establish /jswdk-1.0.1/webpages/test/web-inf directory, and copy the following four files from the /jswdk-1.0.1/webpages/web-inf directory: mappings .properties, mime.properties, servlets.properties, and Webapp.properties. Complete these procedures can only notify the JSWDK's web server to perform the JSP program in http: // localhost / test. Sixth, one of the JavaBean JSP webpages is one of the functions of JavaBean technology to expand the program in the web page. JavaBean is a Java class (Class) that has a certain function or an object that has some function or handling a service by encapsulation properties and methods. JavaBean is organized into package for management. In fact, putting a set of JavaBeans in a certain directory, plus a Package for each class, this example is TEST. The directory TEST must be placed in the system environment classpath, and the system can find the JavaBean. JSWDK adds /jswk-1.0.1/webpages/web-inf/jsp/Beans/web-inf/jsp/Beans/, in the default state. When you build your own JavaBean and Package, it is not a simple method in this directory. Here is a simple JavaBean framework.</p> <p>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, its contents are as follows: Package test; public class helloworld {public string name = "My first bean"; public string gethi () {return "Hello from" name;}} HelloWORLD.JAVA After editing, in DOS state, enter the directory /JSWDK-1.0.1/webpages/web-inf/ JSP / Beans /, compiled HelloWorld.java with JDK's Javac commands as follows: Javac HelloWorld.java Note that Java is case sensitive, in the program, the case in the compile command line cannot be written. Compiling success reveals a JavaBean. See how to use this Javabean in JSP. Create a text file hi-bean.jsp with a text editor, and save it in the /jswdk-1.0.1/webpages/test directory, its contents are as follows: <html> <head> <title> javabean test </ title> < / head> <body> <jsp: usebean id = "hellobean" scope = "session" class = "test.HelloWorld" /> <hr> <% hellobean.name = "JSP "; OUT.PRINT (Hellobean.Gethi ());%> </ body> </ html> In the JSP page, use the <JSP: UseBean ... /> syntax to create a JavaBean object and name Hellobean. The reader can see the settings from this simple example, get JavaBeaN properties, and call the JavaBean method. Type http: // localhost: 8080 / test / hi-bean.jsp in the address bar of the browser, resulting as shown in Figure 3. Note that if you modify and recompile the JavaBean program, you need to turn off and restart the result of the WEB server that will be modified after the JSWDK will be valid. If you only modify the JSP file, you don't have to restart the JSWDK's web server. Although this only completed a very simple JavaBean framework, you can design a variety of JavaBeans with this framework. For example, access data from JSP is usually implemented by JavaBean. 7. Database Connection Database Connections is the most important part of the dynamic website. The technology connected to the database in Java is JDBC (Java Database Connectivity). Many database systems have a JDBC driver, and the Java program is connected to the database through the JDBC driver, performing queries, extracting data, etc. Sun has also developed JDBC-ODBC Bridge. With this technology Java program, you can access databases with ODBC drivers. Most database systems have an ODBC driver, so Java programs can access such as Oracle, Sybase, MS SQL. Server and MS Access and other databases.</p> <p>Here is how to implement a dynamic FAQ (FAQ (FAQ) website with Access. First create an Access database FAQ.mdb, where table FAQs have field ID (automatic incremental, and set to primary keyword), Subject (text, length 200), Answers. This table can store common issues and answers to programming knowledge, and then add the System DSN in the ODBC Datasource module of the Control Panel (Control Panel), name 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.</p> <p>The content of FAQ.java is 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.Execute Query:" EX.GetMessage ());} Return RS;}} After using the method introduced by the previous section, compiling FAQ.java, in /jswdk-1.0.1/webpages/test Create a JSP file FAQ.JSP in the directory, its contents are 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.executeQuery ("SELECT * FROM FAQS"); string tt; while (rs.next ()) {tt = rs.getstring ("Answer"); Out.Print ("<li>" rs.getstring ("Subject") "</ li>"); out.print ("<pre>" "</ pre>");}}} rs.close ();%> In the browser's address bar Type http: // localhost: 8080 / test / faq.jsp, FAQ.jsp call JavaBean, read the content from the database and output, resulting in Figure 5. Show the space,</p> <p>This article does not enumerate complex examples of JSP-JavaBean-JDBC / ODBC-database, readers can find and download them to database connection examples from the last recommended URL in this article. Eight, technical analysis Microsoft's ASP technology is also dynamic web development technologies. JSP and ASP are very similar to the form, and the ASP programmer recognizes <%%> and <% =%>. But in-depth exploration, you will find a lot of differences, the most important of which have the following three points: 1, JSP efficiency and security ASP is stored in the source code, to interpret how to run, each ASP web page call requires the source code Explanation, the operating efficiency is not high. In addition, the vulnerability of IIS has made many website source procedures, including the IIS, including websites developed by ASP, and the ASP program is all downloaded. JSP first compiled into a zona code before execution, the byte code is explained by Java Virtual Machine, the efficiency of the source code is high; the server is also available on the server, can Improve the access efficiency of the bytecode. The first call JSP web page may be slightly slow because it is compiled into cache, and it will be much better in the future. At the same time, the JSP source program is unlikely to be downloaded, especially the JavaBean program can completely put it in an universe directory. 2. Component's Component is more convenient for ASP to expand complex functions through COM, such as file uploading, email, and separating business processing or complex calculations into independently reusable modules. JSP has achieved the same functional expansion through JavaBean. In terms of development, COM development is far more complex and cumbersome than JavaBean, and it is not difficult to learn ASP, but learn to develop COM is not simple. JavaBean is more simple, and it can be seen from the above example of this article. It is easy to develop JavaBean. In terms of maintenance, COM must register on the server. If the COM program modified, you must re-register, or even shut down and restart. JavaBean does not need to register and put it in the directory contained in ClassPath. If Javabean has modified, JSWDK and Tomcat also need to turn off and re-run (but not shutdown), but developers have promised that they will do not need to turn off the server in future versions. In addition, JavaBean is complete OOP, which can easily establish a complete set of reusable object libraries, such as user rights control, email auto reply, and more. 3. The JSP adaptation platform is widely available only for NT and IIS. Although there is a CHILISoft plug-in to support ASP, the ASP itself is limited, and the combination of ASP COM must be expanded. It is very difficult to implement the COM under UNIX. JSP is different, almost all platforms support Java, JSP JavaBean can pass unimpeded under all platforms. NT IIS can support JSP through a plugin, 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. Since Apache is widely used in NT, UNIX, and Linux, JSP has a wider range of operational platforms. Although the NT operating system now accounts for a large market share, the advantages of UNIX in the server are still very large, and the new rise Linux is not small. Migrating from one platform to another platform, JSP and Javabean do not even recompile because Java bytecodes are standard with platform-independent.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-128682.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="128682" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.045</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'S_2FE4UO00Cy9C42QFX87ZycG1wGYO1eXen3lpBQJ4SgLk6JFnFugfmISHZNKJ1Ih9ENtTR5YAvvLlyaiv3exz5Q_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>