Magazine
 
Tips & Tricks
 
String password = ((HttpServletRequest)
req).getParameter(“password”);
// Check whether it matches with the desired
password.
if(password.equals(“mypassword”)) {
long start = System.currentTimeMillis();
String address = req.getRemoteAddr();
String file = ((HttpServletRequest)
req).getRequestURI();
// Pass control to the WelcomeServlet’s
service() method

chain.doFilter(req, res);
// After returning the control back to the
filter, log user ip, resource uri and time used .
filterConfig.getServletContext().log(“ User IP:
“ + address + “ Resource: “ + file + “
Milliseconds used: “ +
(System.currentTimeMillis() - start) );
}
else {
// If password doesn’t match then send
the page informing incorrect password.
res.setContentType(“text/html”);
PrintWriter pw = res.getWriter();
pw.println(“<html>”);
pw.println(“<head><title>Wrong
Password</title></head>”);
pw.println(“<body>”);
pw.println(“<h3>Sorry, the password
was incorrect.</h3>”);
pw.println(“</body>”);
pw.println(“</html>”);
}
}
public void destroy() { }
}

WelcomeServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class WelcomeServlet extends
HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws

 

 
ServletException, IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
String username =
req.getParameter(“username”);
out.println(“<html><body>Welcome :
<b>”+username+”<br/><br/>”);
out.println(new Date().toString());
out.println(“</b></body></html>”);
}
}

To make the filter work, declare the filter in Deployment Descriptor. If filter is required to be used only when the specific servlet is requested then filter is mapped to that
servlet. To create a filter mapping for a specific servlet, map the filter to the name of a servlet by specifying the name of the filter in <filter-name> element and servlet’s name in <servlet-name> element.

Web.xml

<?xml version=”1.0" encoding=”ISO-8859-
1"?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN”
“http://java.sun.com/j2ee/dtds/webapp_
2_2.dtd”>
<web-app>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<servlet-name>WelcomeServlet</servletname>
</filter-mapping>
<servlet>
<servlet-name>WelcomeServlet</servletname>
<servlet-class>WelcomeServlet</servletclass>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-

Dec 2007 | Java Jazz Up | 77
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 ,

Download PDF