Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang



Similar documents
Web Application Programmer's Guide

TypingMaster Intra. LDAP / Active Directory Installation. Technical White Paper (2009-9)

Web Application Architecture (based J2EE 1.4 Tutorial)

Web Container Components Servlet JSP Tag Libraries

Understanding Tomcat Security

Application Security

2. Follow the installation directions and install the server on ccc

Java Web Programming. Student Workbook

24x7 Scheduler Multi-platform Edition 5.2

Programming on the Web(CSC309F) Tutorial: Servlets && Tomcat TA:Wael Aboelsaadat

Web Applications. For live Java training, please see training courses at

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Server Setup and Configuration

PowerTier Web Development Tools 4

Securing a Web Service

Configuring BEA WebLogic Server for Web Authentication with SAS 9.2 Web Applications

IUCLID 5 Guidance and Support

Java Servlet and JSP Programming. Structure and Deployment China Jiliang University

How to Integrate IIS with JBoss / Tomcat Under Windows XP and Linux

SERVER SETUP AND CONFIGURATION

Java Servlet Tutorial. Java Servlet Tutorial

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

Virtual Open-Source Labs for Web Security Education

An introduction to web programming with Java

Implementing the Shop with EJB

Recommended readings. Lecture 11 - Securing Web. Applications. Security. Declarative Security

The Server.xml File. Containers APPENDIX A. The Server Container

a) Install the SDK into a directory of your choice (/opt/java/jdk1.5.0_11, /opt/java/jdk1.6.0_02, or YOUR_JAVA_HOME_DIR)

In this chapter, we lay the foundation for all our further discussions. We start

Mastering Tomcat Development

An Overview of Servlet & JSP Technology

Java and Web. WebWork

Creating Java EE Applications and Servlets with IntelliJ IDEA

Glassfish, JAVA EE, Servlets, JSP, EJB

Struts 2 - Practical examples

DTS Web Developers Guide

Controlling Web Application Behavior

For Introduction to Java Programming, 5E By Y. Daniel Liang

Web Applications. Originals of Slides and Source Code for Examples:

PicketLink Federation User Guide 1.0.0

DeskNow. Ventia Pty. Ltd. Advanced setup. Version : 3.2 Date : 4 January 2007

Install guide for Websphere 7.0

Tcat Server User s Guide. Version 6 R2 December 2009

Volume 1: Core Technologies Marty Hall Larry Brown. An Overview of Servlet & JSP Technology

STREAMEZZO RICH MEDIA SERVER

Workshop for WebLogic introduces new tools in support of Java EE 5.0 standards. The support for Java EE5 includes the following technologies:

Java Web Programming with Eclipse

ACM Crossroads Student Magazine The ACM's First Electronic Publication

Building Java Servlets with Oracle JDeveloper

Configuring Integrated Windows Authentication for JBoss with SAS 9.2 Web Applications

Instant Chime for IBM Sametime Installation Guide for Apache Tomcat and Microsoft SQL

J2EE-Application Server

Apache Roller, Acegi Security and Single Sign-on

Application Notes for Packaging and Deploying Avaya Communications Process Manager Sample SDK Web Application on a JBoss Application Server Issue 1.

Lucid Key Server v2 Installation Documentation.

Installation Guide for contineo

LiquidOffice v4 Architecture/Technologies

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

INTRODUCTION TO WEB TECHNOLOGY

NetBeans IDE Field Guide

Web-JISIS Reference Manual

Installing and Running Tomcat 5.5

CatDV Pro Workgroup Serve r

Oracle WebLogic Server

JasperServer Localization Guide Version 3.5

Java Servlet 3.0. Rajiv Mordani Spec Lead

TIBCO ActiveMatrix Service Grid WebApp Component Development. Software Release August 2012

Configuring Integrated Windows Authentication for Oracle WebLogic with SAS 9.2 Web Applications

Pure server-side Web Applications with Java, JSP. Application Servers: the Essential Tool of Server-Side Programming. Install and Check Tomcat

ServletExec TM 6.0 Installation Guide. for Microsoft Internet Information Server SunONE Web Server Sun Java System Web Server and Apache HTTP Server

Crawl Proxy Installation and Configuration Guide

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

Please send your comments to:

3. Installation and Configuration. 3.1 Java Development Kit (JDK)

EMC Smarts Service Assurance Manager Dashboard Version 8.0. Configuration Guide P/N REV A01

Project (Group) Management Installation Guide (Linux) Version 1.3. Copyright 2007 MGH

Keycloak SAML Client Adapter Reference Guide

1z0-102 Q&A. DEMO Version

CORISECIO. Quick Installation Guide Open XML Gateway

EMC Documentum Web Development Kit and Webtop

Configuring ActiveVOS Identity Service Using LDAP

