Getting Started Guide
The most effective way to learn a framework is by examining and understanding a non-trivial application that uses it. Learning by just reading API documentation is often slower, since it is harder to see how your applications will work in practice. Any framework that doesn't give you such an example application isn't doing you any favors.
Since .class files are included in the download, there is no initial need to perform a compile before running the application. Once you modify the source, then a compile will be needed in order to see your changes.
(If you have followed these steps but still cannot launch the app successfully, just ask for email support. Please include log files, if any, and a description of the problem.)
The example applications aren't small. The tutorial is an alternative for those looking for a quicker introduction, and for those with less familiarity with Java web apps.
Table of Contents
Download
Configuring The Application : web.xml
Populating The Database
Configuring Tomcat : Context File
Configuring Tomcat : Jar Files
Configuring Captcha
First Launch
First Login
Main Links
Editing The Source
Adding New Users
Tomcat Manager
Disabling Login
Running Unit Tests
Download
The first step is to download the example app zip file, and unzip it to a convenient location. That location is referred as APP_HOME below. Just to be clear, here are two example listings of the contents of APP_HOME, one for each example app:For APP_HOME = 'C:\TEMP2\predictions' C:\TEMP2\predictions> dir /b css\ images\ main\ pub\ WEB-INF\ build.xml Error.html ... For APP_HOME = 'C:\myname\myprojects\fish\' C:\myname\myprojects\fish\> dir /b access\ all\ exercise\ images\ main\ translate\ WEB-INF\ webmaster\ build.xml Error.html ...
Configuring The Application : web.xml
Every web application based on servlets uses a web.xml file for configuration. Its official name is the deployment descriptor. It's located in[APP_HOME]\WEB-INF\web.xml
There are a number of web4j settings in the deployment descriptor. When getting started, the only ones you should likely set are:
- MailServerConfig and MailServerCredentials - mail server used to send TroubleTicket emails. This setting must be the server which is 'native' to your network. If you receive a "Relaying Denied" error, change this setting. Use 'NONE' to suppress emails entirely.
- Webmaster - the 'from' address on emails sent by the application. Must be on the same network as used by the MailServerConfig setting. For example, if you are on blah.com, then the Webmaster might be support@blah.com, while MailServerConfig might refer to smtp.blah.com.
- LoggingDirectory - location for application log files. Must end with a separator, as in 'C:\log\fish\'.
- TroubleTicketMailingList - who to inform in case of trouble.
- DefaultUserTimeZone - default time zone for the application, in the format used by TimeZone. Example values: UTC, America/New_York.
- RedirectWelcomeFile (Fish and Chips only) - Redirects directory requests to the home page Action. Depends on context and port.
Populating The Database
There is a single script for creating and populating the MySQL database. It's located in :[APP_HOME]\WEB-INF\datastore\mysql\CreateALL.SQLThe script has been validated against MySQL version 5.5.8. If you want to use a different database other than MySQL, then the script will need to be ported to the new target database. However, you need to be aware that there a number of settings in web.xml that are also sensitive to the database. To avoid problems with those relatively minor settings, you are strongly encouraged to use MySQL during this introduction to WEB4J.
In the CreateALL.SQL script, you may have to replace
DROP DATABASE/CREATE DATABASEwith
DROP SCHEMA/CREATE SCHEMA
The script is run using the mysql client :
[APP_HOME]\WEB-INF\datastore\mysql>C:\mysql\bin\mysql --local-infile=1 -u myname -pmypass < CreateALL.SQL
The above example runs the .SQL script directly from the directory where it resides.
You will need wide permissions in order to run the script.
It's important to note that the user and role tables contain entries suitable only for testing. If you build a 'real' application from this example application, you will need to remove such entries. Note as well that user passwords are protected by being stored in a hashed form. You can enter new user names and passwords only through the application, not by direct manipulation of the tables (see below).
This script sets the default encoding for all tables to UTF-8.
Configuring Tomcat : Context File
The example application needs to have its context file copy into Tomcat, and then configured.| Predictions context file: | [APP_HOME]\WEB-INF\tomcat\predict.xml |
| Fish and Chips Club context file: | [APP_HOME]\WEB-INF\tomcat\fish.xml |
You simply copy the context file into the directory named
[TOMCAT_HOME]\conf\Catalina\localhost\
If the above directory doesn't exist, then just create it.
You must then edit the context file to match your environment. Remember to :
- change user names
- change passwords
- change the docBase attribute to match your [APP_HOME] directory
Please edit the context file with care. Any mistake will cause the launch of the app to fail. If you have a problem launching, the cause is almost always with the context file.
The context file specifies :
- database connections
- a 'security realm', needed for log in operations handled by Tomcat
- mapping your APP_HOME directory to a URL path or 'context'. This mapping is a way of deploying an application directly, without needing to create a .war file. Instead of a giving Tomcat a .war file, it's simply instructed on where to find the web app implementation on the local file system. This is the preferred style when developing, since there is no need to go through a build-and-deploy cycle in order to see updates.
Here are two examples of a customised version of the context file. Compare them with your version, to see where you need to make changes specific to your own environment.
Important: the docBase attribute of the <Context> tag must point to your APP_HOME.
For predict.xml:
<Context docBase="C:\TEMP2\predictions" reloadable="true"> <Resource name="jdbc/predict" auth="Container" type="javax.sql.DataSource" username="fred" password="****" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/predict?useServerPrepStmts=false" maxActive="10" maxIdle="5" /> <Realm className="org.apache.catalina.realm.JDBCRealm" connectionURL="jdbc:mysql://localhost:3306/predict" digest="SHA-1" driverName="com.mysql.jdbc.Driver" roleNameCol="Role" userCredCol="Password" userNameCol="LoginName" userRoleTable="userrole" userTable="users" connectionName="fred" connectionPassword="****" debug="99" /> </Context>
For fish.xml:
<Context docBase="C:\bob\projects\fish" reloadable="true"> <Resource name="jdbc/fish" auth="Container" type="javax.sql.DataSource" username="bob" password="****" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/fish?useServerPrepStmts=false" maxActive="10" maxIdle="5" /> <Resource name="jdbc/fish_translation" auth="Container" type="javax.sql.DataSource" username="bob" password="****" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/fish_translation" maxActive="10" maxIdle="5" /> <Resource name="jdbc/fish_access" auth="Container" type="javax.sql.DataSource" username="bob" password="****" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/fish_access" maxActive="10" maxIdle="5" /> <Realm className="org.apache.catalina.realm.JDBCRealm" connectionURL="jdbc:mysql://localhost:3306/fish_access" digest="SHA-1" driverName="com.mysql.jdbc.Driver" roleNameCol="Role" userCredCol="Password" userNameCol="Name" userRoleTable="UserRole" userTable="Users" connectionName="bob" connectionPassword="****" debug="99" /> </Context>
Configuring Tomcat : Jar Files
Two jar files must be made visible to your application :- the database driver
- junit.jar
- [TOMCAT_HOME]\lib\
It's a bit silly to require junit.jar for a deployment. The reason it's required is because WEB4J loads all classes in your app upon startup, and examines them using reflection. In a production deployment, you would likely remove all JUnit test classes, and there would be no need for junit.jar.
Configuring Captcha
This section applies to the Predictions application only. It doesn't apply to the Fish and Chips Club, which doesn't use a captcha.A captcha is often used on the public web. They're used to prevent bots from creating accounts and putting spam into databases. The Predictions application implements a captcha using :
- a recaptcha account
- a Java library named recaptcha4j (created by Soren Davidsen)
To use Predictions, you will need to create a recaptcha account. (Don't worry, it only takes a minute.) When you create an account, you will receive two items: a public key and a private key. These keys identify which app is calling the recaptcha server. Inside the Predictions app, you need to do two things with these keys:
- put your private key value in the CaptchaPrivateKey setting, in WEB-INF/web.xml
- put your public key value in the WEB-INF/tags/captcha.tag file; simply replace the text 'YOUR_PUBLIC_KEY_GOES_HERE' with the value of your public key
First Launch
To launch the application, start Tomcat. Check the log file, located in the LoggingDirectory you configured in web.xml. There should be a new time-stamped log file in that directory. If there is no log file, then a problem has occured. If so, check the Tomcat logs located in [TOMCAT_HOME]\logs. Tomcat uses several log files, so look around the various files. Look for stack traces, and anything logged at SEVERE level. Possible causes of error:- typo while editing web.xml or the context file (see above) has rendered the file syntactically invalid.
- missing .jar files
- problem with JSP tag libraries
- your environment doesn't meet the requirements somehow
For purposes of comparison, example log files are included, under [APP_HOME]. A successful launch will end with the time it has taken to initialize the app (usually about a second). If you see such a message, then congratulations, you have launched the example application successfully. Hallelujah.
If your need to test JSP taglib configuration, a simple test page has been provided, called TestTags.jsp. It's located in the root of the web app. Example URLs:
http://localhost:8080/predict/TestTags.jsp http://localhost:8080/fish/TestTags.jsp
First Login
Navigate to the context path you defined in the context file (predict.xml, fish.xml) :http://localhost:8080/predict/ http://localhost:8080/fish/
Predictions will let you view some pages, without needing to login in immediately (in the style of most public web apps). Fish and Chips Club, on the other hand, forces you to login in immediately (in the style of most intranet apps).
Either way, you can log in with user name 'testeD', and password 'testtest'.
It's important that you understand the mechanics of the login mechanism, so that you don't bookmark the wrong item. That is, you're not supposed to bookmark the login page itself. It's natural to find this confusing. Rather, you're supposed to bookmark the home page (or some other page you are interested in). Then, when you navigate to that bookmark, and you're already logged in, then you won't be bothered with a second, unnecessary login. But, if you are not logged in, then a security-constraint defined in web.xml which protects that URL will be activated, and you will be asked to provide a user name and password in the usual way.
This kind of behavior is defined by the servlet specification's form-based login mechanism. Once you understand this mechanism, you can see that attempting to bookmark the Login.jsp page itself does not make sense: after successful login, Tomcat would not know where you 'really' wanted to go.
Main Links
The Predictions example app is pretty simple.
- Main home page - link
- Search (no login required) - link
- and so on, with the links in the navigation menu
The Fish and Chips example app has distinct modules. Users can access the various modules only if they have been assigned the proper role. (The user name mentioned in the previous section has wide open permissions.) Here are the links to the main page in each module. These links are valid for the default Tomcat port 8080, and with 'fish' as the context path. Please amend as needed.
- Main home page - link
- Webmaster module - link
- Access Control module - link
- Preferences module - link
- Translation module - link
- Exercise module - link
Editing The Source
You may of course edit the source. It's likely best to use a modern IDE, such as IntelliJ Idea, NetBeans, or Eclipse. Many IDEs can automatically compile as you edit. In addition, Tomcat will automatically refresh the app when it detects changes.The startup time is short - usually under a second. When you have configured Tomcat's <Context> as described above, where the context is mapped directly to the source code root directory, then you can see your changes reflected quickly, without an extended waiting period.
You can also use the WEB4J Developer Tools to speed up your development. (The Log Viewer is particularly useful.)
Adding New Users
Usually, you will want to create a more convenient user name and password. This must be done through the screens provided by the application itself, and not by editing the access control database tables directly. The password is stored in a hashed form, in order to keep it secret. The hash function is defined in Java, not in MySQL. So, it's not possible to add a new user correctly by using only MySQL tools.In the beginning, adding a new user will seem unnecessarily painful. There is some inconvenience, but there's a reason for the inconvenience. The whole idea of an example application is to mimic what a 'real' application might do.
Predictions
The Predictions app follows the style of most public web apps. Creation of user accounts is handled by the user. The steps are:- select the Login link
- select the "Not Registered Yet?" link
- enter the information in the form, including the captcha
- finally, do a regular login, using your new credentials
- (if you forget your login, you can later reset your password)
Fish and Chips Club
Th Fish and Chips Club mimics the style of most intranet applications. Creation of accounts is controlled not by the user, but by some other party within the organization. For intranet apps, it's a common requirement to :- separate out the user maintenance role to people who are explicitly assigned that single role
- assign one or more roles to each user
To add a new user, navigate to the Access Control module:
http://localhost:8080/fish/access/user/UserAction.list
Login as 'testeD', as described above. (This user has wide privileges.)
You add a new user in two steps :
- add a user name (Users screen).
- assign one or more roles to the new user name (Roles screen). If you are adding a new user name for yourself, you usually want to assign every role to yourself. Otherwise, you will not have access to all features.
When a new user is added, they always receive the default password
'changemetosomethingalotmoreconvenienttotype'This password is intentionally inconvenient, so that the user will be motivated to change it. After login, any user can change their password at any time by navigating to the Preferences screen. (This is simply an example of a particular password policy. Many others are possible.)
Tomcat Manager
Tomcat comes with a simple tool for managing your deployed web applications, called Tomcat Manager. It has a nice reload mechanism, whereby you may reload your app, when needed, simply through a browser refresh. It's always best to reload an application instead of the server, since a server restart takes longer.Tomcat Manager requires login. You need to add an entry to [TOMCAT_HOME]\conf\tomcat-users.xml, such that a user has the role of 'manager'. Here is an example entry:
<?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="manager"/> <user username="blah" password="blah" roles="manager"/> </tomcat-users>The tool is accessed using :
http://localhost:8080/manager/html/list
Disabling Login
Sometimes it's convenient to disable login during development. To disable login, edit [APP_HOME]\WEB-INF\web.xml, and comment out these items :- all <security-constraint> tags
- in older versions of web4j (previous to version 4.3.0 of September 2009), you also need to comment out the <filter-mapping> tag which enables the CsrfFilter