tags:

views:

48

answers:

2

Hi,

How will you handle the exception without sending to error page? How will you set a message detail to the exception object?(Not using any JSTL Tags)

Thanks, Ravi

+2  A: 

I think the best answer is you don't.

It is considered good design with jsp technology to handle all the stuff that can cause exceptions before you start the render-phase. This means you should normally try to do things that can cause exceptions in "execute" methods in your web framework before arriving at the jsp page. If you need to catch anything, do it there.

krosenvold
+2  A: 

Not using any JSTL Tags

I was going to suggest the c:catch, but as you don't want to use JSTL, it stops here.

Still then, it would have been a bad idea. You normally really don't want to use JSP for business logic. Just use (indirectly) a Servlet for this. With Servlets you can control, preprocess and/or postprocess requests and forward the request to the JSP file which in turn displays the data using EL and controls the page flow dynamically using taglibs like <jsp:xxx> and JSTL.

Here's a basic example based on the "login user" idea:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
        request.setAttribute("error", "Please enter both username and password.");
    } else {
        User user = userDAO.find(username, password);
        if (user == null) {
            request.setAttribute("error", "Unknown login, please try again.");
        } else {
            request.getSession().setAttribute("user", user);
            request.setAttribute("succes", "Login succesful!");
        }
    }

    request.getRequestDispatcher("login.jsp").forward(request, response);
}

and then the basic JSP example:

<form action="login" method="post">
     Username: <input type="text" name="username" value="${param.username}"><br>
     Password: <input type="password" name="password" value="${param.password}"><br>
     Login: <input type="submit" value="Login"><br>
     <span class="error">${error}</span>
     <span class="succes">${succes}</span>
</form>

You could go further by using for example a Map<String, String> for the messages so that you can attach an error message to every input field. You could go any further by using a MVC framework which takes all this work from your hands, but that's another story ;)

BalusC
Nice example +1
krosenvold