EMC Clinical Archiving

In this chapter the concept of Servlets, not the entire Servlet specification, is

Principles and Techniques of DBMS 5 Servlet

Enterprise Knowledge Platform 5.6

Configuring the JBoss Application Server for Secure Sockets Layer and Client-Certificate Authentication on SAS 9.3 Enterprise BI Server Web

TIBCO ActiveMatrix BPM WebApp Component Development

Crystal Reports for Eclipse

Oracle EXAM - 1Z Oracle Weblogic Server 11g: System Administration I. Buy Full Product.

CS506 Web Design and Development Solved Online Quiz No. 01

Project Management (PM) Cell

Packaging and Deploying Java Projects in Forte

CONTROLLING WEB APPLICATION BEHAVIOR WITH

CS 209 Programming in Java #1

Web Application Developer s Guide

Transcription:

Supplement IV.E: Tutorial for Tomcat For Introduction to Java Programming By Y. Daniel Liang This supplement covers the following topics: Obtaining and Installing Tomcat Starting and Stopping Tomcat Choosing a Different Port Compiling Servlets Mapping a Servlet to a URL Running Servlets Running JSP Deploying Web Application Using WAR files Setting a Secured Web Server 0 Introduction Tomcat, developed by Apache (www.apache.org), is a standard reference implementation for Java servlets and JSP. It can be used standalone as a Web server or be plugged into a Web server like Apache, Netscape Enterprise Server, or Microsoft Internet Information Server. There are many versions of Tomcat. This tutorial uses Tomcat 5.5.9 as an example. The tutorial should also apply to all later versions of Tomcat. 1 Obtaining and Installing Tomcat You can download Tomcat from http://tomcat.apache.org/download-60.cgi. On this page, select zip under Core to download a zip file (i.e., apachetomcat-6.0.29.zip). You can use FilZip to extract it into c:\. FilZip is a free compression/decompression utility, which can be downloaded from http://www.filzip.com. 2 Starting and Stopping Tomcat Before running the servlet, you need to start the Tomcat servlet engine. To start Tomcat, you have to first set the JAVA_HOME environment variable to the JDK home directory using the following command. (Please note no space before or after the = sign in the following line.) set JAVA_HOME=c:\Program Files\java\jdk1.6.0_24 The JDK home directory is where your JDK is stored. On my computer, it is c:\program Files\jdk1.6.0_24. You may have a 8

different directory. You can now start Tomcat using the command startup from c:\jakarta-tomcat-5.5.9\bin as follows: c:\jakarta-tomcat-5.5.9\bin>startup NOTE: If you are using Tomcat 7.0.2, the default directory is c:\apache-tomcat-7.0.2. We use Tomcat 5.5.9 as example in this tutorial. NOTE: By default, Tomcat runs on part 8080. An error occurs if this port is currently being used. You can change the port number in c:\jakarta-tomcat-5.5.9\conf\server.xml, as discussed in the next section. NOTE: To terminate Tomcat, use the shutdown command from c:\jakarta-tomcat-5.5.9\bin. To prove that Tomcat is running, type the URL http://localhost:8080 from a Web browser, as shown in Figure 1. Figure 1 The default Tomcat page is displayed. 3 Choosing a Different Port (Optional) By default, Tomcat runs on part 8080. You can change it to a different port. To do so, open c:\jakarta-tomcat- 5.5.9\conf\server.xml using a text editor such as NotePad. Search for 8080 and change it to a desired port number such as 8100 in the following context. <Connector classname="org.apache.coyote.tomcat4.coyoteconnector" port="8080" minprocessors="5" maxprocessors="75" enablelookups="true" redirectport="8443" acceptcount="100" debug="0" connectiontimeout="20000" useurivalidationhack="false" disableuploadtimeout="true" /> 9

