Spring MVC Web请求提交数据

Spring MVC Web请求提交数据到控制器有下面几种方法:  

  1.使用HttpServletRequest获取   

 2.使用@RequestParam注解   

 3.使用自动机制封装成Bean对象 

4.使用自动机制封装成Bean对象   定义user实体,属性名与<form>表单组件的name相同

 1.使用HttpServletRequest获取   

String 自动参数注入HttpServletRequest,优点直接,缺点是需要自己处理数据类型

public class TsetController {
	@Controller
	@RequestMapping("/demo")
	public class TestController {
		// 使用request接收参数
		@RequestMapping("/test1.do")
		public ModelAndView test1(HttpServletRequest request) {
			String userName = request.getParameter("uaserName");
			String password = request.getParameter("password");
			System.out.println(userName);
			System.out.println(password);
			return new ModelAndView("jsp/hello1");
		}

2.使用@RequestParam注解     

Spring会自动将表单参数注入到方法参数(名称一样),使用@RequestParam注解,映射不一样

优点参数类型转换,但可能出现类型转换异常

 2.使用方法参数接收参数
		// 后端参数名不同,强转
		@RequestMapping("/test2.do")
		public ModelAndView test2(String userName, @RequestParam("password") String pwd) {
			System.out.println(userName);
			System.out.println(pwd);
			return new ModelAndView("jsp/hello1");
		}

3.使用自动机制封装成Bean对象

定义user实体,属性名与<form>表单组件的name相同

4.使用自动机封装成实体参数实例

在Controller组件处理方法定义User类型参数

// 3.使用对象接收参数
		@RequestMapping("/test3.do")
		public ModelAndView test3(User user) {
			System.out.println(user.getUserName());
			System.out.println(user.getPassword());
			return new ModelAndView("jsp/hello1");

		}

猜你喜欢

转载自blog.csdn.net/abcdefghwelcome/article/details/82632642
今日推荐