1、使用ServletAPI进行接收 设置方法中参数为 HttpServletRequest HttpSession HttpServletRespone 当设置了 参数为以上几种时,springMVC会自动进行参数对象的赋值 ; 使用的方式上和servlet相同;
2、使用String类型进行接收 使用用户请求的参数名作为方法的参数名,springmvc会自动将对应的属性进行赋值; http://localhost:8848/login ?username=admin&password=123&code=123 public String login(String username , String password , String code ){
3、使用对象进行接收 http://localhost:8848/login ?username=admin&password=123&code=123 public String login(User user ){} class User{ private String username ; private String password ; private String code ; public void setxxx( xx ){ this.xx = xx } }
4、通过@RequestParam接收请求参数 使用位置 放在 方法参数之前,用来设置请求参数的名称的,以及此参数是否是必须的; public String login(@RequestParam(value="username" ,required = false) String name , String password , String code ){ }
5、通过@PathVariable接收URL中的请求参数
6、使用@ModelAttribure注解获取请求参数
重定向与转发
转发:请求转发,由request请求发出的,当一个请求过来之后,当前接收的类、文件不能做出相应的响 应而把此请求转发其他Servlet、jsp、html等 进行处理; 地址栏中内容不会发生变化,只有一次请求;( 只能转发本项目中的资源 )
重定向:由response响应做出的,当一个请求过来之后,当前接收的类、文件不能做出相应的响应而 是,重新发出了一个请求去访问其他Servlet、jsp、html等 进行处理; 地址栏会变化成新的请求路径; ( 不仅能重定向到当前项目中的资源,还能重新到网络中的其他资源 )
SpringMVC中的转发和重定向
当方法设置为String类型的返回值时,默认使用的转发处理;
@RequestMapping("/login")
public String login(){
return "success"; }
1、直接使用 return "success" 表示转发给 前缀+success+后缀 的页面 ;
2、使用 return "forward:success" 表示将请求转发给 success 路径 ,不再设置前后缀 如果想要转发给一个页面, 使用 return "forward:/WEB-INF/success.jsp";
3、重定向: 使用 return "redirect:success.jsp