Web Application Deployment Descriptors – “web.xml”

he “web.xml” contains the deployment descriptors. There are two sets of web.xml

:

  1. $CATALINA_HOME\conf\web.xml: applicable to all web application under Tomcat.
  2. WebContextRoot\WEB-INF\web.xml: applicable to the specific web context. It overrides the global setting, if any.

The complete specification for “web.xml” can be found in the “Java Servlet Specification” (@ http://java.sun.com/products/servlet), under “Deployment Descriptor”.

Suppose that you wish to deploy two servlets: TestServlet.class and QueryServlet.class (that have to be kept under your application’s “WebContextRoot\WEB-INF\classes” directory):

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0" metadata-complete="true">

  <servlet>
    <servlet-name>Test</servlet-name>
    <servlet-class>TestServlet</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>Query</servlet-name>
    <servlet-class>QueryServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/Echo</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>Query</servlet-name>
    <url-pattern>/Query</url-pattern>
  </servlet-mapping>
</web-app>

Explanation:

  • Each servlet requires two configuration elements. A <servlet> to specify the servlet-name and the servlet-class, and a <servlet-mapping> to specify the URL for that particular servlet-name. In the above example, the TestServlet can be referenced via URL http://host:port/context-path/Echo, and the QueryServlet via URL http://host:port/context-path/Query.
  • You have to list ALL the <servlet> elements first, followed by <servlet-mapping> elements.

Tomcat’s Global Configuration Files

Tomcat’s Global Configuration Files

Tomcat has three global configuration files (applicable to all web applications) at $CATALINA_HOME\conf:

  • $CATALINA_HOME\conf\server.xml: Tomcat main configuration file.
  • $CATALINA_HOME\conf\web.xml: web application deployment descriptors, for all the web contexts.
  • $CATALINA_HOME\conf\context.xml: Tomcat specific configuration options.

Directory Structure of a Web Context

All the Java web application (servlet, JSP, JSF, web services) follows a standard structure, which enables deployment in a Java-capable web server (such as Apache Tomcat and Glassfish). A web context may contain many types of files, such as HTML, CSS, Scripts, images, JSP, servlet, utility classes, external lib aries (jar files). All these files are to be kept under a standard directory structure, as illustrated:

  • WebContextRoot: The directory that your application resides is called the context root (or document base directory). You should keep all your HTML files and resources visible to the web users (e.g., CSS, Scripts, images, JSPs) under the context root. You can create sub-directory, such as scripts and images, under the context root.
  • WebContextRoot\WEB-INF: This directory, although under the context root, is not visible to the web users. This is where you keep your application specific configuration files such as web.xml.
  • WebContextRoot\WEB-INF\classes: This is where you keep all the Java classes such as servlets class-files
  • WebContextRoot\WEB-INF\lib: This is where you keep the jar files and native libraries, from external parties.
  • WebContextRoot\WEB-INF\src: You can keep your source files here or outside the web context. Source files are usually not distributed in production.
  • WebContextRoot\META-INF: Like WEB-INF, this directory is also not visible to the web users. This is for Tomcat specific configuration option files, such as context.xml.

Apache Tomcat 6.0 Realm Configuration HOW-TO

This document describes how to configure Tomcat to support container managed security, by connecting to an existing “database” of usernames, passwords, and user roles. You only need to care about this if you are using a web application that includes one or more <security-constraint> elements, and a <login-config> element defining how users are required to authenticate themselves. If you are not utilizing these features, you can safely skip this document.

 

http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html#JDBCRealm

 

Authentication in JSP

Introduction

Authentication is a process of proving that someone is who they say they are. In Web applications, authentication generally consists of two parts: querying for credentials (usually by some interface that requests a login name and password) and verifying those credentials against some source (such as a database). Most Web applications created or worked with using servlets and JSP will have some kind of authentication process to determine who is accessing the application. Bare in mind that authentication is not the same thing as authorization, which is the process of determining what parts of a Web site or Web application a user can access after his or her identity has been authenticated.

This article will provide brief examples of some familiar JSP-based authentication schemes. Unfortunately, because authentication is tied into the Web.xml (Java) and Web.config (Microsoft® ASP.NET) files, the Java Language Conversion Assistant (JLCA) will not directly convert authentication rules. We will look briefly at what the JLCA does and how to finish the conversion process. Finally, we will discuss the various types of authentication available to ASP.NET applications, and how to implement these schemes so that the authentication process on a new ASP.NET application will be as close as possible to the process in a JSP application.

Authentication in JSP

There are actually four different ways of authenticating users using servlets and JSP. These are:

  • Basic authentication, which is defined in the HTTP/1.1 specification. When a user attempts to access a JSP page, the system will request a user name and password (using a built-in interface that depends on the Web browser) and will allow several (usually three) attempts to supply correct credentials before providing an error page (usually an HTTP 401 Unauthorized error).
  • Form-based authentication, which is similar to basic authentication except that you can create your own login interface by using HTML. This is often more useful than basic authentication because you can create login interfaces that require something other than, or in addition to, the traditional user name and password (such as an e-mail address or digits of a telephone number).
  • Digest authentication is also similar to basic authentication, except that passwords are encrypted using a hash formula. This makes digest authentication more secure than basic authentication, as only the password’s hash value is transmitted over HTTP. However, digest authentication is still rarely used, simply because there are better and more complex ways of providing security (such as using HTTPS and SSL).
  • Client certificate authentication requires that each client accessing the resource has a certificate that it sends to authenticate itself. This type of authentication requires the SSL (Secure Sockets Layer) protocol.

Only the first two of these authentication methods are commonly used in JSP applications. An example of each follows.

Basic Authentication

Assuming you have a JSP application you want to secure, you can create a basic authentication scheme that will cause a user’s browser to present him or her with a dialog requesting a user name and password each time he or she attempts to access a page in that application in a new session.

Login configuration

To indicate that your server should be using basic authentication, you need to add a <login-config> element to your Web.xml file (if this element does not already exist). Web.xml is usually located in the WEB-INF directory on your server. The <login-config> element should look something like Listing 1.

Listing 1. A <login-config> element for basic authentication

<login-config>
   <auth-method>BASIC</auth-method>
   <realm-name>CodeNotes Examples</realm-name>
</login-config>

You would want to change the realm name to something more suited to your own application. In addition, notice how we indicate that basic authentication will be used using the keyword BASIC. The other three methods of authentication use similar capitalized keywords: FORM, DIGEST, and CLIENT-CERT.

Security constraints

You then need to add a security constraint to Web.xml for each page that requires authentication. A <security-constraint> element looks something like Listing 2.

Listing 2. A <security-constraint> element for basic authentication

<security-constraint>
   <web-resource-collection>
   <web-resource-name>Hello with BASIC protection</web-resource-name>
   <url-pattern>/HelloBasic.jsp</url-pattern>
   </web-resource-collection>
   <auth-constraint>
   <role-name>codenotes</role-name>
   </auth-constraint>
</security-constraint>

As you can see, a security constraint consists of two parts: a Web resource collection, which names the resource and provides its URL so that the server knows that this particular page requires authentication; and an authorization constraint, that allows you to indicate what roles (that is, groups of users) are allowed to access the page.

User names and passwords

The location and method in which user names and passwords are stored depends on the servlet container you use to provide access to your servlets and JSP pages. For example, the Tomcat servlet contains stored user names and passwords in an unencrypted XML file named Tomcat-users.xml (located in Tomcats conf folder). Each user is stored in a separate <user> element, which looks something like Listing 3.

Listing 3. A <user> element in Tomcat-users.xml

<user name=craig password=secret roles=codenotes />

Each user has a user name, a password and a list of roles, or groups, of which he or she is a member. The roles attribute can contain a comma-separated list of roles so that users can be members of more than one role. Remember that we indicate roles that can access our JSP pages, and not specific users.

Other servlet containers or Web servers will have their own methods of storing user names and passwords. Having developed JSP applications in the past, you will probably be familiar with your own server; if not, you should see its documentation to determine where this information is kept.

Accessing the page

If you completed the steps above, opening the page HelloBasic.jsp in Microsoft® Internet Explorer will cause a dialog box to appear in your browser. You must provide a valid user name and password in order to access the page.

Notice that the realm name we specified in the <login-config> element is used as the subtitle for this dialog box. Remember also that the appearance of this dialog box will be different if you are using a browser other than Internet Explorer; the basic structure and functionality of the box, however, will be the same.

Form-based Authentication

The basic steps of adding form-based authentication are very similar to those for basic authentication, except that there is the additional work of designing a login page containing the form that will allow a user self-authentication.

Login configuration

As with basic authentication, you need to add a <login-config> element to Web.xml. This time, however, the element is a little more complicated because you need to tell the servlet container where to find the login page and, optionally, where to find the error page that will be displayed if the login is unsuccessful.

Listing 4 shows a <login-config> element for a JSP application using form-based authentication.

Listing 4. A <login-config> element for forms-based authentication

<login-config>
   <auth-method>FORM</auth-method>
   <form-login-config>
   <form-login-page>/login.jsp</form-login-page>
   <form-error-page>/error.jsp</form-error-page>
   </form-login-config>
</login-config>

Notice that the <realm-name> element has been replaced by a <form-login-config> element, in which we specify the login and error pages. Also notice that the BASIC keyword has been replaced by FORM.

Security constraints

The <security-constraint> element can be exactly the same as it was for basic authentication. No special additions are required to make authentication form-based. The only difference that you will see in the example at the end of this section is that the page that requires authentication is called HelloForm.jsp rather than HelloBasic.jsp.

Designing a login form

Login forms require the use of special keywords for the actions or names of the <form> and <input> elements used for authentication. These keywords let the server know that these particular parts of the input should be checked against the stored user info. A simple login page might look like Listing 5:

Listing 5. A simple login page (login.jsp)

<html>
   <head><title>Login</title></head>
   <body>
      <form action="j_security_check" method="post">
         <p>Enter your user name and password here.</p>
         <p>User name: <input type="text" name="j_username" /></p>
         <p>Password: <input type="password" name="j_password" />
         </p>
         <p><input type="submit" value="Login" /></p>
      </form>
   </body>
</html>

All this page does is provide entry fields for a user name and password and a submit button that submits the field data. However, take note of the fact that the action for the form is j_security_check, and that the names of the user name and password <input> elements are j_username and j_password, respectively. These keywords are all defined in the servlet specification and must be used in order for this form to be treated as a login page.

Designing an error page

Forms-based authentication allows designed, custom error pages. Listing 6 shows an example of a simple error page that informs the user that their credentials were not valid, and provides a button to return to the login page and try again.

Listing 6. A simple error page (error.jsp)

<html>
   <head><title>Error</title></head>
   <body>
   <p>Sorry, you can't come in.</p>
   <form action='<%=response.encodeURL("login.jsp")%>' method="post">
      <input type="submit" value="Try Again" />
   </form>
   </body>
</html>

Note the use of the encodeURL() method. This method encodes the given URL with a session ID if one exists, or returns just the URL if one does not exist. You can find information on this and the other request and response methods in the J2EE API documentation.

Accessing the page

If you completed the steps above, opening HelloForm.jsp in Internet Explorer will open a page. Valid credentials will open HelloForm.jsp. Invalid credentials will open error.jsp.

Authentication in CodeNotes

The only area in the CodeNotes Web site that requires authentication is posting to forums. In the JSP version, the CodeNotes Web site uses a simple forms-based authentication, but does not directly tie into the authentication schemes defined in the J2EE specification. Although this situation is not ideal, it worked well for our particular needs. A more common case would be to require a login for any action on the Web site. For those scenarios, one of the above authorization schemes would be more appropriate.

login page in jsp

Login page in jsp

————–
<%@ page language =”java” import=”java.sql.*” %>
<html>
<body bgcolor=”pink”>
<form name=”f1″ method=”post”>
<table>
<tr>
<td>User Name</td><td><input type=”text” name=”t1″ ></td>
</tr>
<td>Password</td>
<td><input type=””password”” name=”t2″></td>
</tr>
<tr>
<td></td>
<td><input type=”submit” name=”b1″ value=”LogIn”></td>
</tr>
</table>
<%
String user=request.getParameter(“t1”);
String pass=request.getParameter(“t2”);

try{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“jdbc:odbc:mydsn”, “jp”, “jp”);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(“select username,password from userlog”);
while(rs.next())
{
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
%>
<jsp:forward page=”/Training_solutions/LoginSuccess.jsp” />
<%}
else
out.println(“Login Failed,Please try Againe”);
%>

<%
}
}catch(Exception e1)
{}

