Wednesday, April 1, 2009

Creating Your own RequestProcessor

creating a custom RequestProcessor, we will change our sample application to implement these two business requirements:

  • We want to create a ContactImageAction class that will generate images instead of a regular HTML page.
  • Before processing every request, we want to check that user is logged in by checking for userName attribute of the session. If that attribute is not found, we will redirect the user to the login page.
We will change our sample application in two steps to implement these business requirements.
  1. Create your own CustomRequestProcessor class, which will extend the RequestProcessor class, like this:


public class CustomRequestProcessor

extends RequestProcessor {
protected boolean processPreprocess (
HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession(false);
//If user is trying to access login page
// then don't check
if( request.getServletPath().equals("/loginInput.do")
|| request.getServletPath().equals("/login.do") )
return true;
//Check if userName attribute is there is session.
//If so, it means user has allready logged in
if( session != null &&
session.getAttribute("userName") != null)
return true;
else{
try{
//If no redirect user to login Page
request.getRequestDispatcher
("/Login.jsp").forward(request,response);
}catch(Exception ex){
}
}
return false;
}

protected void processContent(HttpServletRequest request,
HttpServletResponse response) {
//Check if user is requesting ContactImageAction
// if yes then set image/gif as content type
if( request.getServletPath().equals("/contactimage.do")){
response.setContentType("image/gif");
return;
}
super.processContent(request, response);
}
}


In the processPreprocess method of our CustomRequestProcessor class, we are
checking for the userName attribute of the session and if it's not found,
redirect the user to the login page.

For our requirement of generating images as output from the ContactImageAction class,
we have to override the processContent method and first check if the request is
for the /contactimage path. If so, we set the contentType to image/gif; otherwise,
it's text/html
...

More Details


No comments:

Post a Comment

Followers