Generate dynamic content with Tomcat and MySQL

xiaoxiao2021-03-06  23

Javid Jamae (Javidjamae@yahoo.com), Independent Software Consultant, Jamae Consulting Kulvir Singh Bhogal (Kbhogal@us.ibm.com), IBM WebSphere Service Consultant, IBM DoubleClick.net, DoubleClick.net, DoubleClick.net Providing banner advertising services have earned a lot of money. The services they provide are great, but why do you pay for what you can do? In this article, enterprise Java advisor Javid Jamae and Kulvir Bhogal will demonstrate how to create scrolling banner ads using a full open source environment: Apache Tomcat, MySQL, and MM MySQL JDBC drivers. First, they will gradually introduce you the required Tomcat and MySQL installation, and then demonstrate how to install the MM MySQL JDBC driver to allow Java Servlets running in Tomcat to communicate with MySQL. When the Internet starts from education and government information storage to an international business center, banner advertising has appeared. The scrolling banner is the assigned space on the web page. When loading or reloading the web page, use this space to display the ad - random display or display based on certain business logic. Drive scrolling banner ads is quite simple, but it is an important advertising tool. As they are similar, such as half-minute broadcasting and TV ads, these dynamic advertising tools allow a single web page to display different sources of advertisements and make different companies to establish their products and services for their products and services for different companies. Whether you look at the web banner ad (Yes, we all find that they are sometimes annoying), they have become a way of lifestyle on the Internet. A fact: The web of the web is composed of huge consumer groups, and their money makes e-commerce wheels to rotate. In short history of Internet marketing, e-commerce has exhibited money they wish to spend a banner advertisement at the hot site. Some companies (such as DoubleClick.NET) have been profited from the web banner phenomenon by using the application service provider (ASP), providing a service such as a click of a click for a specific banner ad. These ASPs then tell the advertisers to their Web advertising activities. Of course, ASPs like DoubleClick.net are charged. If you are like us, then you will not be willing to spend free of charge. Wait a little later - you may have already listened to the free lunch in the world. But don't worry. This article will cost only your time. In fact, we will demonstrate how to make an open source (ie free) environment to create your own powerful web banner tracking system. In order to complete this task, we selected "weapons" is Tomcat, MySQL, a Java Servlet and several assistant classes. Excited? So let us install software. Install Tomcat and MySQL In this section, we will gradually introduce Tomcat and MySQL installation. Then we will show you how to install the drivers that support these two applications to communicate with each other. Install Tomcat download and install Tomcat. For this article, we use Tomcat 4.1 Windows version, which has a good installation package and creates an icon and a Start menu folder for you. It also creates a "Windows Service" that is used to start and stop Tomcat servers.

The installation should be very simple, but if you have trouble, please check the Tomcat documentation. Because Tomcat is very popular, you can also find a lot of help on the newsgroup and the web, and some of the references are listed. After the Tomcat is installed, you have to complete a few steps to set our scrolling banner web application. First, we will create a subdirectory named Banner in the [InstallDir] / WebApps directory. Then in the Banner subdirectory, create a standard web application directory structure: [InstallDir] / WebApps / banner [installdir] / WebApps / banner / web-inf [installdir] / WebApps / banner / web-inf / class [installdir] / WebApps / Banner / Web-INF / LIB Next, we will add the context to our web application. Context is just an alias, which tells tomcat where you can access the web application. Our Context path will be / banner, which will point to the Banner subdirectories we have just created. After the user enters http: // localhost: 8080 / banner, turn to the top banner directory under WebApps. If he wants to run our bannerservlet (will exist in the web-inf / class directory), he can use http: // localhost: 8080 / banner / servlet / bannerservlet. To add / banner context, first, we need to edit the Server.xml file in the Tomcat conf directory. At the location close to the bottom of the file, you will see a few Context tags. There should have a Context for / admin, and a context for / examples. Add the following context tag: After adding the context tag Restart Tomcat to make changes to the server.xml file (in our example, we only restart the Tomcat installed Windows service). Install MySQL MySQL Because of its price (free), many companies use mysql to handle their data. Since many companies want to enter the Web market with a lower budget, the number of companies using MySQL is increasing every day. Open source community has opened your arms Welcome Mysql. Documents about this powerful database are very rich, and there are Linux and Windows versions. Download and install MySQL, install the "Typical" installation option (for this article, we assume you using MySQL's Winnt version). Once you have finished installation, you will notice an annoying aspect of MySQL: it doesn't place anything in the Start menu. You need to go to the database installation directory (default C: / MySQL /), then turn to the bin directory, where you will find an executable running MySQL.

