2
votes

I am using Spring MVC to build my web application, and I have a question about validating parameters I receive in the URL. What is the best way to detect invalid parameters and display errors to the user?

Suppose I have a "View User Profile" page. The profile that is displayed is based on a user ID parameter specified in the URL. I might go to the following address to view the profile of the user with ID 92:

http://www.somedomain.com/profile.html?id=92

I have created a ProfileControlller object which will do the following:

  1. Get the id parameter from the request object
  2. Load a UserProfile object from my database
  3. Add the UserProfile object to the model
  4. Construct a ModelAndView with my model and the "View User Profile" JSP

That works fine if the user enters a valid ID number. My UserProfile object is loaded and displayed perfectly using JSP. But what if someone passes user ID -30294 to my page? My data access layer will simply return a null object if the ID is invalid, but I would like to show a friendly error message to the user. Is checking for a null UserProfile object in the JSP code really the best solution here?

Since I am new to Spring, I'm not sure. I like the way Validator classes can be used with FormController objects, if that is any help.

2

2 Answers

5
votes

If the DAO returns null, simply return a ModelAndView for an error page.

Example:

UserProfile profile = userProfileDao.findUserProfileById(userId);
if (profile == null) {
    return new ModelAndView("Error", "message", "Invalid user ID");
} else {
    // process accordingly.
}

In the Spring 2.5 distribution, check the jpetstore application in the samples directory. Find the org.springframework.samples.jpetstore.web.spring.SignonController for a simple example with an application.

0
votes

Out of the desire to avoid writing a lot of code, the way I do this is let an Exception get thrown by either the Data Access or Service layer. It is then thrown by the web controller, and goes to a general error page that has been configured in the web.xml file, that would say something like "page not found."

But it really depends on your domain and requirements. A recent app I wrote was a simple social network where the users didn't have the option to deactivate their account or change their username. So, the only way that they could have requested an invalid profile was by monkeying around with the URL. I wasn't about to create a more specific error page just to show them they were monkeying around with it wrong.

But if you DID allow the user to, for example, deactivate their account, you may want to take an approach like yawmark does and show a more specific error message.