SpringMVC的簡略傳值(完成代碼)。本站提示廣大學習愛好者:(SpringMVC的簡略傳值(完成代碼))文章只能為提供參考,不一定能成為您想要的結果。以下是SpringMVC的簡略傳值(完成代碼)正文
之前進修SpringMVC時感到他的傳值很奇異:輕便,快捷,高效。
明天寫幾個簡略的傳值與年夜家分享,願望能對年夜家有贊助。
1、
從後往前傳:
(1)
@Controller
@RequestMapping(value={"/hello"})
public class HelloController {
@RequestMapping(value={"sub"})
public ModelAndView submit(HttpServletRequest request) throws Exception {
// TODO Auto-generated method stub
ModelAndView m=new ModelAndView();
m.addObject("ok", "hello");
m.setViewName("success");
return m;
}
}
把想要傳遞的器械放在addObject(String,Object)裡,值是Object類型,甚麼都可以放。
setViewName() 是設置跳轉到哪一個頁面 (success.jsp頁面)。
在success.jsp 頁面裡用${requestScope}或${ok}便可掏出。是否是異常輕便快捷。
還可以以這類方法傳:
@Controller
@RequestMapping(value={"/user"})
public class UserController {
@RequestMapping(value={"/get"})
public ModelAndView user(User user) throws Exception {
ModelAndView mv=new ModelAndView();
mv.addObject("ok",user.getUsername()+"--"+user.getPassword());
mv.setViewName("success");
return mv;
}
}
前端是一個簡略的form表單:
<form action="user/get" method="post">
<input type="text" name="username" id="username">
<input type="text" name="password" id="password">
<input type="submit">
</form>
(2)前往值也能夠不是ModelAndView
@RequestMapping(value={"/map"})
public String ok(Map map,Model model,ModelMap modelmap,User user) throws Exception {
map.put("ok1", user);
model.addAttribute("ok2",user);
modelmap.addAttribute("ok3", user);
return "show";
}
2、
早年往後傳:
(1)
@RequestMapping(value={"ant/{username}/topic/{topic}"},method={RequestMethod.GET})
public ModelAndView ant(
@PathVariable(value="username") String username,
@PathVariable(value="topic") String topic
) throws Exception {
// TODO Auto-generated method stub
ModelAndView m=new ModelAndView();
System.out.println(username);
System.out.println(topic);
return m;
}
前端是這個模樣:
<a href="hello/ant/Tom/topic/Cat">ant</a>
與value={"ant/{username}/topic/{topic}"}逐個對應。
還可以以這類情勢:
@RequestMapping(value={"/regex/{number:\\d+}-{tel:\\d+}"})
public ModelAndView regex(
@PathVariable(value="number") int number,
@PathVariable(value="tel") String tel
) throws Exception {
// TODO Auto-generated method stub
ModelAndView m=new ModelAndView();
System.out.println(number);
System.out.println(tel);
return m;
}
前端是這個模樣:
<a href="hello/regex/100-111">regex(正則)</a>
(2)這是有鍵傳值:
@RequestMapping(value={"/ok1"})
public String ok1(@RequestParam(value="username") String username) throws Exception {
System.out.println(username);
return "show";
}
前端是這個模樣:
<a href="user/ok1?username=Tom">有鍵傳值</a>
這是無鍵傳值:
@RequestMapping(value={"/ok2"})
public String ok2(@RequestParam String password,@RequestParam String username) throws Exception {
System.out.println(username);
System.out.println(password);
return "show";
}
前端是這個模樣:
<a href="user/ok2?username=Tom&password=111">無鍵傳值</a>
成心思的是它可以精確的對應好兩個值。
以上這篇SpringMVC的簡略傳值(完成代碼)就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。