Tomcat has to say two or three things [Nicktai Posted on 2005-3-16 15:32:09]
Reprinted http://blog.9cbs.net/darkxie/archive/2004/10/25/tomcatapp.aspx I would like to give all people who are using Tomcat or intend to use this article, pay tribute to all developers of Tomcat! First, the kitten Tomcat is actually very cute in 2003, I changed the company, and I also changed WebApp, Tomcat appeared in front of me (used before using WebLogic), I am a bit awkward, free, free? Worrying ing ... (in fact, in Mars staying out, there is a hit, originally this cat coming from famous door-Jakarta project, 2001 most innovative Java Product), and Java's Big Sun's SUN (Officially recommended servlet and JSP containers), will rely on it to eat. Don't say two words, get up: 1, install Tomcat latest version is 5.0.29 (http://jakarta.cgi) If you can automatically find your JDK or set java_home if you are in Windows C: / JDK needs to decompress first under Linux, then set java_homeexport java_home = / usr / local / jdk2, then you can run Tomcat servers after running, enter Tomcat's bin directory, starting with Startup with startup, Linux Startup.sh, the corresponding Tomcat command is shutdown and shutdown.sh. After starting the service, enter http: // localhost: 8080 in the browser to test 3. Directory structure bin: Store startup and close Tomcat script. Conf: contains different profiles, Server.xml (Tomcat's primary profile). WORK: Store the Class file generated after the JSP compiled. WebApp: Store application examples, after you have to deploy the application, you have to put it in this directory. Logs: Store log file comm./server/shared: The LIB folder under these three folders will put JAR files. 1. Configuring the server.xml file There is nothing to say, see Tomcat's documentation is more useful, here there are some main things.
Element Name Properties Interpretation ServerPort Specifies a port, this port is responsible for monitoring the request Shutdown specifying Shutdown Specifying the command string service to port serviceName Specifying the name of the service in the client and services port specifying the server side to create The port number, and in this fracture, the process requested by the process request from the client's request minprocessors server startup MAXPROCESSORS MaxProcessors can create the number of process requests Enablelookups If true, you can perform DNS query by calling request.getRemotehost () To get the actual host name of the remote client, if the DNS query is not performed for False, but returns its IP address redirectport specifies that the server is processing the HTTP request to receive a SSL transmission request and the port number ACCEPTCOUNT specified when all can be used. When the number of processes requested is used, it can be placed on the number of requests in the process queue. If the request exceeds this number will not process the timeout (in milliseconds) of the connectionTimeout (in milliseconds), which is specified in milliseconds. Processor, Receive, and Processing Requests from Connector) DefaultHost Specifies the host name of the default processing request, which at least one of the name attribute values of one of the host elements is the same content (represents a web application, usually a WAR file, Regarding the specific information of WAR, see the servlet specification. The path of the DOCBASE application or the path stored by the WAR file Path indicates the prefix of the URL of this web application, so the requested URL is http: // localhost: 8080 / path / *** * Reloadable This property is very important. If true, Tomcat automatically detects changes in the application's / web-inf / lib and / web-inf / class directory, automatically loads new applications, we can do not count Tomcat In the case where the application host (represents a virtual host) name specifies the basic directory of the hostname AppBase application, that is, the directory where the application is placed. If True is true, Tomcat will automatically decompress the WAR file, otherwise it is not extracted, directly from War Run the application logger in the file (indicating log, debugging, and error message) classname specifies the class name used by the Logger, and this class must implement org.apache.catalina.logger interface prefix specifies log files Prefix Suffix Specifies the suffix timestamp of the log file If True, the log file name is to join the time, as in the following example: localhost_log.2001-10-04.txTrealm (indicating that the user name, password, and ROLE database) classname Specifies Realm Class names, such must implement org.apache.catalina.Realm interface Valve (functionality is similar to Logger, its prefix and suffix attribute interpretation, etc.) ClassName specifies the class name used by Valve, such as Org.Apache.catalina .valves.accessLogvalve class You can record the application's access information Directory specifies that the location of the log file is stored in Pattern, and the common host name or IP address, user name, date, first line requested string, HTTP response Code, the number of bytes sent. Combined approaches more than the value recorded by the common mode, managing Tomcat management capabilities, enters http: // localhost: 8080 /, you will slowly take yourself.
Practice real knowledge, I like this: ^ _ ^, everything is in master http: // localhost: 8080 / manager / html. First, letting the database connection pool into a J2EE programmer, everyone may have a ready-made JDBC database connection pool, in fact, this is not necessary, because it is WebLogic ... Enterprise WebApp has its own connection pool, everyone Don't use it directly, it is also very good, no need to envy .NET's ADO (former MS never worrying data connection, ADO does use it very cool), if you want to implement a JDBC Connection Pool note is: 1. There is a simple function to get a Connection from the connection pool. 2. The Close function must put the Connection back to the database connection pool. 3. When there is no idle Connection in the database connection pool, the database connection pool must be able to automatically increase the number of Connection. 4. When the number of Connection in the database connection pool is very large in a particular time, only one of the small parts will be used for a long time, and you should automatically turn off excess Connection. 5. If possible, you should provide the debug information report that does not close NEW Connection. There are all kinds of connecting pool code on the Internet, 改 ~ ~ Here you introduce how to configure Tomcat connection pools, take SQLServer as an example: Step 1: Installing SQLServer JDBC Drive SQL Server JDBC driver is actually three JAR File, msbase.jar / mssqlser.jar / msutil.jar, copy these three files to your / tomcat_home / commit / lib directory.
Step 2: Modify the server.xml file specific code as follows:
! - Class Name for SQLServer2000 JDBC Driver ->
Private preparedStatement thepstmt = null; / **************************************************************************************************** Source object ************************************************************************** / publicdbmanager () {TRY {INITCTX = New InitialContext ); // init context, read config web.xmlif (InitctX == null) {throw new exception ("initial failed!");} ctx = (context) INITX.LOOKUP ("Java: Comp / ENV"); / / Find "JDBC / SQLSERVERDB" Object this configRuation in the server.xml of tomcatif (CTX! = null) {DS = (Datasource) CTX.lookup ("jdbc / sqlserverdb");} if (ds == null) {throw New Exception ("Look Up Datasource Failed!");}} Catch (Exception E) {log (e, "can't get the context!");}} / *********** *****************************************************************************************************************************TION ************************** / public synchronizedConnection getConnection () {/ jet connection and set to delay time timelong startTime = new java.util.date (). gettime (); connection conne = NULL; while {con = newconnection (); if (con! = null) {// log ("CREATE New Connection!"); Break;} try {log ("Connection timeout, reconnection Waiting " T IMEOUT "MS"); Wait (Timeout);} catch (interruptedException e) {log (e, "connection timeout!");} if ((NEW java.util.date (). gettime () - starttime)> = Timeout) {log ("Connection Timeout!"); Break;}} returnne ()} privateconnection newconnection ()}}}}} privation con = NULL; try {con = ds.getConnection (); if (con == null) {throw New Exception ("Create Connection Failed!");}}} Catch ("Create Connection Failed!"); System.out.Println (E.GetMessage ());} Return Con;} / ** ******************************************** RELEASE THE Connection * @
Pram conn connection * @Param stmt statement * @Param pstmt preparedStatement ************************************************************************************************************************************************************** public synchronizedvoid freeConnection (Connection conn, Statement stmt, PreparedStatement pstmt) {try {// close Statementif (stmt = null!) {stmt.close (); stmt = null; // log ( "Close Statement ...... ");} // close prepaaredStatementif (PSTMT! = null) {pstmt.close (); pstmt = null; // log (" close preparedstate ... ");}} catch (Exception E) {System .out.println (E.GetMessage ());} try {// close connectionif (conn! = null) {conn = null; // log ("Close Connection ..." );}} catch (SQLEXCEPTION E) {log (e, "release resource error!");}} / ********************************** ************ WRITE log file. * @Param s string **************************************** ******* / privatevoid log (string s) {if (verbose) {system.out.println (new java.util.date () ":" s); // logger.info (New Java }} / *********************************************** Write log file. * @Param EX Object ***************************************************************************************************************************************************** EX) {if (verbose) {//system.out.println (new java.util.date () ":" s); // logger.error (ex);}} / ******** ***************************** WRITE log file. * @Param e throwable * @Param msg string ****** ************************************** / Privatevoid log (throwable E, STRING MSG) {system.out.println (New java.util .Date () ":" msg); // logger.info (new java.util.date () ": msg, e);} ...} OK, you can now easily use the connection pool If you want one, remember to be released, the number of connecting pools is always limited. Second, the Chinese problem is very simple. Each country (or region) specifies the character encoding set for computer information exchange, such as the development of the United States, China's GB2312-80, Japan's JIS, etc., as the country / region The basis of information processing has an important role in unified coding.
The character coding set is divided into two categories: SBCS (single-byte character set), DBCS (Double-byte character set). Early software (especially operating system), in order to solve the computer processing of local character information, there have been various localized version (L10N), in order to distinguish, introduce LANG, CODEPAGE and other concepts. However, due to the overlap of each local character set code, information exchange is difficult to exchange; the localized version of the software is high. It is therefore necessary to extract the commonality in the localization work, and consistently processed, and special localization processing content is lowered to minimize. This is the so-called internationalization (I18N). Various language information is further specified as Locale information. The underlying character set of processed has become a Unicode that contains all glyphs. Most of the software core character processing of most international features is based on Unicode. When the software is run, determine the corresponding local character encoding setting based on the local locale / codepage setting, and processes the local characters. The mutual conversion of Unicode and local character sets is required during processing, or even Unicode is the mutual conversion of two different local character sets in the middle. This approach extends in a network environment, and character information at both ends of any network also needs to be converted to an acceptable content according to the setting of the character set. The Java language inside the Java language uses Unicode to represent the character, comply with Unicode V2.0. The Java program will be transformed from the URL connection to the URL connection to the URL connection, or the URL connection is written, whether it is from / the file system. Although this increases the complexity of programming, it is easy to confuse, but it is in line with international ideas. In theory, these characters conversions according to character set settings should not have too many problems. The fact is due to the different actual operating environment of the application, the complementary, perfect, and the irregularity of the system or application, and the problem that the system or application implemented, and the problem occurred in the time of transcoding. In fact, the method of solving Chinese character encoding problems in the Java program is often simple, but understands the reasons behind it, positioning problems, but also understands existing Chinese character encoding and coding conversion. I believe that there is a new string (Request.getParameter ("ISO-8859-1"). GBK ")," GBK "), this code is not a solution, this will increase The complexity of the program, write the database, submit form, URL in Chinese parameters, everywhere is Chinese problem! As a lazy person who has a shortest distance, it is certainly not willing to read NEW STRING ("ISO-8859-1", "GBK"), "GBK"), "GBK", " The problem of dealing with various character transitions, I walked into the mountains, turning over the mountain, finally found a perfect solution, only a simple configuration in Tomcat, introducing 2 files to easily get it.
Prerequisites, each page uses <% @ Page ContentType = "text / html; charset = GBK" Language = "Java" IMPORT = "java.sql. *" ErrorPage = ""%> Earth people know something. Step 1: Add the filter to find these 2 files in Tomcat RequestDumperfilter.java, setcharacterencodingfilter.java, they are located in D: /Tomcat5.0.27/webapps/jsp-examples/web-inf/classess/filters, add to your project Go to the file, compile them. Step 2: Configure Web.xml to join this section in Web.xml ...
Step 3: Modify server.xml modifications in two places server.xml
This 2 East East is called a coupling (Tomcat is hooked by this guy) 1. Using mod_jk_1.2.5_2.0.47.dll to integrate step 1 under Windows 1: Prepare material apache2.0.52http: //apache.te8 .com / dist / httpd / binaries / win32 / apache_2.0.52-win32-x86-no_ssl.msitomcat5.0.27 http: //apache.linuxforum.net/vist/jakarta/tomcat-5/v5.0.19/bin/jakarta- Tomcat-5.0.27.exejdk (This is not to say it, ^ _ ^) MOD_JK_1.2.5_2.0.47.dll (the key is this stuff, find me N long), it is said that it can be under below, finally My colleague found. http://apache.linuxForum.Net/dist/jakarta/tomcat-connectors/jk/binaries/win32/mod_jk_1.2.5_2.0.47.dll Install Apache / Tomcat / JDK. Step 2: Set the environment variable after installation My Computer / Properties / Advanced / Environment Variable / New System Variable Variable Name: Java_Home Variable: C: /JBuilderx/JDK1.4 (pointing to the actual installation path of JDK); Tomcat_hMOM Variable value : Tomcat5.0.27; LassPath Edit variable value plus ...;% java_home% / bin;% java_home% / lib;% tomcat_home% / bin;.; Test, access http: // localhost and http: // localhost : 8080, the default installation does not have any errors ^ _ ^ put the connector MOD_JK_1.2.5_2.0.47.dll Copy to D: / Apache2 / Modules / under. Step 3: Apache is configured to find httpd.conf under D: / Apache2 / Conf, find DirectoryIndex, add index.jsp after index.html; look for "listen" for this machine test: Listen 127.0.0.1:80, I This is the Listen *: 80 lookup addDefaultcharset set to AddDefaultCharset off, so Apache will resolve the page with the character set you defined by your page.
At the end, add the following code:
Test it, visit http: // localhost and http: // localhost: 8080, see the same page? Careful point, in fact, it is very simple, look at the help of E text, it can't be problematic. 2, using mod_jk2.so (also called JK2) integration JK2 is a Jakarta-Tomcat-Connectors-jk2.0.4-win32-apache2.0.49.zip file, mainly used by MOD_JK2.SO. In fact, using mod_jk2.so integration and use mod_jk_1.2.5_2.0.47.dll integration, just changed a connection, now step by step ~ Step 1: Do not say, install Tomcat and Apache download Jakarta-Tomcat -connectors-jk2.0.4-win32-apache2.0.49.zip, decompress, put the mod_jk2 in the module folder under the Apache installation folder. Step 2: Apache Configuration Add a Work.properties file in / confation, its contents are as follows: [shm] file = d: //apache2/logs/shm.filesize=1048576.com This Socket Channel is a must, Port and Host correspond to the setting of the Tomcat. -> # The socket channel: localhost: 8009] Port = 8009Host = localhost # Define the workerhost: 8009] channel: localhost: 8009 # Uri mapping [URI: / *] #, just like the first way ^ _ ^ [URI: / *. JSP] [URI: / *. do] worker = ajp13: localhost: 8009 in httpd.conf In LoadModule, add this sentence: loadModule JK2_Module Modules / Mod_jk2.so At the end, JKSET config.file "conf / work.properties" This is to tell Apache where to find JK configuration, according to the specific situation. Also modify DirectoryIndex, DirectoryIndex index.html index.html.var index.jsp Find "Listen" for this machine: Listen 127.0.0.1:80, mine is the Listen *: 80 of this setting.