Rajesh
Rajesh

Reputation: 3034

How servlet filter will dispatch error message on request page?

I have written a servlet filter which is configured to be invoked for each url (/*). On the basis of some condition, if the condition is passed, I want to proceed normal execution by chain.doFilter(request,response), I also want to open same request URL with error message..

"say value entered in particular textbox is incorrect". Is this possible?

Do I have to use response.sendRedirect(request.getURL())? I hope I wont end up in infinite loop as I have configured filter on each URL. I am doing validation check on request parameter.

Upvotes: 3

Views: 5949

Answers (1)

BalusC
BalusC

Reputation: 1109172

Just do the same as you'd do in a servlet: perform a forward.

request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);

A filter is by default not (re)invoked on a forward. Additional advantage is that the JSP reuses the same request and thus you can just set the validation error messages as a request attribute without the need for session or cookie based workarounds/hacks.


Unrelated to the concrete problem, this isn't entirely the right approach. Form-specific validation job should be performed in a servlet, not in a filter. If you'd like to keep your servlet(s) DRY, then look at the front controller pattern or just adopt a MVC framework which already offers a front controller servlet and decent validation out the box, such as JSF or Spring MVC.

Upvotes: 5

Related Questions