SpringMVC是一个基于DispatcherServlet的MVC框架,每个请求最早访问的都是DispatcherServlet,DispatcherServlet负责转发每个Request请求给相应的Handler,Handler处理之后再返回相应的视图(View)和模型(Model),返回的视图和模型均可以不指定,便可以只返回Model或只返回View或都不返回。在使用注解的SpringMVC中,处理器Handler是基于@Controller和@RequestMapping这两个注解的,@Controller声明一个处理器类,@RequestMapping声明对应请求的映射关系,这样就能够提供一个很是灵活的匹配和处理方式。java
DispatcherServlet是继承自HttpServlet的,既然SpringMVC是基于DispatcherServlet的,那么咱们先来配置一下DispatcherServlet,好让它可以管理咱们但愿它管理的内容。HttpServlet是在web.xml文件中声明的。web
1、从视图向controller传递值, controller <--- 视图spring
一、经过@PathVariabl注解获取路径中传递参数
app
1 @RequestMapping(value = "/{id}/{str}") 2 public ModelAndView helloWorld(@PathVariable String id, 3 @PathVariable String str) { 4 System.out.println(id); 5 System.out.println(str); 6 return new ModelAndView("/helloWorld"); 7 }
二、
1)简单类型,如int, String, 应在变量名前加@RequestParam注解,
例如:
框架
@RequestMapping("hello3") public String hello3( @RequestParam("name" ) String name, @RequestParam("hobby" ) String hobby){ System. out.println("name=" +name); System. out.println("hobby=" +hobby); return "hello" ; }
但这样就要求输入里面必须有这两个参数了,能够用required=false来取消,例如:
@RequestParam(value="name",required=false) String name
但经测试也能够彻底不写这些注解,即方法的参数写String name,效果与上面相同。
2)对象类型:
测试
@RequestMapping("/hello4" ) public String hello4(User user){ System.out.println("user.getName()=" +user.getName()); System.out.println("user.getHobby()=" +user.getHobby()); return "hello"; }
Spring MVC会按:
“HTTP请求参数名= 命令/表单对象的属性名”
的规则自动绑定请求数据,支持“级联属性名”,自动进行基本类型数据转换。
此外,还能够限定提交方法为POST,即修改方法的@RequestMapping注解为
@RequestMapping(value="/hello4",method=RequestMethod.POST)
最后,注意,若是这里提交过来的字符出现乱码,应该在web.xml里加入以下filter:
ui
<filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name > <url-pattern>/*</url-pattern> </filter-mapping>
返回数据到页面几种方式: url
//返回页面参数的第二种方式,在形参中放入一个Model @RequestMapping(value = "/hello2.htm") public String hello2(int id,Model model){ System.out.println("hello2 action:"+id); model.addAttribute("name", "huangjie"); //这个只有值没有键的状况下,使用Object的类型做为key,String-->string model.addAttribute("ok"); return "hello"; }
//返回页面参数的第一种方式,在形参中放入一个map @RequestMapping(value = "/hello1.htm") public String hello(int id,Map<String,Object> map){ System.out.println("hello1 action:"+id); map.put("name", "huangjie"); return "hello"; }