2011-06-06 121 views
1

我有一個控制器類,用於搜索學生數據庫並顯示其 信息。現在無論是否找到特定的學生,它都會顯示相同的屏幕。 如果後端搜索不返回任何數據,我打算顯示不同的視圖。對於這 我編碼我的控制器if else塊(數據發現:顯示視圖,否則顯示不同的看法),但 它似乎沒有工作。無論如何,我看到相同的觀點返回。在這個樣本 學生/ homePage。我在這裏做錯了什麼?Spring MVC控制器

@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 Found: Show student homepage 
     return "student/homePage"; 
    } 

    //No Student Found: Show splash page 
    return "student/noDataPage"; 
     } 
} 
+0

是否總是返回'student/noDataPage'或'student/homePage'的視圖? – Pat 2011-06-06 18:33:54

+0

其始終返回的視圖是student/homePage(這是舊頁面)。我添加了noDataPage並將其放在「if」之外。 – t0mcat 2011-06-06 18:35:43

+0

使用調試器並找出getRollNum()從不返回null的原因。如果你找不到,請發佈bundleStudentBean源碼。 – abalogh 2011-06-06 19:12:12

回答

1

而不是檢查rollNum是否爲空,更好地檢查它的值是否爲零。即使你對它沒有任何價值,函數也可能返回零。大多數情況下,在數據庫中你可能會設置列不爲空,並且int

1

好的做法:控制器方法應儘可能輕量級。

不良做法:using Exceptions as control flow

Spring MVC有一個很好的方法將業務異常映射到自定義視圖使用ExceptionHandlers。我認爲這只是控制器正在尋找學生而沒有發現的情況之一 - 使用ExceptionHandlers應該可以幫助您編寫可讀的輕量級控制器。