%>

</form>
</body>
</html>
================
LoginSuccess.jsp
—–
<hi>U sucessfuly Entered</h1>

install the windows fonts on my Fedora

install the windows fonts on my Fedora

Advice: Use ctrl+shift+v to copy into your console.

1

wget http://www.my-guides.net/en/images/stories/fedora10/msttcore-fonts-2.0-2.noarch.rpm

2

su -c ‘rpm -ivh msttcore-fonts-2.0-2.noarch.rpm’

3

su -c ‘yum install rpmdevtools rpm-build cabextract ttmkfdir’

4

rpmdev-setuptree

5

cd ~/rpmbuild/SPECS/

6

wget http://www.my-guides.net/en/images/stories/fedora10/msttcore-fonts-2.0-2.spec

7

rpmbuild -bb msttcore-fonts-2.0-2.spec

8

cd ~/rpmbuild/RPMS/noarch/

9

su -c ‘rpm -ivh msttcore-fonts-2.0-2.noarch.rpm’

Performance improvement techniques in loops in java

 

This topic illustrates the performance improvement techniques in loops with the following sections:

  • Overview of loops
  • Optimization techniques in loops
  • Key Points

Overview of loops

Loops provide efficient way for repeating a piece of code as many times as required. Java has three types of loop control structures they are : for loop, while loop and do-while loop. The for loop is used when we know in advance how many iterations are required. The while loop is used when we do not know in advance the number of iterations required so each time before entering the loop the condition is checked and if it is true then the loop is executed. The do-while loop is always executed at least once and then the condition is checked at the end of the loop. Loops have a considerable effect on the performance of the program let us look at some points that focus on optimizing while using the loop control structures.