First, double-click the winmysqladmin.exe file. When you open this file for the first time, you will ask you to enter your username and password. Next, right-click the red green light icon that appears in the taskbar. Go to Winnt and select "Start The Service" to run MySQL in the background. Finally, double-click the "mysql.exe" icon to launch "MySQL Monitor", you will use MySQL here. Make MySQL and Tomcat work together to make Mysql and Tomcat mutual communication may have some difficulties. However, by using the JDBC API, we will be able to communicate with the MySQL database relatively easy to use SQL from the Java class. We will use the MM MySQL JDBC driver (an open source driver) that makes communication between mysql and tomcat easily. (When writing this article, 2.0.14 is its latest version.) Unfortunately, installing this driver is slightly troublesome. First, download the appropriate JAR file for the driver from here. We downloaded files named mm.mysql-2.0.14-you-must-unjar-me.jar. Next, decompress the file (unjAR or unzip) to a temporary directory. Finally, copy the file containing the driver from the decompressed directory structure into the WebApps / Banner / web-INF / lib directory, and then restart Tomcat. In the driver version we downloaded, the name of the file is mm.mysql-2.0.14-bin.jar. We can use the JDBC / ODBC bridge driver to communicate with MySQL, but we believe that this driver has a greater advantage in performance (although we don't run any reference test programs to confirm our hypothesis). For this app, it may not have a big difference in performance, but we decided to demonstrate how to use the JDBC driver so you don't have to know it when you design a larger application. Scroll banner applications Since we have installed all the software, let's take a look at what this app can do and how we organize its architecture and develop it. In essence, you can use our banner servlet to perform two operations. First, you can use it to view the random banner image on the web page, and the random banner image will appear each time you load the web page containing the banner ad. Second, you can click on the banner image, which will allow you to go to the link corresponding to the image loaded. According to HTML, its code is similar to: If you want to load random Image, then obvious image tags cannot point to still image files, so we will indicate it to run the servlet, and the bannerservlet will be called in this case. We will use the HTTP GET method parameters to indicate that servlets provide us with images. Therefore, image tags are similar to: This tag calls servlet and passes into the parameter key value to type = image. The service () method of the servlet explains the request and then returns a random image to the browser.

Of course, servlet must remember which image sent to the client, so when the client clicks on the image, it knows where it should be linked. We will store metadata associated with the transmitted image on the client's session, so that when the user clicks the image, the metadata will be loaded from his session and re-directed to the appropriate URL. The link tag looks almost the same as the image tag: When the servlet is called with the Type = Link key value, the servlet grabs the metadata of the banner and re-routes the user to the appropriate URL. Code and ClassPath Settings To use the code supplied with this article, you must first decompress this zip file (in the reference), then compile this .java file with the command line Javac compiler or your favorite IDE. To compile this code, set the classpath to include these two JAR files. mm.mysql-2.0.14-bin.jar (or any other version obtained from the MM MySQL website) servlet.jar (if it doesn't have the JDK you use) to copy the .class file to previously created The [Tomcat_InstallDir] / WebApps / Banner / Web-INF / CLASS directory. The image files and .htm files provided as an example must be placed in the [Tomcat_InstallDir] / WebApps / banner directory. The database settings Our application's database sections are just metadata used to last for each banner in the system. In other words, we don't actually store image files in the database, but only store references to each image file. In our database, we will use seven columns to describe each banner ad. The description in Table 1 illustrates the contents of each record will be included. We will actually use only five of these seven database columns in the application. There is no Customername and NumberOfClickSpurchaseD in our version, but we place them as placeholders here for expansion. You can easily extend this app and use it for real business applications, where customers pay for each banner. Table 1. Database Field Field Name Description Example ImageFile The reference / IMAGES/Sitea.gif URL site user in the Banner Image After clicking on the banner, you should re-routing their target URL http://www.sitea.com customername Buy banner Customer Name John Doe NumberOfClickSpurchased User Purchased Clicked Clicks 140 NumberOfClickSremaining Customer Remaining Clickes 139 NumberOfimpressions Banners Has been displayed 23 BannerWeight The weight 10 of course 10. Of course, in a realistic environment, you will have more than one site Banner. According to your banner "Sponsored", you may want more or less to show his banner more or less. The BannerWeight field will be used to implement this feature.

