Spring MVC Web请求提交数据

本文介绍了SpringMVC中四种常见的Web请求数据提交方法:通过HttpServletRequest获取参数、使用@RequestParam注解、利用自动机制封装为Bean对象及直接使用实体参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

		}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值