【SpringMVC】【接收前台参数】【向前台传递参数】

接收前台参数

jsp中,传递的参数为:

  • username=Armo.
  • age=18.
    姓名:<input type="text" name="username" value="Armo">
    年龄:<input type="text" name="age" value="18">
方式1:用req手动提取
    @RequestMapping("/method1")
    public ModelAndView method1(HttpServletRequest req) throws Exception{
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        System.out.println(username+age);
        return null;
    }
方式2:形参自动注入
  • 形参名和input中的的name值相同
    @RequestMapping("/method2")
    public ModelAndView method2(String username,Integer age) throws Exception{
        System.out.println(username);
        System.out.println(age);
        return null;
    }
  • 形参名和input中的的name值不相同
    • 在形参前,加@RequestParam(“name值”).
    @RequestMapping("/method2")
    public ModelAndView method2(@RequestParam("username") String myName,Integer age) throws Exception{
        System.out.println(myName);
        System.out.println(age);
        return null;
    }
  • 将参数封装成对象
  • 对象属性和input的name值要相对应.
public class User {
    private String username;
    private Integer age;
    }

    @RequestMapping("/method3")
    public ModelAndView method3(User user) throws Exception{
        System.out.println(user);
        return null;
    }
方式3:地址栏传值

在超链接后加入参数: ……./参数

<a href="http://localhost:8080/SpringMVC/method4/10">删除</a>
    @RequestMapping("/method4/{id}")
    public ModelAndView method4(@PathVariable("id") Long id) throws Exception{
        System.out.println(id);
        return null;
    }

向前台传递参数

方式1:req传递参数
req.setAttribute("name", "Armo");
方式2:mv传递参数
    @RequestMapping("/method1")
    public ModelAndView method1(HttpServletRequest req,ModelAndView mv) throws Exception{
        mv.setViewName("forward:index.jsp");
        //使用${key}取值
        mv.addObject("name3", "Armo3");

        //默认key为对应类的小写(前者被后者覆盖)
        mv.addObject("Armo2");     //${string}
        mv.addObject(new Date());  //${date}
        mv.addObject(new User());  //${user}

        return mv;
    }
方式3:返回一个对象

根据视图解析器,会请求转发到
前缀+/method2+后缀. 并传递对象user

    @RequestMapping("/method2")
    public User method2() throws Exception{
        return new User();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值