Spring MVC接收参数的方式

来源:互联网 发布:淘宝开店未认证 编辑:程序博客网 时间:2024/05/22 09:11

第一种接收参数的方式:

1、com.venustech.entity.User实体类属性:

Integer id  、String username、String password

2、controller控制层

package com.venustech.controller;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import com.venustech.entity.User;


@Controller
@RequestMapping("/user")
public class UserAction {
@RequestMapping("/test")
public ModelAndView test2(User user){
ModelAndView mov=new ModelAndView();
mov.setViewName("hello");
mov.addObject("name", user.getUsername());
mov.addObject("password", user.getPassword());
mov.addObject("msg", "保存成功");
return mov;
}

}

只需要调用http://ip:port/项目名/user/test?username="se7en"&password="123"就可以传递参数

如果你传入的参数为user.username="se7en"反而还收不到了呢!

总结:1、spring MVC接收类对象时只需要写入对应类中的属性的名称对应的get方法

2、这里面的mov中的setViewName是对应的跳转的页面

addObject中的string 可以在跳转的页面中用${string}来获取。

第二种接收参数:

@RequestMapping("/test")
public ModelAndView test2(
S
tring username,String password)

{
ModelAndView mov=new ModelAndView();
mov.setViewName("hello");
mov.addObject("name", name);
mov.addObject("password", password);
mov.addObject("msg", "保存成功");
return mov;
}

注意:如果是用mov传递一个user对象的话页面上的接收方式为${requestScope.user.username}如果只是单纯的

${user.username}是没有用的。

第三中接收参数

@RequestMapping("/save")
public String test1(@RequestParam(required=true,defaultValue="18")String username,@RequestParam(required=false)String password){
System.out.println("name:"+name+"password:"+password);
//return "hello";//    http://ip:端口/web应用/hello.jsp
return "redirect:/hello.jsp";
}


0 0