SpringMVC的简单传值(实现代码)

网友投稿 282 2023-07-17


SpringMVC的简单传值(实现代码)

之前学习SpringMVC时感觉他的传值很神奇:简便,快捷,高效。

今天写几个简单的传值与大家分享,希望能对大家有帮助。

一、

从后往前传:

(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}即可取出。是不是非http://常简便快捷。

还可以以这种方式传:

@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表单:

(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";

}

二、

从前往后传:

(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;

}

前端是这个样子:

ant

与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;

}

前端是这个样子:

regex(正则)

(2)这是有键传值:

@RequestMapping(value={"/ok1"})

public String ok1(@RequestParam(value="username") String username) throws Exception {

System.out.println(username);

return "show";

}

前端是这个样子:

有键传值

这是无键传值:

@RequestMapping(value={"/ok2"})

public String ok2(@RequestParam String password,@RequestParam String username) throws Exception {

System.out.println(username);

System.out.println(password);

return "show";

}

前端是这个样子:

无键传值

有意思的是它可以准确的对应好两个值。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:常用的api在线测试工具有哪些,几款可尝试的接口测试工具或接口测试平台
下一篇:一款用于检测系统完整性、api漏洞的api检测系统
相关文章

 发表评论

暂时没有评论,来抢沙发吧~