We have achieved a very simple weighted system, each of which has a percentage probability of: (BannerWeight / Sum of all bannerweights) * 100 converts the content you have said to SQL, you can use mysql monitor input The following statement: MySQL> Create Database Banner; you can enter: mysql> use banner; next, we create a table: mysql> create table ads (imagefile varchar (50) Not null, url varchar (50) not NULL, CUSTOMERNAME VARCHAR (50), NUMBEROFCLICKSPURCHASED INT (4), NUMBEROFCLICKSREMAINING INT (4) NOT NULL, NUMBEROFIMPRESSIONS INT (4) NOT NULL, BANNERWEIGHT INT (4) NOT NULL); ADS table "describe" operation is similar to FIG. 1 Indicated. Figure 1. ADS table You need to use some sample values ​​to populate the database to determine if the built database is correct. The project's ZIP file includes some sample banners (GIF formats) that use them to understand the application of the application. Of course, for the web banner URL, you need to declare that you decide the location of the banner file. You can follow the SQL syntax below to "register" to the database: mysql> Insert Ints Values ​​('/sitea.gif','http://www.cnn.com', 'John Doe', 100, 100, 0, 10); Insert the records shown in Table 2 into the database using this syntax. Table 2. Database record imagefile sitea.gif siteb.gif sitec.gif sited.gif url http: // www.cn.com http://wwwww.ibm.com http: // www.yahoo.com CUSTOMERNAME John Doe Albert Einstein Jane Doe Madonna NUMBEROFCLICKSPURCHASED 100 20 30 20 NUMBEROFCLICKSREMAINING 100 20 30 20 NUMBEROFIMPRESSIONS 0 0 0 0 BANNERWEIGHT 10 10 30 10 Note: Web banner URL is on the local host, for testing purposes only. In the production environment, the URL will point to the actual location of the GIF file. This URL can actually be any location on the Internet. Since we have a database, you need to use the data just fill in. We will do this with Java servlet. The Java Servlet code will be described below, which will "promote" our efforts. You may wish to spend some time to communicate with BannerServlet.java code in the ZIP file. If you feel difficult, don't worry; we will spend some time to explain how the code works. Banner architecture This banner advertising servlet is very simple. We will use four classes: universal Logger class, a class that writes log messages to a text file. The servlet called bannerservlet, each displaying a banner image (ie, each load page) and each time you click the banner image, will call it. The servlet is the core of our application.

