I have a controller class that makes a search on the Student Database and displays its information. Right now no matter if a particular student is found or not, it displays the same screen. I am planning to show a different view if backend search doesnt return any data. For this I coded my controller with if else block (data found: show view, else show different view) but it doesnt seem to be working. In any case I am seeing the same view returned back. In this sample student/homePage. What am I doing wrong here?
@Controller
public class StudentController extends BaseClassController
{
@RequestMapping( value = "/student/studentSearch.html", method = RequestMethod.POST )
public String searchStudent( Arguments )
{
if( bundleStudentBean.getRollNum() != null)
{
try
{
//Call Service layer and get the data
//Set into a model
}
catch( ServiceException e )
{
// Some exception occured
}
catch( Exception e )
{
//print error trace
}
//Student Fou开发者_StackOverflow社区nd: Show student homepage
return "student/homePage";
}
//No Student Found: Show splash page
return "student/noDataPage";
}
}
Instead of checking whether the rollNum to null,better check whether it's value is zero. Chances are more that the function returns zero even when youi give no value into it.Most probably in the database you would have set the column to be not null and int
Good practice: Controller methods should be as lightweight as possible.
Bad practice: using Exceptions as control flow.
Spring MVC has a nice way of mapping business exceptions to custom views using ExceptionHandlers. I assume this is only one of the cases where a Controller is looking for a student and finds none - using ExceptionHandlers should help you write readable, lightweight Controllers.
精彩评论