欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC四种controller接收参数的方式,三种controller向界面传递参数的方法

程序员文章站 2022-07-15 11:10:26
...

分享几种springmvc传递接收参数的方式

/**
	 * 接收参数1
	 * @param req
	 * @return
	 */
	@RequestMapping("/hello3")
	public String hello3(HttpServletRequest req) {
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		System.out.println("name:"+name);
		System.out.println("age:"+age);
		return "hello";
	}
	/**
	 * 接收参数2
	 * @param name
	 * @param age
	 * @return
	 */
	@RequestMapping("/hello4")
	public String hello4(String name,String age) {
		System.out.println("name:"+name);
		System.out.println("age:"+age);
		return "hello";
	}
	/**
	 * 接收参数3(自动装箱)
	 * 成员变量的名字要与页面的参数名字对应
	 * @param user
	 * @return
	 */
	@RequestMapping("/hello5")
	public String hello5(User user) {
		System.out.println("name:"+user.getName());
		System.out.println("age:"+user.getAge());
		return "hello";
	}
	/**
	 * 接收参数4
	 * 利用@RequestParam("页面参数的名字") 自定义变量名
	 * @param user
	 * @return
	 */
	@RequestMapping("/hello6")
	public String hello6(@RequestParam("name") String username,@RequestParam("age") String userage) {
		System.out.println("name:"+username);
		System.out.println("age:"+userage);
		return "hello";
	}
	/**
	 * 传递参数1
	 * 利用ModelAndView对象,通过addobject方法传参
	 * @param user
	 * @return
	 */
	@RequestMapping("/hello7")
	public ModelAndView hello7(ModelAndView mv) {
		mv.setViewName("hello");
		mv.addObject("username", "laowang");
		mv.addObject("age", "50");
		return mv;
	}
	/**
	 * 传递参数2
	 * 利用声明map传参
	 * @param user
	 * @return
	 */
	@RequestMapping("/hello8")
	public String hello8(Map<String,Object> map) {
		map.put("username", "陈");
		map.put("age", "26");
		return "hello";
	}
	/**
	 * 传递参数3
	 * 利用声明model对象addAttribute方法进行传参
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/hello9")
	public String hello9(Model model) {
		System.out.println("hello9");
		model.addAttribute("username", "二傻");
		model.addAttribute("age", "18");
		return "hello";
	}