Mike Roberts
Mike Roberts

Reputation: 550

JSP/Servlet Attribute Validation

Is there a way to validate request attributes passed from Servlet to JSP?

For example, in my Servlet I do something like this:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Foo foo = new Foo();
    request.setAttribute("foo", foo);
    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/bar.jsp);
    dispatcher.forward(request, response);
}

bar.jsp looks like this:

<html>
    <body>
        ${foo.getBaz}
    </body>
</html>

In bar.jsp, is there a way to ensure that the "foo" attribute is a Foo object? We use the Maven JSPC plugin to compile JSPs and it'd be nice to catch refactoring/renaming errors (like Foo.getBaz() being renamed to Foo.getFluff()) at compile-time.

Upvotes: 2

Views: 834

Answers (2)

TimeToCodeTheRoad
TimeToCodeTheRoad

Reputation: 7312

check out the instanceof operator in java. It should solve your problem.

Upvotes: 1

Saket
Saket

Reputation: 46137

You could use a scriptlet such as this:

<%
Foo foo = (Foo) request.getAttribute("foo");
String baz = foo.getBaz();
%>

and then use baz within your HTML as <%= baz %>

Upvotes: 0

Related Questions