This section examples are tested on Windows millennium, 320mb RAM and JDK 1.3

Note: This section assumes that reader has some basic knowledge of Java loops.

Optimization techinques in loops

 

  • Always use an int data type as the loop index variable whenever possible because it is efficient when compared to using byte or short data types. because when we use byte or short data type as the loop index variable they involve implicit type cast to int data type.
  • When using arrays it is always efficient to copy arrays using System.arraycopy() than using a loop. The following example shows the difference

package com.performance.loop;// This class tests the loop copy versus System.arraycopy()

public class loopTest1{

public static void main(String s[]){

long start,end;

int[] a=new int[2500000];

int[] b= new int[2500000];

for(int i=0;i<a.length;i++){

a[i]=i;

}

start=System.currentTimeMillis();

for(int j=0;j<a.length;j++){

b[j]=a[j];

}

end=System.currentTimeMillis();

System.out.println(end-start + ” milli seconds for loop copy “);

int[] c= new int[2500000];

start=System.currentTimeMillis();

System.arraycopy(a,0,c,0,c.length);

end=System.currentTimeMillis();

System.out.println(end-start + ” milli seconds for System.arraycopy() “);

}

}

The output is

110 milli seconds for loop copy

50 milli seconds for System.arraycopy()

  • Always avoid anything that can be done outside of the loop like method calls, assigning values to variables, or testing for conditions .
  • Method calls are very costly and you only make it worse by putting them in a loop. So as far as possible avoid method calls in a loop.
  • It is better to avoid accessing array elements in a loop the better option would be to use a temporary variables inside the loop and modify the array values out of the loop. It is fast to use a variable in a loop than accessing an array element.
  • Try to compare the terminating condition with zero if you use non-JIT or HotSpot virtual machine, here is an example to prove the point. JIT or HotSpot virtual machines are optimized for general loops so you do not have to bother about the terminating condition.