4 Creating a Servlet A servlet resembles an applet in some extent. Every Java applet is a subclass of the Applet class. You need to override appropriate methods in the Applet class to implement the applet. Every servlet is a subclass of the HttpServlet class. You need to override appropriate methods in the HttpServlet class to implement the servlet. Listed below is a simple servlet example that generates a response in HTML using the doget method. import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { /** Handle the HTTP <code>get</code> method. * @param request servlet request * @param response servlet response */ protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, java.io.ioexception { response.setcontenttype("text/html"); java.io.printwriter out = response.getwriter(); // output your page here out.println("<html>"); out.println("<head>"); out.println("<title>servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("hello, Java Servlets"); out.println("</body>"); out.println("</html>"); out.close(); } } 5 Compiling Servlets Suppose you have installed Tomcat 5.5.9 at c:\jakartatomcat-5.5.9. To compile FirstServlet.java, you need to add c:\jakarta-tomcat-5.5.9\common\lib\servlet-api.jar to the classpath from DOS prompt as follows: set classpath=%classpath%;c:\jakarta-tomcat-5.5.9\common\lib\servlet-api.jar servlet.jar contains the classes and interfaces to support servlets. Use the following command to compile the servlet: javac FirstServlet.java Copy the resultant.class file into c:\jakarta-tomcat- 5.5.9\webapps\liangweb\WEB-INF\classes so it can be found at runtime. TIP: You can compile FirstServlet directly into the target directory by using the d option in the javac command as follows: 10

javac FirstServlet.java d targetdirectory 6 Mapping a Servlet to a URL Before you can run a servlet in Tomcat 5.5.9, you have to first create the web.xml file with a servlet entry and a mapping entry. This file is located in C:\jakarta-tomcat- 5.5.9\webapps\liangweb\WEB-INF\web.xml. If the file already exists, insert a servlet entry and a mapping entry into web.xml for the servlet. The servlet entry declares an internal servlet name for a servlet class using the following syntax: <servlet> <servlet-name>internal Name</servlet-name> <servlet-class>servlet class name</servlet-class> </servlet> The map entry maps an internal servlet name with a URL using the following syntax: <servlet-mapping> <servlet-name>internal Name</servlet-name> <url-pattern>url</url-pattern> </servlet-mapping> For example, before running FirstServlet.class, you may insert the following lines to the web.xml file: <web-app> <servlet> <servlet-name>firstservlet</servlet-name> <servlet-class>firstservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>firstservlet</servlet-name> <url-pattern>/firstservlet</url-pattern> </servlet-mapping> </web-app> NOTE <Side Remark: download web.xml> For your convenience, I have created the web.xml that contains the decriptions for running all servlets in this chapter. You can download it from www.cs.armstrong.edu/liang/intro6e/supplement/we b.xml. TIP <side remark: Web development tools> 11

You can use an IDE such as NetBeans, Eclipse, and JBuilder to simplify development of Web applications. The tool can automatically create the directories and files. For more information, see the tutorials on NetBeans, Eclipse, and JBuilder on the Companion Website. 7 Running Servlets To run the servlet, start a Web browser and type http://localhost:8080/liangweb/firstservlet in the URL, as shown in Figure 2. Figure 2 You can request a servlet from a Web browser. NOTE: You can use the servlet from anywhere on the Internet if your Tomcat is running on a host machine on the Internet. Suppose the host name is liang.armstrong.edu; use the URL http:// liang.armstrong.edu:8080/liangweb/firstservlet to test the servlet. NOTE: If you have modified the servlet, you need to shut down and restart Tomcat. 8 Running JSP To run a JSP (e.g., Factorial.jsp), store it in webapps/liangweb, start a Web browser and type http://localhost:8080/liangweb/factorial.jsp in the URL, as shown in Figure 3. 12

Figure 3 You can request a JSP from a Web browser. 9 Deploying Web Application Using WAR Files Servlets, JSPs and their supporting files are placed in the appropriate subdirectories under the webapps directory in Tomcat. For convenience, you can create all the files under the webapps directory into one compressed file. This file is known as the WAR (Web Application Archive) and ends with the.war file extension. You can deploy a Web application by placing a WAR file in the webapps directory. When a Web server begins execution, it extracts the WAR file s contents into the appropriate webapps subdirectories. 9.1 Creating WAR Files You can create a WAR file using a tool or the jar command. If you use NetBeans, JBuilder, or Eclipse, a WAR file is automatically created every time you build the Web project. (e.g., you can find this file under the dist node in a Web project). To create a WAR file for the examples in Tmocat, change the directory to c:\jakarta-tomcat- 5.5.9\webapps\liangweb, and type the following command: jar cvf liangweb.war. A WAR file named liangweb.war is now created for all files and directories under \webapps\liangweb. The file is in \webapps\liangweb\liangweb.war. 9.2 Deploying WAR Files You can now deploy the WAR file to a new machine. Follow the steps below to test liangweb.war: 1. Place liangweb.war to \webapps\liangweb.war under your 13

Tomcat home directory. 2. Delete the entire directory of liangweb under webapps if it exists (this is necessary to enable new contents to be created). 3. Start Tomcat (if it is already running, you need to shut it down first.) Tomcat automatically extracts the contents in liangweb.war into the appropriate directories. You will see a new directory named liangweb created under the webapps directory. 4. Enter URL http://localhost:8080/liangweb/firstservlet to test the servlet. 10 Setting a Secured Server You can set the Tomcat server to activate basic HTTP authentication. You need to specify a security realm, which is a term that defines authorized users. There are three types of realms: Memory, Database, and JNDI. This section introduces how to set Memory and Database realms. 10.1 Setting a Secured Server Using Memory Realm To set a Memory realm, do the following: 1. Inside the <Engine>... </Engine> tag in conf/server.xml, insert the following line: <Realm classname="org.apache.catalina.realm.memoryrealm" /> TIP: The server.xml file already has this line commented. Simply uncomment it to set a Memory realm. 2. Edit conf/tomcat-users.xml to add user name, password, and the role for each user. For example, the following content defines two users with the role named test. <?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="test"/> <user username="john" password="cat" roles="test"/> <user username="scott" password="tiger" roles="test"/> </tomcat-users> NOTE: The user authentication information is defined in the file tomcat-users.xml. This information is loaded to an object stored in the memory upon Tomcat startup. That is why it is called the Memory realm. 3. Uncomment the following lines in conf/web.xml and modify the <role-name> field to test. This is the role used for the users in the Memory realm defined in Step 2. 14

... <security-constraint> <web-resource-collection> <web-resource-name> Protected Site </web-resource-name> <!-- This would protect the entire site --> <url-pattern> /* </url-pattern> <!-- If you list http methods, only those methods are protected --> <http-method> DELETE </http-method> <http-method> GET </http-method> <http-method> POST </http-method> <http-method> PUT </http-method> </web-resource-collection> <auth-constraint> <!-- Roles that have access --> <role-name> test </role-name> </auth-constraint> </security-constraint> <!-- BASIC authentication --> <login-config> <auth-method> BASIC </auth-method> <realm-name> Example Basic Authentication </realm-name> </login-config> <!-- Define security roles --> <security-role> <description> Test role </description> <role-name> test </role-name> </security-role>.. 4. Start Tomcat. 5. Type http://localhost:8080/liangweb/firstservlet from a Web browser, you will be prompted to enter user name and password, as shown in Figure 4. 15

Figure 4 Tomcat supports basic authentication using the Memory realm. 10.2 Setting a Secured Server Using Database Realm To set a Database realm, do the following: 1. Inside the <Engine>... </Engine> tag in conf/server.xml, insert the following lines: <Realm classname="org.apache.catalina.realm.jdbcrealm" drivername="oracle.jdbc.driver.oracledriver" connectionurl="jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl" connectionname="scott" connectionpassword="tiger" usertable="users" usernamecol="username" usercredcol="user_pass" userroletable="userroles" rolenamecol="rolename" /> The classname is always the same. The drivername specifies a fully qualified JDBC driver name (e.g., oracle.jdbc.driver.oracledriver for Oracle database). The connectionurl specifies the database URL. Note that the JAR file for the driver should be placed in the /common/lib directory. The connectionname is the database user name in which authorized Tomcat users are stored. The connectionpassword specifies the password for the database user. The usertable specifies the table where the authorized Tomcat user information is stored. The usernamecol specifies the column name in the usertable table for storing the authorized Tomcat user names. The usercredcol specifies the column name in the 16

usertable table for storing the authorized Tomcat user password. The rolenamecol specifies the column name in the usercredcol table for storing the role names. 2. Create the Users table and UserRoles table tables in the database as follows: create table Users ( username varchar(15) not null primary key, userpass varchar(15) not null ); create table UserRoles ( username varchar(15) not null, rolename varchar(15) not null, primary key (username, rolename) ); Authorize two users named student1 and student2 with password pstudent1 and pstudent2. Store the information in the Users table, as follows: insert into Users values ('student1', 'pstudent1'); insert into Users values ('student2', 'pstudent2'); Assign student1 and studnet2 to the role named test and store the information in the UserRoles table, as follows: insert into UserRoles values ('student1', 'test'); insert into UserRoles values ('student2', 'test'); 3. Uncomment the following lines in conf/web.xml and modify the <role-name> field to test. This is the role used for the users in the Memory realm defined in Step 2.... <security-constraint> <web-resource-collection> <web-resource-name> Protected Site </web-resource-name> <!-- This would protect the entire site --> <url-pattern> /* </url-pattern> <!-- If you list http methods, only those methods are protected --> <http-method> DELETE </http-method> <http-method> GET </http-method> <http-method> POST </http-method> <http-method> PUT </http-method> </web-resource-collection> <auth-constraint> 17

<!-- Roles that have access --> <role-name> test </role-name> </auth-constraint> </security-constraint> <!-- BASIC authentication --> <login-config> <auth-method> BASIC </auth-method> <realm-name> Example Basic Authentication </realm-name> </login-config> <!-- Define security roles --> <security-role> <description> Test role </description> <role-name> test </role-name> </security-role>.. 4. Start Tomcat. 5. Type http://localhost:8080/liangweb/firstservlet from a Web browser, you will be prompted to enter user name and password, as shown in Figure 4. Figure 5 Tomcat supports basic authentication using the Database realm. 18