Saturday, November 27, 2010

Simple servlet to print parameters and attributes, headers and cookies


public class MyServlet extends GenericServlet
{

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
{
System.out.println("\n\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(">>> alexey: MyServlet.service 1 = " + 1);

HttpServletRequest hReq = (HttpServletRequest)req;
HttpServletResponse hRes = (HttpServletResponse)res;

printParsAndAttrs(hReq);
printHeaders(hReq);
printCookies(hReq);

}

private void printParsAndAttrs(ServletRequest req)
{
Enumeration parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements())
{
String name = (String)parameterNames.nextElement();
System.out.println(">>> alexey: MyServlet.logParsAndAttrs P name = " + name);
System.out.println(">>> alexey: MyServlet.logParsAndAttrs = " + req.getParameter(name));
}
Enumeration attributeNames = req.getAttributeNames();
while (attributeNames.hasMoreElements())
{
String name = (String)attributeNames.nextElement();
System.out.println(">>> alexey: MyServlet.logParsAndAttrs A name = " + name);
System.out.println(">>> alexey: MyServlet.logParsAndAttrs = " + req.getAttribute(name));
}
}

private void printHeaders(HttpServletRequest hReq)
{
Enumeration headerNames = hReq.getHeaderNames();
if (headerNames != null)
{
while (headerNames.hasMoreElements())
{
String name = (String)headerNames.nextElement();
System.out.println(">>> alexey: MyServlet.printHeaders H name = " + name);
System.out.println(">>> alexey: MyServlet.printHeaders = " + hReq.getHeader(name));
}
}
}

private void printCookies(HttpServletRequest hReq)
{
Cookie[] cookies = hReq.getCookies();
if (cookies != null)
{
for (Cookie cookie : cookies)
{
System.out.println(">>> alexey: MyServlet.printCookies C name = " + cookie.getName());
System.out.println(">>> alexey: MyServlet.printCookies = " + cookie.getValue());
}
}
}

}


1 comment:

Igor Azarny said...

Use MessageFormat.format for more attractive output.