General DBHANDLER class, BannerServlet will use it to communicate with the MySQL database. Banner class, we use it to create objects, which contain all metadata owned by each banner in the database. The BannerServlet class and Banner class are specific to our application. They are quite simple, you can easily extend them to add more complex features. The benefits of DBHANDLER and Logger classes are: You can reuse these two classes in any of the applications you actually prepared, need to communicate with database communication or write log files. We will discuss all these four classes in more detail so you can understand how servlet works, and how it uses DBHANDLER to communicate with MySQL database. The Logger class Logger class is very simple. It has a single field that represents the File object we are writing to the log. You can pass references to a single Logger object to several classes, allowing these classes to write the same log file. The Logger class allows you to do the following. You can: Create a logger ("------" string) to the log file ("----" string) Add a log item to the default message to add a log item to the name and log message of the transfer. The default message to the end of the addition method Deletes the log file Returns the file object used by the logger object We will use the Logger object at the DBHANDLER class and BannerServlet. DbHandler class DBHandler is a very much class that can be used to interoperate with almost any database via JDBC. It requires a string with a JDBC / ODBC driver (we are using this driver to connect to the database) name, a string with a database (we set a DSN) name and a logger parameter. Logger parameters tell it where to print output messages when DbHandler complete its "magical" task. DBHandler's constructor opens to the database. After using the DBHANDLER to complete the task, you must use the Close () method to close it. After creating a DBHANDLER object, you must create a query to execute. Use the setQueryString () method to pass to the string containing the query, the query can be in the form of a PreparedStatement class. PreparedStatement is a good feature of JDBC. It allows you to define a query string that uses the question mark character to replace the variable standard in the query. You can then use the setter method of the PreparedStatement class to set the value of the unknown element in the query. Fortunately, the DBHandler class handles all these things. We only need to set the query you want to execute, then call a method of dbHandler, as shown below: Public banner getbannerbyname (String name) {... DBHANDLER.SETQUERYSTRING ("SELECT * from ADS where name =?" ResultSet RS = DBHANDLER.LOOKUP (); DBHANDLER.CLOSE (); ...} You can use the lookup () method to perform a SELECT query, use the executeUpdate () method to perform Update queries, and use INSERT The method is to perform an Insert query. There is also an Execute () method, it does not require parameters, you can execute any queries without pre previousatement parameters.

The Banner class Banner class is just a set of setter and getter methods that directly correspond to the values ​​of each column in the ADS database table. BannerServlet BannerServlet is the core of our application. We will divide this class into several different parts to explain to you. By browsing the code, you will be more familiar with how to connect to the database with a DBHANDLER class. Field BannerServlet uses five fields: string _databaseURL: To access the name of the database (JDBC: ODBC: // localhost / banner). String_drivername: The name of the driver used to communicate with the database. As described above, we will use the MM MySQL JDBC driver. The name of the driver is org.gjt.mm.mysql.driver. Logger _logger: Logger class name, use this class to log all events that occur in our application. Hashmap _banners: Hashmap for all Banner objects. The HashMap is populated with the servlet's init () method. Convert every line in the database table into a Banner object stored in the HashMap. We will explain this in a while. INT _TotalWeight: All Banner weights. This value is also set in the init () method; we will discuss this soon. Init () any servlet's init (servletConfig) method is called when the container is first loaded into the servlet. Here, the container is Tomcat. Tomcat is generated and passed into the servletconfig object, which contains the default configuration information of the container settings and developers (you) can set custom configuration information in the Servlet configuration file. For our use, there is no need to pass any configuration information, but you may need to extend the servlet and use this feature. The first thing we did after calling super.init () is to initialize the HashMap variable _banrs and set the _TotalWeight to 0. Then, connect to the database to get all the rows from the ADS table in the form of ResultSet. We use the for loop to loop the ResultSet, constructed a Banner object from each line, then put the index of the FOR cycle as a hash value, add the Banner object to the HashMap. (We can also easily use Vector or some other Collection classes to complete the same task.) Now, there is a HashMap containing all Banner. If you update the database, you can reload the uSHMAP simply call the init () method. We will be used in the IncreaseImpressions () and DecreaseClickSRemaining () methods. The service () service () method is defined in our BannerServlet class to handle any request, whether it is a get method or a Post method. There are two core parts for the implementation of the service () method. The first part processing the behavior of the servlet when sending the web page, and the second part processing the link request. Finally, let's take a look at the Type parameter sent from the client.

转载请注明原文地址:https://www.9cbs.com/read-77170.html

New Post(0)