2012-01-03 109 views
1

我寫了下面的代碼:Spring MVC的3網址初學者

@Controller 
@RequestMapping("/test") 
public class Home { 

@RequestMapping(value = "index") 
public String index() { 
    return "index"; 
} 

@RequestMapping(value = "welcome") 
public String welcome(@RequestParam("txtname") String name, ModelMap model) { 
    model.addAttribute("msg", name); 
    return "index"; 
} 

} 

現在我有兩個疑問。我想要/ test這樣的東西來直接加載index()。現在我必須輸入/ test/index。我如何配置它。

其次index()和welcome()幾乎相同。只是請求參數被添加到輸出中。我寫了index(),因爲如果沒有參數,/ welcome將不起作用。我想讓txtname成爲可選的或類似的東西,以便可以放棄歡迎。

+1

你可以嘗試將@RequestParam設置所需=假:@RequestParam(值=「改爲txtName 「,required = false) – 2012-01-03 13:37:59

回答

3

我想要類似/ test的東西來直接加載index()。現在我必須輸入/ test/index。

只是跳過額外的映射:

@RequestMapping 
public String index() { 
    return "index"; 
} 

我想txtName的要進行選配什麼這樣,這樣的歡迎能夠被丟棄。

試試這個:

@RequestParam(value = "txtname", required = false) 

除了你welcome()方法可以簡化爲:

@RequestMapping(value = "welcome") 
public String welcome(@RequestParam("txtname") String name) { 
    return new ModelAndView("index", "msg", name); 
}