package com.performance.loop;

// Note that this class may give different results in latest JDK versions as discussed above.

public class loopTest2{

public static void main(String s[]){

long start,end;

int[] a=new int[2500000];

start=System.currentTimeMillis();

for(int i=0;i<a.length;i++){

a[i]+=i;

}

end=System.currentTimeMillis();

System.out.println(end-start + ” millis with i<a.length “);

 

int[] b=new int[2500000];

start=System.currentTimeMillis();

for(int i=b.length-1;i>=0;i–){

b[i]+=i;

}

end=System.currentTimeMillis();

System.out.println(end-start + ” millis with i>=0″);

}

}

The output is

100 millis with i<250000

60 millis with i>=0

  • Avoid using method calls in loops for termination condition this is costly instead use a temporary variable and test the loop termination with the temporary variable.
  • When using short circuit operators to test for loop termination tests always put the expression that will most likely evaluate to false at extreme left.This saves all the following expressions from being tested in case there is an && operator and if there are only || operators then put the expression which is most likely to evaluate to true in the extreme left.
  • Avoid using try-catch inside the loops instead place the loops inside the try-catch for better performance

Key Points

  1. Use integer as loop index variable.
  2. Use System.arraycopy() to copy arrays.
  3. Avoid method calls in loops .
  4. It is efficient to access variables in a loop when compared to accessing array elements.
  5. Compare the termination condition in a loop with zero if you use non-JIT or HotSpot VMs.
  6. Avoid using method calls to check for termination condition in a loop
  7. When using short circuit operators place the expression which is likely to evaluate to false on extreme left if the expresion contains &&.
  8. When using short circuit operators place the expression which is likely to evaluate to true on extreme left if the expresion contains only ||.
  9. Do not use exception handling inside loops.