SpringMVC的简单传值(实现代码)
之前学习SpringMVC时感觉他的传值很神奇:简便,快捷,高效。
今天写几个简单的传值与大家分享,希望能对大家有帮助。
一、
从后往前传:
(1)
@Controller
@RequestMapping(value={"/hello"})
publicclassHelloController{
@RequestMapping(value={"sub"})
publicModelAndViewsubmit(HttpServletRequestrequest)throwsException{
//TODOAuto-generatedmethodstub
ModelAndViewm=newModelAndView();
m.addObject("ok","hello");
m.setViewName("success");
returnm;
}
}
把想要传递的东西放在addObject(String,Object)里,值是Object类型,什么都可以放。
setViewName()是设置跳转到哪个页面(success.jsp页面)。
在success.jsp页面里用${requestScope}或${ok}即可取出。是不是非常简便快捷。
还可以以这种方式传:
@Controller
@RequestMapping(value={"/user"})
publicclassUserController{
@RequestMapping(value={"/get"})
publicModelAndViewuser(Useruser)throwsException{
ModelAndViewmv=newModelAndView();
mv.addObject("ok",user.getUsername()+"--"+user.getPassword());
mv.setViewName("success");
returnmv;
}
}
前端是一个简单的form表单:
<formaction="user/get"method="post"> <inputtype="text"name="username"id="username"> <inputtype="text"name="password"id="password"> <inputtype="submit"> </form>
(2)返回值也可以不是ModelAndView
@RequestMapping(value={"/map"})
publicStringok(Mapmap,Modelmodel,ModelMapmodelmap,Useruser)throwsException{
map.put("ok1",user);
model.addAttribute("ok2",user);
modelmap.addAttribute("ok3",user);
return"show";
}
二、
从前往后传:
(1)
@RequestMapping(value={"ant/{username}/topic/{topic}"},method={RequestMethod.GET})
publicModelAndViewant(
@PathVariable(value="username")Stringusername,
@PathVariable(value="topic")Stringtopic
)throwsException{
//TODOAuto-generatedmethodstub
ModelAndViewm=newModelAndView();
System.out.println(username);
System.out.println(topic);
returnm;
}
前端是这个样子:
<ahref="hello/ant/Tom/topic/Cat">ant</a>
与value={"ant/{username}/topic/{topic}"}一一对应。
还可以以这种形式:
@RequestMapping(value={"/regex/{number:\\d+}-{tel:\\d+}"})
publicModelAndViewregex(
@PathVariable(value="number")intnumber,
@PathVariable(value="tel")Stringtel
)throwsException{
//TODOAuto-generatedmethodstub
ModelAndViewm=newModelAndView();
System.out.println(number);
System.out.println(tel);
returnm;
}
前端是这个样子:
<ahref="hello/regex/100-111">regex(正则)</a>
(2)这是有键传值:
@RequestMapping(value={"/ok1"})
publicStringok1(@RequestParam(value="username")Stringusername)throwsException{
System.out.println(username);
return"show";
}
前端是这个样子:
<ahref="user/ok1?username=Tom">有键传值</a>
这是无键传值:
@RequestMapping(value={"/ok2"})
publicStringok2(@RequestParamStringpassword,@RequestParamStringusername)throwsException{
System.out.println(username);
System.out.println(password);
return"show";
}
前端是这个样子:
<ahref="user/ok2?username=Tom&password=111">无键传值</a>
有意思的是它可以准确的对应好两个值。
以上这篇SpringMVC的简单传值(实现代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。