接收前台参数
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();
}