Jsp entry examples - multimedia classrooms single booking
Abstract: jsp entry examples - multimedia classrooms single booking
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle">
This article will demonstrate how you use Apache Tomcat JSP + to create multimedia classrooms appointment alone.
1, interface requirements:
The first week alone multimedia classrooms appointment
I would like to booking <table width = "56%" border = 1> <tr> <td width="12%"> </ td> <td width="12%"> Monday </ td> <td width = "12%"> Tuesday </ td> <td width="12%"> Wednesday </ td> <td width="12%"> Thursday </ td> <td width="13%"> Friday </ td> <td width="13%"> Saturday </ td> <td width="14%"> Sunday </ td> </ tr> <tr> <td> the first quarter </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td > </ tr> <tr> <td> section </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> < / td> <td> </ td> <td> </ td> </ tr> <tr> <td> the third quarter </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> </ tr> <tr> <td> IV </ td> < td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> </ tr> <tr> <td> Section V </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> </ tr> <tr> <td> VI </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> </ tr> <tr> <td> Section VII </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> </ tr> <tr> <td> VIII </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td> </ td> <td > </ td> <td> </ td> </ tr> </ table>
Among them, "I would like to reserve" hyperlinks to fill booking single page.
Second, install Tomcat
Tomcat installed first, and then we set up the working directory.
First, in the c: \ Tomcat 5.0 \ webapps directory to create a subdirectory called yyd. Then yyd subdirectory,
Creating standards for Web application directory structure:
C: \ Tomcat 5.0 \ webapps \ yyd
C: \ Tomcat 5.0 \ webapps \ yyd \ WEB-INF
C: \ Tomcat 5.0 \ webapps \ yyd \ WEB-INF \ classes
C: \ Tomcat 5.0 \ webapps \ yyd \ WEB-INF \ classes \ dingdan
Third, we set up the appointment database single database for storing records of the appointment of teachers, open Access, to create the database dingdan, archiving kept in:
C: \ Tomcat 5.0 \ webapps \ yyd \ WEB-INF \ dingdan.mdb
In creating 25 Table: guestbook1, guestbook2 … guestbook25. Like the structure of each table, as follows:
Field Description </ td> <td> field </ td> <td> data types </ td> <td> whether empty </ td> </ tr> <tr> <td> # </ td > <td> serial_no </ td> <td> automatically # </ td> <td> not </ td> </ tr> <tr> <td> name </ td> <td> name </ td> < td> text </ td> <td> not </ td> </ tr> <tr> <td> several weeks </ td> <td> week </ td> <td> text </ td> <td> not </ td> </ tr> <tr> <td> first sections of </ td> <td> jie </ td> <td> text </ td> <td> not </ td> </ tr> <tr> <td> class topics </ td> <td> content </ td> <td> text </ td> <td> not </ td> </ tr> </ table>
We use 25 tables corresponding one semester of 25 weeks, so manageable. Of course, it could also be a table. Week and jie field with the text type.
Fourth, set up data sources
To win2000 example, from the control panel to open the management tools "ODBC data source management," and click "System DSN" tab, in which data sources dingdan added, pointing us in the creation of a database dingdan.mdb above.
5, multimedia classrooms appointment single file structure
Making use of this appointment will be five single document:
Dingdan.jsp choose week, the main document.
Index1.jsp appointment this week showed that the document jsp
Adddingdan.jsp fill the appointments for teachers alone
Okdingdan.jsp appointment will be recorded into the database
Dingdan.java for connecting to database
(1) Dingdan.jsp booking option is for teachers of the week, jsp documents, and is responsible for the index1.jsp transmission parameters. The original code is as follows:
<% @ Page contentType = "text / html; gb2312 charset ="%>
<body>
Multimedia classrooms appointment alone
<table Border="0" width="103%" cellspacing="0" cellpadding="0" height="1">
<tr> <form Name="guideform" action=index1.jsp target="_blank" method="post">
<select Name="guidelinks">
<option SELECTED value="1"> first week
<option Value="2"> second week
<option Value="3"> third week
<option Value="4"> fourth week
<option Value="5"> fifth week
<option Value="6"> sixth week
<option Value="7"> seventh week
<option Value="8"> 8 weeks
<option Value="9"> ninth week
<option Value="10"> 10th week
<option Value="11"> Week 11
<option Value="12"> 12 weeks
<option Value="13"> 13 weeks
<option Value="14"> 14th week
<option Value="15"> 15th week
<option Value="16"> 16th week
<option Value="17"> 17 weeks
<option Value="18"> 18th week
<option Value="19"> 19 weeks
<option Value="20"> 20th week
<option Value="21"> 21 weeks
<option Value="22"> 22 weeks
<option Value="23"> 23 weeks
<option Value="24"> 24 weeks
<option Value="25"> 25th week
</ Select> <input type = "submit" name = "go" value = "Go!"
</form>
</ Tr>
</ Table>
</ Body>
(2) to show that this week's index1.jsp booking situation
Week booking situation with an array week [] [] record, first of all, the array will be given initial:
For (int i = 0; i <= 8; i + +)
For (int j = 0; j <= 7; j + +)
Week [i] [j] = "";
Week [0] [1] = "Monday";
Week [0] [2] = "Tuesday";
Week [0] [3] = "Wednesday";
Week [0] [4] = "Thursday";
Week [0] [5] = "Friday";
Week [0] [6] = "Saturday";
Week [0] [7] = "Sunday";
For (int i = 1; i <= 8; i + +)
Week [i] [0] = "" + i + "Festival";
This array of other elements of value from the database to read out
Rs = showBean.executeQuery ( "SELECT * FROM guestbook" + sn1);
While (Rs.next ()) (
E1 = Rs.getString (the "week");
Name1 = Rs.getString ( "name");
E2 = Rs.getString ( "jie");
Int k = Integer.parseInt (e1);
Int l = Integer.parseInt (e2);
Week [l] [k] = name1;
)
Finally, a week shown in the table [] []. The original code is as follows:
<% @ Page contentType = "text / html; gb2312 charset ="%>
<head>
<script LANGUAGE="javascript">
Function newwin (url) (
Var newwin = window.open (url, "newwin", "toolbar = no, location = no, directories = no,
Status = no, menubar = no, scrollbars = yes, resizable = yes, width = 400, height = 350 ");
Newwin.focus ();
Return false;
)
</ Script>
</ Head>
<body Bgcolor="#FFFFCC">
<script LANGUAGE="javascript">
Function submit11 ()
(
Self.location.replace ( "index1.jsp")
)
</ Script>
<%
String sn, sn1;
String e1;
String name1;
String e2;
String week [][]= new String [9] [8];
Int m1 and m2;
Sn = request.getParameter ( "guidelinks");
If (sn! = Null) (
Session.setAttribute ( "SN" sn);
Sn1 = (String) session.getAttribute ( "SN");
Else ()
Sn1 = (String) session.getAttribute ( "SN");)
%>
No. <%% sn1 => weeks multimedia classrooms single booking
<% @ Page language = "java" import = "java.sql .*"%>
<%
ResultSet Rs = null;
For (int i = 0; i <= 8; i + +)
For (int j = 0; j <= 7; j + +)
Week [i] [j] = "";
Week [0] [1] = "Monday";
Week [0] [2] = "Tuesday";
Week [0] [3] = "Wednesday";
Week [0] [4] = "Thursday";
Week [0] [5] = "Friday";
Week [0] [6] = "Saturday";
Week [0] [7] = "Sunday";
For (int i = 1; i <= 8; i + +)
Week [i] [0] = "" + i + "Festival";
Try (
Rs = showBean.executeQuery ( "SELECT * FROM guestbook" + sn1);
While (Rs.next ()) (
E1 = Rs.getString (the "week");
Name1 = Rs.getString ( "name");
E2 = Rs.getString ( "jie");
Int k = Integer.parseInt (e1);
Int l = Integer.parseInt (e2);
Week [l] [k] = name1;
)
Rs.close ();
) Catch (Exception e) (
System.out.println (e.toString ());
)
ShowBean.closeConn ();
%>
<% Out.print ( "I want to reserve");%>
<table Border='1' cellspacing='0' width='632' bgcolor='#ffffff bordercolorlight='red' bordercolordark='red'>
<% For (m1 = 0; m1 <= 8; m1 + +) (%>
<tr>
<% For (m2 = 0; m2 <= 7; m2 + +) (%>
<td Bgcolor='#33ccff'> <% = week [m1] [m2]%> </ td>
<%)%>
<tr>
<%)%>
</ Table>
Certain production
(3) add.jsp to fill appointments for teachers to single ok_add.jsp transfer form data.
The original code below, the function valiform () client for the certification form.
<% @ Page contentType = "text / html; gb2312 charset ="%>
<head>
<script LANGUAGE="JavaScript">
Function valiform () (
If (document.form1.content.value ==""){
Alert ( "Please type the subject!");
Document.form1.content.focus ();
Return false;
)
Else if (document.form1.name.value ==""){
Alert ( "Please enter names!");
Document.form1.name.focus ();
Return false;
)
Else if (document.form1.week.value ==""){
Alert ( "Please enter weeks!");
Document.form1.week.focus ();
Return false;
)
Else if (document.form1.jie.value ==""){
Alert ( "Please enter the festival!");
Document.form1.jie.focus ();
Return false;
)
)
</ Script>
</ Head>
<body>
<form METHOD=POST action="ok_add.jsp" name=form1 onSubmit="return valiform()">
Single-booking
Reservation alone can not be changed, please carefully fill!
<table Width='60%' height='120'>
<tr>
<td> Name: <input TYPE = "text" name = "name" value = ""> </ td>
</ Tr>
<tr>
<td> Week:
<select Name="week" size="1">
<option Style="color: #000000" value="1" selected> Monday </ option>
<option Style="color: #000000" value="2"> Tuesday </ option>
<option Style="color: #000000" value="3"> Wednesday </ option>
<option Style="color: #000000" value="4"> Thursday </ option>
<option Style="color: #000000" value="5"> Friday </ option>
<option Style="color: #000000" value="6"> Saturday </ option>
<option Style="color: #000000" value="7"> Sunday </ option>
</ Select>
</ Td>
<tr>
<td> Sections: <select name = "jie" size = "1">
<option Style="color: #000000" value="1" selected> the first quarter </ option>
<option Style="color: #000000" value="2"> section </ option>
<option Style="color: #000000" value="3"> the third quarter </ option>
<option Style="color: #000000" value="4"> IV </ option>
<option Style="color: #000000" value="5"> Section V </ option>
<option Style="color: #000000" value="6"> VI </ option>
<option Style="color: #000000" value="7"> Section VII </ option>
<option Style="color: #000000" value="8"> VIII </ option>
</ Select>
</ Td>
</ Td>
</ Tr>
<tr>
<td> Topics: <input type "text" name = "content" value =""></ td>
</ Tr>
<tr>
<td Align="center"> <input TYPE="submit" size="4" value="æäº¤" class="buttonface">
<input TYPE="reset" size="4" value="é‡å†™" class="buttonface"> </ td>
</ Tr>
</ Table>
</ Form>
</ Body>
(4) ok_add.jsp documents will be teachers appointment data into the database and refresh index1.jsp
<head>
<% @ Page contentType = "text / html; gb2312 charset ="%>
</ Head>
<% @ Page language = "java" import = "java.sql .*"%>
<%
Int i = 0;
String name = new String (request.getParameter ( "name"). GetBytes ( "8859_1"));
String em = new String (request.getParameter ( "week"). GetBytes ( "8859_1"));
String em2 = new String (request.getParameter ( "jie"). GetBytes ( "8859_1"));
String content = new String (request.getParameter ( "content"). GetBytes ( "8859_1"));
String sn = (String) session.getAttribute ( "SN");
String sql = "select * from guestbook" + sn;
ResultSet rs = addBean.executeQuery (sql);
While (rs.next ()) (
String ee = rs.getString (the "week");
String ee1 = rs.getString ( "jie");
If ((em.equals (ee ))&&( em2.equals (ee1))) (
I = 1;
Break;
)
)
Rs.close ();
If (i == 0) (
String strSQL = "insert into guestbook" sn + + "(name, week, jie, content) values ( '" + name + "','" em + + + "','"+ em2 +"','"
Content + "')";
AddBean.executeUpdate (strSQL);
Out.print ( "Your reservation has been saved to the database, thank you!");
) Else if (i == 1) (
If (em.equals ( "7")) (out.print ( "Sunday" + "" + em2 + "section, it was booking, please re-fill single !!");
Else ()
Out.print ( "a week" em + + "" + em2 + "section, it was booking, please re-fill single !!");
)
)
AddBean.close ();
%>
<body Onload="load2()">
<script Language=javascript>
Function load2 () (
Opener.setTimeout ( "submit11 ()", 1500)
Self.setTimeout ( "exit ()", 1500)
)
Function exit () (
Window.close ()
)
</ Script>
</ Body>
(5) dingdan.java documents used to connect databases
Package dingdan; import java.sql .*; public class dingdan (String sDBDriver = "sun.jdbc.odbc.JdbcOdbcDriver" String sConnStr = "jdbc: odbc: dingdan"; private Connection conn = null; private Statement stmt = null; ResultSet rs = null; public dingdan () (try (Class.forName (sDBDriver);) catch (java.lang.ClassNotFoundException e) (System.err.println ( "dingdan ():" + e.getMessage ()); )) public ResultSet executeQuery (String sql) (try (conn = DriverManager.getConnection (sConnStr); stmt = conn.createStatement (); rs = stmt.executeQuery (sql);) catch (SQLException ex) (System.err.println ( "aq1.executeQuery:" + ex.getMessage ());) return rs;) public void executeUpdate (String sql) (stmt = null; try (conn = DriverManager.getConnection (sConnStr); stmt = conn.createStatement () ; stmt.executeUpdate (sql);) catch (SQLException ex) (System.err.println ( "aq2.executeQuery:" + ex.getMessage ());)) public void closeStmt () (try (stmt.close ()
catch (SQLException e) (e.printStackTrace ();)) public void closeConn () (try (conn.close ();) catch (SQLException e) (e.printStackTrace ();)))
6, compile documents dingdan.java
In order to use dingdan.java, you must use a command line javac compiler of this. Java document.
Will be compiled dingdan.class documents copied to the previously created
C: \ Tomcat 5.0 \ webapps \ yyd \ WEB-INF \ classes \ dingdan under.
7, running
Will be dingdan.html, index1.jsp, add.jsp, ok_add.jsp four documents on c; \ Tomcat 5.0 \ wepapps \ ydd,
Start Tomcat, in the browser address bar type http://127.0.0.1:8080/ydd/dingdan.jsp.
↑ Back
Ajax simple examples
Abstract: simple examples of Ajax
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="219" height="86" align="center" valign="top"> </ td> <td width="465" valign="top">
Ajax, for Asynchronous JavaScript and XML is the use of client-side script and the Web server data exchange Web application development methods. In this way, interactive Web pages do not have to interrupt the process of re-plus CD, can be dynamically updated. Using Ajax, you can create closer to a desktop application, direct, high availability, and even richer, more dynamic Web user interface.
Ajax process
An interactive Ajax from a group called XMLHttpRequest JavaScript objects began. As the name suggests, it allows a client-side scripting to implement HTTP requests, and an XML format will be analytic server response. Ajax the first step in the process is to create a XMLHttpRequest examples. Use HTTP methods (GET or POST) to deal with the request, and will target URL to the XMLHttpRequest object.
Now, remember how Ajax in the first asynchronous processing state? When you send HTTP requests, you do not want to wait for the browser and server hung response Instead, the pages you wish to continue to respond to users through the interactive interface and the server response to the arrival of the real deal with them. To complete it, you can XMLHttpRequest register a callback function, and asynchronous request to distribute XMLHttpRequest. Control immediately be returned to the browser, when the server response arrived, the callback function will be called.
- In the Java Web server, at the request of any other HttpServletRequest and the same. Analytical parameters in the request, servlet implementation of the necessary application logic, will respond to the sequence of XML, and write it back to HttpServletResponse.
</ Td> </ tr> <tr> <td height="20" colspan="2">
</ Td> </ tr> </ table>
Examples
I wrote the following is a simple example:
First, ajaxServlet.java procedures list:
Package com; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse ; / * *———————————————- ——– * Filename: ajaxServlet.java * Create Date: 2005-10-25 * original author: miaohai * Copyright: miaohai * Function: Generating XML documents * * revised record: N / A *————————————————- —– * / public class ajaxServlet extends HttpServlet (private static final String CONTENT_TYPE = "text / xml; charset = gb2312" public void init () throws ServletException () public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException (response.setContentType (CONTENT_TYPE); response.getWriter PrintWriter out = (); String action = request.getParameter ( "action"); if (( "send"). equals (action)) (StringBuffer sb = new StringBuffer ( "
Sb.append ( "
Sb.append ( "
Sb.append ( "
Sb.append ( "
Out.write (sb.toString ()); out.close ();)))
<head>
</ Head>
<script Type="text/javascript">
/ * XMLHTTP through asynchronous transfer parameters to ajaxServlet sent back to the line with the conditions of XML documents * /
Function getResult () (var url = "/ Test / ajaxServlet? Send action =" if (window.XMLHttpRequest) (req = new XMLHttpRequest ();) else if (window.ActiveXObject) (req = new ActiveXObject ( "Microsoft. XMLHTTP ");) if (req) (req.open (" GET ", url, true); req.onreadystatechange = complete; req.send (null);)) / * return of the XML document * / function complete () (if (req.readyState == 4) (if (req.status == 200) (var type = req.responseXML.getElementsByTagName ( "type_name"); var str = new Array (); for (var i = 0; i <type.length; i + +) (str [i] [i] = type. firstChild.data; document.all [ 'td']. innerHTML + = str [i] + "
";))))
</ Script>
<body OnLoad="getResult()">
<table Width="80%" border="0" cellspacing="0" cellpadding="0">
<tr> <td Id="td"> </ td> </ tr>
</ Table>
</ Body>
Third, web.xml file
<? Xml version = "1.0" encoding = "ISO-8859-1">
Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
Version = "2.4">
4. Diagram:
</ Td> </ tr> <tr>
↑ Back
JSF examples of learning - Pisa (pizza) ordering system.
Abstract: JSF examples of learning - Pisa (pizza) ordering system.
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle">
JavaServer Face for the Java application development speed.
JavaServer Faces (JSF) is a Java technology used to quickly build Web applications of the new technology. JSF through the provision of the following features to speed up the development process:
Standards and scalable user interface components; vulnerable configuration pages navigation; certification for the importation of components; automation Bean management; incident; easily error handling,
And built-in support of the international.
This paper describes how to use JSF to build online Pisa (pizza) ordering system.
Job description
class=bodycopy> The application is called PizzaRia is an online store that allows users to choose pizza and submit selected pizza. PizzaRia similar with other online stores,
Users can browse the menu, add to the shopping cart and checkout selected products.
The application's user interface from five JSP document composition, they are index.jsp, details.jsp, shoppingCart.jsp, checkOut.jsp and order.jsp.
Each user interface pages, including three other pages: header.jsp, menu.jsp and footer.jsp
Users shopping process: the store to view the goods detailed information, shopping (Add to Cart), checkout, payment.
<table Width="100%" align=center> <tr> <td align=middle> </ td> </ tr> </ table><table Width="100%" align=center> <tr> <td align=middle> </ td> </ tr> </ table>
<table Width="100%" align=center> <tr> <td align=middle> </ td> </ tr> </ table>
<table Width="100%" align=center> <tr> <td align=middle> </ td> </ tr> </ table> <table width="100%" align=center> <tr> <td height = "453" align = middle> </ td> </ tr> </ table>
Database
The procedure of data stored in three forms: products (products), orders (orders) and OrderDetails (orders detailed project). Products Table information storage products, has four: ProductId (product logo), Name (name), Description (Note), and Price (prices).
class=bodycopy style1> Orders table for each row in a separate storage of orders, the information including contact names, addresses and credit card details of delivery. Orders Table 6 are:
OrderId (orders logo), ContactName (contact name), DeliveryAddress (postal address), CCName (credit card belonging name),
CCNumber (credit card numbers) and CCExpiryDate (credit card expiration date).
Each of the detailed project orders in the OrderDetails be stored in the table. OrderDetails table with four: OrderId (orders logo), ProductId (product logo),
Quantity (quantity) and Price (prices). Orders and OrderDetails through OrderID table included one-to-many relationship. Please note that the user table OrderDetails orders on the preservation of the relevant price information. The prices may be different with the current product prices, which stored in the table Products Price column.
In an Oracle database used to create the necessary tables script files stored in pizzaria-oracle.sql pizzaria.zip document.
Business Object
Following is the application used in the business object:
ProductBean package for a product information. It has the following attributes: id (logo), the name (name), description (Note), and price (prices).
Details.jsp each page visited, JSF Implementation (implementation) will automatically create a ProductBean examples. The JSF Implementation call ProductBean
No parameters of the structure, from the database access to the relevant data, and will fill its corresponding word column.
ProductSummary. ProductSummary (Product Overview) for a summary of that product. These include two attributes: id (identification) and the name (name).
ShoppingItemBean. ShoppingItemBean shopping for that item. These include four attributes: productId (product logo), productName
(Product name), the price (price), as well as quantity (number).
ShoppingCartBean. ShoppingCartBean used for storage in a dialogue (session) objects in the cart. Allows users to add such items (using addShopping methods), including all access to a list of items (using getShoppingItems method), and was purchased by the total value of goods (used getTotal methods).
OrderBean. OrderBean said that one orders. Such has the following five attributes: contactName, deliveryAddress, creditCardName,
CreditCardNumber and creditCardExpiryDate.
MenuBean. MenuBean getMenu method showed that the use of products for the directory. The method returns a product contains details of the link to the HTML table.
Package pizzaria;
Import java.util.ArrayList;
Import java.util.Iterator;
Import javax.faces.context.FacesContext;
Import javax.servlet.ServletContext;
(Public class MenuBean
String browsePage = "details.jsp";
Public String getBrowsePage () (
Return browsePage;
)
Public void setBrowsePage (String page) (
BrowsePage = page;
)
Public String getMenu () (
/ / Get DatabaseUtil instance
FacesContext facesContext = FacesContext.getCurrentInstance ();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext (). GetContext ();
DatabaseUtil dbUtil = (DatabaseUtil) servletContext.getAttribute ( "DATABASE_UTIL");
StringBuffer buffer = new StringBuffer (512);
Buffer.append ( "<table> \ n");
ArrayList summaries = dbUtil.getProductSummaries ();
= Summaries.iterator Iterator iterator ();
While (iterator.hasNext ()) (
ProductSummary summary = (ProductSummary) iterator.next ();
Buffer.append ( "<tr> <td>");
Buffer.append ( "" +
Summary.getName () + "");
Buffer.append ( "</ td> </ tr> \ n");
)
Buffer.append ( "</ table> \ n");
Return buffer.toString ();
)
)
DatabaseUtil. DatabaseUtil provided the following three kinds of methods to access and manipulate data:
- GetProductSummaries: The method returns a product contains a summary table in a list of all products. Overview of a product category to ProductSummary said.
- GetProductDetails: ProductBean the method returns an object, the object identifier package with a specific product details.
-
class=bodycopy> InsertOrder: The method to the Orders and OrderDetails Table Insert Table customer orders.
Application context sniffers
class=bodycopy style1> Application context sniffers (AppContextListener) read out from the web.xml file access the database for the initial parameters, and then be incorporated into
ServletContext object. The initial use parameters are as follows: jdbcDriver, dbUrl, dbUserName and dbPassword. In your web.xml file edit these values in order to reflect the true value of your database.
Package pizzaria; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class AppContextListener implements ServletContextListener (/ / web.xml file read Servlet context initialization parameters, construct a DatabaseUtil Object public void contextInitialized (ServletContextEvent event) (DatabaseUtil dbUtil = new DatabaseUtil (); ServletContext servletContext = event.getServletContext (); String jdbcDriver = servletContext.getInitParameter ( "jdbcDriver"); String dbUrl = servletContext.getInitParameter ( "dbUrl"); String dbUserName = servletContext.getInitParameter ( "dbUserName"); String dbPassword = servletContext.getInitParameter ( "dbPassword"); dbUtil.setJdbcDriver (jdbcDriver); dbUtil.setDbUrl (dbUrl); dbUtil.setDbUserName (dbUserName); dbUtil.setDbPassword (dbPassword ); servletContext.setAttribute ( "DATABASE_UTIL" dbUtil);) public void contextDestroyed (ServletContextEvent event) (ServletContext servletContext = event.getServletContext (); servletContext.removeAttribute ( "DATABASE_UTIL");))
JSF application configuration
class=bodycopy style1> JSF allows programmers only through the application process configuration files can be easily configured applications. If the document exists, then it should be named for the faces-config.xml, and should be in your application under the WEB-INF directory.
In the faces-config.xml file in the application's configuration in many aspects, including bean management, page navigation, custom UI (user interface) components,
Custom verification procedures and information resources. In PizzaRia application, I used the faces-config.xml bean management and navigation pages of the configuration.
<? Xml version = "1.0">
Faces-config PUBLIC
"- / / Sun Microsystems, Inc / / DTD JavaServer Faces Config 1.0 / / EN"
"Http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
Incident
In this application, developers need a AppAction Listener called the ActionListener. ProcessAction ActionEvent its way from the target getLocalValue acquire passed to the method of local values. If the local value of "Buy (purchase)," then processAction users with access to relevant ShoppingCartBean objects, and will shoppingItem to join in the bean. If the local value of "pay (payment)," then processAction from the session (session) objects and object access OrderBean ShoppingCartBean object, and call DatabaseUtil insertOrder object methods.
Package pizzaria; import java.util.Map; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.component.UICommand; import javax.faces.context . FacesContext; import javax.faces.el.ValueBinding; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.servlet.ServletContext; public class AppActionListener implements ActionListener (public void processAction (ActionEvent event) = (FacesContext facesContext FacesContext.getCurrentInstance (); String localValue = (String) ((UICommand) event.getComponent ()). getValue (); if (the "Buy." equals (localValue)) (String productId = (String) facesContext . getExternalContext (). getRequestParameterMap (). get ( "myForm: productId"); Map sessionMap = facesContext.getExternalContext (). getSessionMap (); ShoppingCartBean cart = (ShoppingCartBean) sessionMap.get ( "shoppingCartBean"); if (cart = = null) (cart = new ShoppingCartBean ();// create Cart sessionMap.put ( "shoppingCartBean" cart);) = getDatabaseUtil ProductBean product (). getProductDetails (productId); ShoppingItemBean shoppingItem = new ShoppingItemBean (product.getId (), product.getName (), product.getPrice (), 1); cart.addShoppingItem (shoppingItem);) else if ( "Pay." equals (localValue)) (/ / insert a record into the database OrderBean order = (OrderBean) getValueBinding ( "# (orderBean)"). getValue (facesContext); ShoppingCartBean cart = (ShoppingCartBean) getValueBinding ( "# (shoppingCartBean)"). getValue (facesContext); if (cart! = null & order! = null ) (getDatabaseUtil (). insertOrder (order, the cart); / / empty shopping cart cart.removeShoppingItems ();))) private ValueBinding getValueBinding (String valueRef) (ApplicationFactory factory = (ApplicationFactory) FactoryFinder.getFactory (FactoryFinder.APPLICATION_FACTORY); Application application = factory.getApplication (); return application.createValueBinding (valueRef);) private DatabaseUtil getDatabaseUtil () = (FacesContext facesContext FacesContext.getCurrentInstance (); ServletContext servletContext = (ServletContext) facesContext.getExternalContext (). getContext (); return (DatabaseUtil) servletContext.getAttribute ( "DATABASE_UTIL");))
AppActionListener of the use of two very useful approach: getValueBinding and getDatabaseUtil. GetValueBinding accept the designated target of a string, and returns an object of type down conversion ValueBinding type of object. For example, in order to obtain user in the application configuration file to be registered as shoppingCartBean ShoppingCartBean example, developers need to transfer through "shoppingCartBean" to call getValueBinding.
ShoppingCartBean cart = (ShoppingCartBean) getValueBinding ( "# (shoppingCartBean)"). GetValue (facesContext);
GetDatabaseUtil method returns an DatabaseUtil ServletContext of the examples cited:
Private DatabaseUtil getDatabaseUtil () = (FacesContext facesContext FacesContext.getCurrentInstance (); ServletContext servletContext = (ServletContext) facesContext.getExternalContext (). GetContext (); return (DatabaseUtil) servletContext.getAttribute ( "DATABASE_UTIL");) operational procedures: http: / / 127.0.0.1:8080 / pizza / faces / index.jsp
The original author PizzaRia JSF applications using JavaServer Faces [JSF] 1.0. In order to facilitate learning, the station will use its jsf1.1 + Access, and rewrite all jsp document. Please download the source code analysis.
</ Td> </ tr> <tr> ↑ Back
JSP entry examples: Chat refresh JSP
Abstract: JSP entry examples: Chat refresh JSP
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="431" height="86" align="center" valign="top">
XMLHttp history of the smallest non-refresh JSP chat rooms, basically there is no function, this procedure only for the study and the use of non-use of technology refresh. If used please contact me:
This procedure by: Qxin development
E-Mail: lqxttl@21cn.com
You test (26)
What will be written to the standard output when the following program is run? Class Base (int i; Base () (add (1);) void add (int v) (i + = v;) void print () (System . out.println (i);)) (class Extension extends Base Extension () (add (2);) void add (int v) (v * i + = 2;)) public class Qd073 (public static void main ( String args []) (bogo (new Extension ());) static void bogo (Base b) (b.add (8); b.print ();)) a) 9 b) 18 c) 20 d) 21 e) 22
Click for the answer </ td> <td width="253" valign="top"> </ td> </ tr> <tr> <td height="20" colspan="2">
</ Td> </ tr> </ table>
</ Td> </ tr> <tr>
↑ Back
How to start in Web Application examples explain the background tasks
Abstract: How to start in Web Application examples explain the background tasks
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle">
We often in Web applications need to write its own services, the purpose of this paper is to provide you with a solution.
<table Width="674" border="0"> <tr> <td width="396">
Principle
The principle of the programme is to write an interface to achieve the ServletContextListener category, there are two such methods:
Public void contextInitialized (ServletContextEvent sce)
It is activated when the call in the application; Another method is:
Public void contextDestroyed (ServletContextEvent sce)
The method is applied at the end of the call.
</ Td> <td width="268"> </ td> </ tr> </ table>
We have to start the application logic on the background contextInitialized method achieved; to release background applications work in the occupied contextDestroyed resources to deal with them. But we started background task is often required, such as time, frequency, and so on, here I use an open-source components: quartz.
Steps
1, writing business called categories:
This is the main function of quartz in the scheduling of the prescribed rules call implement the necessary business logic.
2, writing class scheduling
The purpose of this call is set up the rules, and here I use the "0 / 10 * * * *?" Said that every 10 seconds once.
3, prepared by the start of services:
Calling in contextInitialized TestShedule.run () start background task; contextDestroyed Calling TestShedule.stop () stop background tasks.
4, the deployment of such services launched
In web.xml file add the following line in the configuration:
5, web services can be launched.
Aggregate
In fact, the functions of the realization of this lot, I am here is the application interface and the ServletContextListener revenue api quartz, and hope that you can help the development. Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr>
↑ Back
Lucene index page for examples
Abstract: Lucene index page for examples
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="269" height="86" align="center" valign="top"> </ td> <td width="415" valign="top"> a key input word lucene.html
<body>
<form Name="form1" method="post" action="search.jsp">
Enter keyword: <input type = "text" name = "keyword">
<input Type="submit" name="Submit" value="æäº¤">
</ Form>
</ Body>
Drawings:
</ Td> </ tr> <tr> <td height="20" colspan="2">
Second, the search and displays the results search.jsp <% @ page contentType = "text / html; gb2312 charset ="%>
<% @ Page import = "java.util .*"%>
<% @ Page import = "java.text.SimpleDateFormat"%>
<% @ Page import = "org.apache.lucene.analysis.standard.StandardAnalyzer"%>
<% @ Page import = "org.apache.lucene.index.IndexReader"%>
<% @ Page import = "org.apache.lucene.document.Document"%>
<% @ Page import = "org.apache.lucene.search.IndexSearcher"%>
<% @ Page import = "org.apache.lucene.search.Hits"%>
<% @ Page import = "org.apache.lucene.search.Query"%>
<% @ Page import = "page.Pagination"%> <% @ page import = "org.apache.lucene.queryParser.QueryParser"%>
<% @ Page import = "org.apache.lucene.analysis.Analyzer"%>
<%
String queryString = request.getParameter ( "keyword"); if (queryString == null | | queryString.length () == 0) (out.println ( "Search keywords can not be empty");) else (= new queryString String (queryString.getBytes ( "ISO8859_1")); String indexPath = getServletContext (). getRealPath ("/")+" index "; boolean error = false; Document doc; IndexSearcher searcher = null; Query query = null; Hits hits = null; try (searcher = new IndexSearcher (IndexReader.open (indexPath));) catch (Exception e) (out.print ( "did not find index files!"); out.print (e.getMessage ()); error = true;) if (error == false) (Analyzer analyzer = new StandardAnalyzer (); query try (= QueryParser.parse (queryString, "Article_name" analyzer);) catch (Exception e) (out.print (e. getMessage ()); error = true;)) if (error == false & searcher! = null) (hits = searcher.search (query) if (hits.length () == 0) (out.print ( " Sorry! did not find the resources you need. "); error = true;)) if (error == false & searcher! = null) (out.print (" Search keywords: "+ + queryString" "); / / Pagination is the downloading, and we need to pass along a vector, you can change, and this is not done two times Vector list = new Vector (); for (int i = 0; i <hits.length (); i + +) (doc = hits.doc (i); list.add (doc);) out.print ( "find resources"); Pagination pagination = null; String pageNumber = request.getParameter ( "pageNumber"); int showItemNumber = 10; if (pageNumber == null) (pageNumber = "1";) String HTML = ""; if (list! = null & list.size ()> 0) (pagination = new Pagination (); pagination.setPageNumber (Integer.parseInt (pageNumber)); pagination.setShowItemNumber (showItemNumber); pagination.setVisitPageURL ( "search.jsp? keyword =" + queryString); list = (Vector) pagination.interceptListByStarItemNumber (list) for (int i = 0; i <list . size (); i + +) (doc = (Document) list.get (i); String A_id = doc.get ( "Article_id"); String doctitle = doc.get ( "Article_name"); String url = doc.get ( "File_name ")+"? id =" + A_id; out.print ( "<a href = 'http://127.0.0.1:8080/cwbwebhome/" + url +"'>( ★) "+ + doctitle" " );) = pagination.buildHTML HTML ( "600"); out.print (HTML);)))
Figure effect:
Thirdly, a paging class Pagination.java (download)
</ Td> </ tr> </ table> </ td> </ tr> <tr>
↑ Back
CachedRowSet and use examples JdbcRowSet
Abstract: JdbcRowSet and CachedRowSet example
</ Td> </ tr> <tr> <td width="528" height="35" valign="top" class="ArticleTeitle">
/ / Access database import java.sql .*; import javax.sql.rowset .*; import com.sun.rowset .*; public class JDBCRowSetExample (public static void main (String argv []) (String url = "jdbc: odbc: zz3zcwb "String login =" "; String password =" "; try (Class.forName (" sun.jdbc.odbc.JdbcOdbcDriver "). newInstance (); JdbcRowSet rowSet = new JdbcRowSetImpl () / / set url , login and password; rowSet.setUrl (url); rowSet.setUsername (login); rowSet.setPassword (password); rowSet.setCommand ( "select * from Article"); rowSet.execute (); while (rowSet.next ( )) (String id = rowSet.getString ( "Article_id"); String name = rowSet.getString ( "Article_name"); System.out.println ( "id =" + id + "name =" + name);) rowSet. close ();) catch (Exception e) (e.printStackTrace ();)))
/ / Mysql database import java.sql .*; import javax.sql.rowset .*; import com.sun.rowset .*; public class JDBCCachedRowSetExample (public static void main (String argv []) (String url = "jdbc: mysql: / / 127.0.0.1:3306 / soft? user = root & password = "; String login =" "; String password =" "; try (Class.forName (" com.mysql.jdbc.Driver "). newInstance () ; CachedRowSet crs = new CachedRowSetImpl () / / set url, login and password; crs.setUrl (url); crs.setUsername (login); crs.setPassword (password); crs.setCommand ( "select * from soft") ; crs.setPageSize (5); crs.execute (); while (crs.nextPage ()) (System.out.println ("——————– –"); while (crs.next ()) (System.out.println (crs.getInt ( "soft_id") + "\ t \ t" + crs.getString ( "soft_name"));)) crs. close ();) catch (Exception e) (e.printStackTrace ();)))
Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> <td width="173" valign="top" class="ArticleTeitle">
</ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">
↑ Back
Jsf study examples
Abstract: The study examples jsf
</ Td> </ tr> <tr> <td width="481" height="35" valign="top" class="ArticleTeitle">
This is "Mastering JavaServerFaces" on the Chinese version of the example, the invoice data search, sort, the list shows that modification, and display components (hide), and other functions, with all source files and libraries, not for this book lovers learning. Below are some of title runs:
I. Home
Second, the search page
3, display, delete, sort page
Fourth, we will amend data pages
5, modify confirmation page
Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> <td width="203" align="center" valign="top" class="ArticleTeitle">
</ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">
↑ Back
JSF examples of learning - CD stores
Abstract: JSF examples of learning - CD stores
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle">
This is what I downloaded from the Internet example, the addition of cd record, edit, delete, update operations. Compiled about.
First, the use of Tiles for JSF layout
Look at the web.xml file (download all the source files):
Definitions-config
/ WEB-INF/tiles-defs.xml - Parser-validate definitions
True
Here uses struts in the Tiles for the layout and operation of the cases when the need to download struts1.1 and struts.jar commons-beanutils.jar commons-collections.jar and common-digester.jar put this application WEB-INF / lib directory. Tiles in the configuration file specified above: WEB-INF/tiles-defs.xml.
Tiles used in the JSF, probably we should pay attention to three points:
1, the use of the JSF pages
Index.jsp
<% @ Page contentType = "text / html; GBK charset ="%>
<% @ Taglib prefix = "t" uri = "http://jakarta.apache.org/struts/tags-tiles"%>
2, conducted in WEB-INF/tiles-defs.xml tiles definition, as in the above:. "Index"
- Defs.xml titles in the definition of all tiles are as follows:
<? Xml version = "1.0" encoding = "ISO-8859-1">
Tiles-definitions PUBLIC
"- / / Apache Software Foundation / / DTD Tiles Configuration 1.1 / / EN"
"Http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
These tiles in the JSF pages as long as the definition of the use of markers
3, in WEB-INF/tiles-defs.xml layout of the main elements of the definition from the designated path attribute. Path = "/ WEB-INF/layout/layout.jsp"
Layout.jsp definition page layouts, page heading into his head, left, content, and the right foot.
<table Width="503" border="1" align="center" cellpadding="0" cellspacing="0"> <tr> <td colspan="3"> head header </ td> </ tr> <tr> <td width="182"> left navigation area navigation. </ td> <td width="146"> content of the middle district center </ td> <td width="175"> right Information Area news </ td> </ tr> <tr> <td colspan="3"> foot area footer </ td> </ tr> </ table> layout.jsp as follows:
<? Xml version = "1.0" encoding = "iso-8859-1">
Html PUBLIC "- / / W3C / / DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<% @ Taglib prefix = "t" uri = "http://jakarta.apache.org/struts/tags-tiles"%>
<% @ Taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%>
<head>
<link> Rel = "stylesheet" type = "text / css" href = "
</ Head>
<body>
</ Body>
T: insert labels to include dynamic content.
All pages 1 2 3 4 5 6 7
</ Td> </ tr> <tr>
↑ Back
JSF examples of learning - JCatalog
Abstract: JSF examples of learning - JCatalog
</ Td> </ tr> <tr> <td width="410" height="35" valign="top" class="ArticleTeitle"> use JSF, and Hibernate SpringFramework Construction on Web Application examples
[Original author] Derek Yang Shen
[Original link] http://www.javaworld.com/javaworld/jw-07-2004/jw-0719-jsf.html
[Source link] http://www.javaworld.com/javaworld/jw-07-2004/jsf/jw-0719-jsf.zip
[Comments] is a text on the JSF and Spring integration of the article is a good example, is more suitable in the Spring and we have a certain understanding of the human learning. Which a lot of space on the JSF, JSF interested can come to see.
Test you (32)
Class C1 (
C1 () (
System.out.print ( "1");)
)
(Class C2 extends C1
C2 () (
System.out.print ( "2");)
)
Public class C3 extends C2 (
C3 () (
System.out.println ( "3");
)
Public static void main (String [] args) (
C3 c = new C3 ();)
)
What will be written to the standard output?
Click for the answer
</ Td> <td width="274" valign="top" class="ArticleTeitle">
</ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">
↑ Back