Now developing Java Web applications and establishing and deploying Web content is a very simple task. People who use Jakarta Tomcat as Servlets and JSP containers have been around the world. Tomcat has many features such as free and cross-platform, and is updated very quickly and is very popular now.
1. Configuration System Management (Admin Web Application)
Most commercial J2EE servers provide a powerful management interface, and most of them use easy-to-understand web application interfaces. Tomcat also provides a mature management tool in its own way, and is no less than those commercial competitors. Tomcat's Admin Web Application was originally launched in version 4.1, and its functions at that time included management context, data source, user, and group. Of course, it can also manage various database management such as initialization parameters, user, group, role, etc. In subsequent versions, these features will be greatly expanded, but existing features are already very practical. Admin Web Application is defined in the automatic deployment file: CATALINA_BASE/webapps/ . (Translator's note: CATALINA_BASE is the server directory under the tomcat installation directory) You must edit this file to determine that the docBase parameter in the Context is the absolute path. That is, the path of CATALINA_BASE/webapps/ is an absolute path. As an alternative, you can also delete this automatic deployment file and create an Admin Web Application context in the file, the effect is the same. You can't manage the Admin Web Application application. In other words, you may not be able to do anything except delete CATALINA_BASE/webapps/ . If you use UserDatabaseRealm (default), you will need to add a user and a role to the CATALINA_BASE/conf/ file. You edit this file and add a role called "admin" to the file, as follows:
<role name="admin"/>
There is also a user, and the role of this user is "admin". Add a user like an existing user (change the password to make it more secure):
<ser name="admin"password="deep_dark_secret"roles="admin"/>
After you complete these steps, restart Tomcat, visit http://localhost:8080/admin, and you will see a login interface. Admin Web Application adopts a container-based security mechanism and adopts the Jakarta Struts framework. Once you log in to the admin interface as a user of the "admin" role, you will be able to configure Tomcat using this admin interface.
2. Configuring Application Management (Manager Web Application)
Manager Web Application allows you to perform some simple web application tasks through a simpler user interface than Admin Web Application. Manager Web Application is defined in an automatic deployment file:
CATALINA_BASE/webapps/
Also, there is a user with the role of "manager". Add a new user like an existing user (change the password to make it more secure):
<user name="manager"password="deep_dark_secret"roles="manager"/>
Then restart Tomcat, visit http://localhost/manager/list, and you will see a simple text-based management interface, or visit http://localhost/manager/html/list, and you will see an HMTL management interface. Either way, it means your Manager Web Application is now launched. Manager application allows you to install new web applications for testing without system management privileges. If we have a new web application located under /home/user/hello and want to install it under /hello, in order to test this application, we can do this, enter "/hello" in the first file box (as the path when accessed) and "file:/home/user/hello" in the second text box (as the Config URL). Manager application also allows you to stop, restart, remove, and redeploy a web application. Stop an application so that it is inaccessible. When a user tries to access the stopped application, he will see a 503 error?? "503 - This application is not currently available". Removing a web application simply means deleting the app from the running copy of Tomcat. If you restart Tomcat, the deleted app will appear again (that is, removal does not mean deleting it from the hard disk).
3. Deploy a web application
There are two ways to deploy web services in the system.
- Copy your WAR file or your web application folder (including all contents of the web) to the $CATALINA_BASE/webapps directory.
- Create an XML fragment file for your web service that only contains context content and place the file in the $CATALINA_BASE/webapps directory. The web application itself can be stored anywhere on the hard drive.
If you have a WAR file, if you want to deploy it, you just need to simply copy the file to the CATALINA_BASE/webapps directory. The file must be ".war" as the extension. Once Tomcat listens to this file, it unpacks the file package as a subdirectory and uses the file name of the WAR file as the subdirectory name. Next, Tomcat will create a context in memory, as if you created it in a file. Of course, other necessary content will be obtained from the DefaultContext in it. Another way to deploy a web application is to write a Context XML fragment file and copy the file to the CATALINA_BASE/webapps directory. A Context fragment is not a complete XML file, but a context element and a corresponding description of the application. This kind of fragment file is like a context element cut out from it, so this fragment is named "context fragment". For example, if we want to deploy an application named, which uses realm as the access control method, we can use the following snippet:
<!--Context fragment for deploying --> <Context path="/demo"docBase="webapps/"debug="0" rivileged="true"> <Realm className=""resourceName="UserDatabase"/> </Context>
Name the fragment "", and copy it to the CATALINA_BASE/webapps directory. This context snippet provides a convenient way to deploy web applications, you do not need to edit unless you want to change the default deployment features and do not need to restart Tomcat when installing a new web application.
4. Configure Virtual Hosts
Regarding the "Host" element, it only needs to be modified if you set up a virtual host. A virtual host is a mechanism for serving multiple domain names on a web server. For each domain name, it seems that the entire host is exclusive. In fact, most small business websites are implemented using virtual hosts, mainly because virtual hosts can directly connect to the Internet and provide corresponding bandwidth to ensure reasonable access response speed. In addition, virtual hosts can also provide a stable fixed IP. A name-based virtual host can be established on any web server. The method of setting up is to establish an alias for the IP address on the domain name server (DNS) and tell the web server to distribute requests to different domain names to the corresponding web page directory. Because this article mainly talks about Tomcat, we are not going to introduce how to set up DNS on various operating systems. If you need help in this regard, please refer to the book "DNS and Bind", authored by Paul Albitz and Cricket Liu (O'Reilly). For demonstration convenience, I will use a static host file, as this is the easiest way to test alias. Tomcat use virtual hosts, you need to set up DNS or host data. For testing, setting an IP alias for the local IP is enough. Next, you need to add a few lines to it, as follows:
<Server port="8005" shutdown="SHUTDOWN" debug="0"> <Service name="Tomcat-Standalone"> <Connector className= "." port="8080" minProcessors="5" maxProcessors="75" enableLookups="true" redirectPort="8443"/> <Connector className= "." port="8443" minProcessors="5" maxProcessors="75" acceptCount="10" debug="0" scheme="https" secure="true"/> <Factory className=". " clientAuth="false" protocol="TLS" /> </Connector> <Engine name="Standalone" defaultHost="localhost" debug="0"> <!-- This Host is the default Host --> <Host name="localhost" debug="0" appBase="webapps" unpackWARs="true" autoDeploy="true"> <Context path="" docBase="ROOT" debug="0"/> <Context path="/orders" docBase="/home/ian/orders" debug="0" reloadable="true" crossContext="true"> </Context> </Host> <!-- This Host is the first "Virtual Host": / --> <Host name="" appBase="/home/example/webapp"> <Context path="" docBase="."/> </Host> </Engine> </Service> </Server>
Tomcat's file, in its initial state, only includes one virtual host, but it is easily expanded to support multiple virtual hosts. In the previous example, a simple version is shown in which the bold part is used to add a virtual host. Each Host element must include one or more context elements, and one of the context elements contained must be the default context. The display path of this default context should be empty (for example, path=”).
5. Basic Authentication
The container management verification method controls how users are authenticated when they access protected web application resources. When a web application uses Basic Authentication (the BASIC parameter is set in the auto-method element in the file) and a user accesses a protected web application, Tomcat will pop up a dialog box through HTTP Basic Authentication, requiring the user to enter the user name and password. In this verification method, all passwords will be transmitted over the network in a 64-bit encoding.
Note: Using Basic Authentication is considered unsafe because it does not have a robust encryption method unless HTTPS is used on both the client and the server side or other password encryption methods (for example, in a virtual private network). Without additional encryption methods, network administrators will be able to intercept (or abuse) the user's password.
However, if you are just starting out with Tomcat, or if you want to test container-based security management in your web application, Basic Authentication is still very easy to set up and use. Just add two elements and , to your web application's file, and add the appropriate and , in the CATALINA_BASE/conf/ file, and restart Tomcat. The following example is excerpted from a club member website system where only the member directory is protected and authenticated using Basic Authentication. Please note that this method will effectively replace the .htaccess file in the Apache web server.
<!-- Define the Members-only area, by defining a "Security Constraint" on this Application, and mapping it to the subdirectory (URL) that we want to restrict. --> <security-constraint> <web-resource-collection> <web-resource-name> Entire Application </web-resource-name> <url-pattern>/members/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>member</role-name> </auth-constraint> </security-constraint> <!-- Define the Login Configuration for this Application --> <login-config> <auth-method>BASIC</auth-method> <realm-name>My Club Members-only Area</realm-name> </login-config>
6. Configure Single Sign-On
Once you set up realm and verification methods, you need to perform actual user login processing. Generally speaking, logging into the system is a very troublesome thing for users, and you must minimize the number of times the user logs in and verifys. By default, every web application will require the user to log in when the user requests a protected resource for the first time. If you run multiple web apps and each app needs separate user verification, it looks a bit like you are fighting your users. Users don’t know how to integrate multiple separate applications into a separate system, and they don’t know how many different applications they need to access, they are just confused why they always have to log in. Tomcat 4's "single sign-on" feature allows users to log in once when accessing all web applications under the same virtual host. To use this feature, you just need to add a SingleSignOn Valve element to the Host, as shown below:
<Valve className=""debug="0"/>
After the initial installation of Tomcat, the comments include SingleSignOn Valve configuration examples. You only need to remove the comments and you can use them. Then, as long as any user has logged in to an application, it will be equally valid for all applications under the same virtual host. There are some important limitations to using single sign-on valve:
- The value must be configured and nested in the same Host element, and all web applications that require single-point verification (must be defined by the context element) are located under that Host.
- The realm that includes sharing user information must be set in the same level of host or outside the nesting.
- Cannot be overwritten by realm in context.
- Web applications using single sign-on are best to use a Tomcat built-in verification method (defined in the ) which is stronger than a custom verification method. Tomcat's built-in verification methods include basic, digest, form and client-cert.
- If you use single sign-on and want to integrate a third-party web application into your website, and this new web application uses its own verification method instead of using container management security, you basically have no tricks. Your users need to log in once every time they log in to all original applications, and they also need to log in again when requesting a new third-party application.
- Of course, if you have the source code of this third-party web application and you are a programmer, you can modify it, but it may not be easy to do it.
- Single sign-on requires cookies.
7. Configure Customized User Directories
Some sites allow individual users to publish web pages on the server. For example, a college may want to give each student a public area, or an ISP wants to give some web space to his clients, but this is not a virtual host. In this case, a typical way is to add a special character (~) before the user's website, such as:
/~username /~username
Tomcat provides two ways to map these personal websites on the host, mainly using a pair of special Listener elements. The className property of Listener should be, and the userClass property should be one of several mapping classes. If your system is Unix, it will have a standard /etc/passwd file, and the account in this file can be read easily by running Tomcat, which specifies the user's home directory and uses the PasswdUserDatabase mapping class.
<Listener className= "" directoryName="public_html" userClass=". "/>
This way, the web file can be located in a directory like /home/ian/public_html or /home/jasonb/public_html. This form is more beneficial for Windows, you can use a directory like c:\home. If these Listener elements appear, they must be in the Host element, not in the context element, because they are all used to apply to the Host itself.
8. Using CGI scripts in Tomcat
Tomcat is mainly used as a Servlet/JSP container, but it also has the performance of many traditional web servers. Supporting Common Gateway Interface (CGI) is one of them. CGI provides a set of methods to run some extensions in response to browser requests. CGI is called universal because it can be called in most programs or scripts, including: Perl, Python, awk, Unix shell scripting, etc., and even Java. Of course, you probably won't run a Java application as CGI, after all, this is too primitive. Generally speaking, developing Servlets is always better than CGI because when a user clicks a link or a button, you don't need to start from the operating system layer. Tomcat includes an optional CGI Servlet that allows you to run legacy CGI scripts. In order for Tomcat to run CGI, you have to do the following:
- Rename (under the CATALINA_HOME/server/lib/ directory) to. The servlet that handles CGI should be located under the CLASSPATH of Tomcat.
- In Tomcat's CATALINA_BASE/conf/ file, remove the comments about the CGI section (by default, this section is located on line 241).
- Similarly, in Tomcat's CATALINA_BASE/conf/ file, the comment about the segment mapping the CGI is removed (by default, this segment is located on line 299). Note that this paragraph specifies how HTML links to CGI scripts are accessed.
- You can place the CGI scripts in the WEB-INF/cgi directory (note that WEB-INF is a safe place, you can place some files that you don't want to be seen by users or do not want to be exposed for security reasons), or you can place the CGI scripts in other directories under the context and adjust the cgiPathPrefix initialization parameters for the CGI Servlet. This specifies the actual location of the CGI Servlet and cannot be duplicated with the URL specified in the previous step.
- Restart Tomcat and your CGI will be ready to run.
In Tomcat, the CGI program is placed in the WEB-INF/cgi directory by default. As mentioned earlier, the WEB-INF directory is protected and cannot be seen through the client's browser, so this is a very good place for placing CGI scripts containing passwords or other sensitive information. To be compatible with other servers, although you can also save CGI scripts in the traditional /cgi-bin directory, it is important to know that files in these directories may be seen by curious surfers online. Also, in Unix, please make sure that the user running Tomcat has permission to execute CGI scripts.
9. Change the JSP Compiler in Tomcat (JSP Compiler)
In Tomcat 4.1 (or later, probably), JSP compilation is performed directly by the Ant program controller contained in Tomcat. This sounds a little weird, but that's exactly what Ant is intentional, with an API documentation guiding developers to use Ant without starting a new JVM. This is a big advantage of using Ant for Java development. In addition, this also means that you can now use any javac-supported compilation method in Ant, here is a list of javac pages about the Apache Ant user manual. It is easy to use because you only need to define a name in the element called "compiler" and there is a compiler name in the value that supports compilation, as shown below:
<servlet> <servlet-name>jsp</servlet-name> <servlet-class> </servlet-class> <init-param> <param-name>logVerbosityLevel </param-name> <param-value>WARNING</param-value> </init-param> <init-param> <param-name>compiler</param-name> <param-value>jikes</param-value> </init-param> <load-on-startup>3</load-on-startup> </servlet>
Of course, the compiler given must already be installed in your system and CLASSPATH may need to be set, which depends on what kind of compiler you choose.
10. Restricting Access to Specific Hosts
Sometimes, you may want to restrict access to Tomcat web applications, for example, you want only the host or IP address you specified to have access to your app. In this way, only those specified clients can access the content of the service. To achieve this effect, Tomcat provides two parameters for you to configure: RemoteHostValve and RemoteAddrValve. By configuring these two parameters, you can filter the host or IP address from the requested and allow or reject which hosts/IPs. Similarly, there is an allow/denied specification for each directory in Apache's httpd file. For example, you can set the Admin Web application to allow only local access, and the settings are as follows:
<Context path= "/path/to/secret_files" ...> <Valve className=". " allow="127.0.0.1" deny=""/> </Context>
If no specification is given for the allow host, the host matching the rejected host will be rejected, and all other than that are allowed. Similarly, if no specification for rejecting a host is given, the host matching the allow host will be allowed, and all other things are rejected.
The above is a detailed summary of the 10 essential tips for Tomcat configuration. For more information about Tomcat configuration tips, please pay attention to my other related articles!