一、SpringMVC注解入门

1. 创建web项目
2. 在springmvc的配置文件中指定注解驱动,配置扫描器

  1. <!-- mvc的注解驱动 -->
  2. <mvc:annotation-driven />
  3. <!--只要定义了扫描器,注解驱动就不需要,扫描器已经有了注解驱动的功能 -->
  4. <context:component-scan base-package="org.study1.mvc.controller" />
  5. <!-- 前缀+ viewName +后缀 -->
  6. <bean
  7. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  8. <!-- WebContent(WebRoot)到某一指定的文件夹的路径 ,如下表示/WEB-INF/view/*.jsp -->
  9. <property name="prefix" value="/WEB-INF/view/"></property>
  10. <!-- 视图名称的后缀 -->
  11. <property name="suffix" value=".jsp"></property>
  12. </bean>

<context:component-scan/> 扫描指定的包中的类上的注解,常用的注解有:

@Controller 声明Action组件
@Service    声明Service组件    @Service("myMovieLister") 
@Repository 声明Dao组件
@Component   泛指组件, 当不好归类时. 
@RequestMapping("/menu")  请求映射
@Resource  用于注入,( j2ee提供的 ) 默认按名称装配,@Resource(name="beanName") 
@Autowired 用于注入,(srping提供的) 默认按类型装配 
@Transactional( rollbackFor={Exception.class}) 事务管理
@ResponseBody
@Scope("prototype")   设定bean的作用

3. @controller:标识当前类是控制层的一个具体的实现
4. @requestMapping:放在方法上面用来指定某个方法的路径,当它放在类上的时候相当于命名空间需要组合方法上的requestmapping来访问。

  1. @Controller // 用来标注当前类是springmvc的控制层的类
  2. @RequestMapping("/test") // RequestMapping表示 该控制器的唯一标识或者命名空间
  3. public class TestController {
  4. /**
  5. * 方法的返回值是ModelAndView中的
  6. */
  7. @RequestMapping("/hello.do") // 用来访问控制层的方法的注解
  8. public String hello() {
  9. System.out.println("springmvc annotation... ");
  10. return "jsp1/index";
  11. }
  12. //*****
  13. }

在本例中,项目部署名为mvc,tomcat url为 http://localhost,所以实际为:http://localhos/mvc

在本例中,因为有命名空间 /test,所以请求hello方法地址为:http://localhost/mvc/test/hello.do

输出:springmvc annotation...

二、注解形式的参数接收

1. HttpServletRequest可以直接定义在参数的列表,通过该请求可以传递参数

url:http://localhost/mvc/test/toPerson.do?name=zhangsan

  1. /**
  2. * HttpServletRequest可以直接定义在参数的列表,
  3. *
  4. */
  5. @RequestMapping("/toPerson.do")
  6. public String toPerson(HttpServletRequest request) {
  7. String result = request.getParameter("name");
  8. System.out.println(result);
  9. return "jsp1/index";
  10. }

可以从HttpServletRequest 取出“name”属性,然后进行操作!如上,可以取出 “name=zhangsan”

输出:zhangsan
2. 在参数列表上直接定义要接收的参数名称,只要参数名称能匹配的上就能接收所传过来的数据, 可以自动转换成参数列表里面的类型,注意的是值与类型之间是可以转换的

2.1传递多种不同类型的参数:

url:http://localhost/mvc/test/toPerson1.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

  1. /**
  2. * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分
  3. * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到 a
  4. *
  5. */
  6. @RequestMapping("/toPerson1.do")
  7. public String toPerson1(String name, Integer age, String address,
  8. Date birthday) {
  9. System.out.println(name + " " + age + " " + address + " " + birthday);
  10. return "jsp1/index";
  11. }
  12. /**
  13. * 注册时间类型的属性编辑器,将String转化为Date
  14. */
  15. @InitBinder
  16. public void initBinder(ServletRequestDataBinder binder) {
  17. binder.registerCustomEditor(Date.class, new CustomDateEditor(
  18. new SimpleDateFormat("yyyy-MM-dd"), true));
  19. }

输出:zhangsan 14 china Fri Feb 11 00:00:00 CST 2000

2.2传递数组:

url:http://localhost/mvc/test/toPerson2.do?name=tom&name=jack

  1. /**
  2. * 对数组的接收,定义为同名即可
  3. */
  4. @RequestMapping("/toPerson2.do")
  5. public String toPerson2(String[] name) {
  6. for (String result : name) {
  7. System.out.println(result);
  8. }
  9. return "jsp1/index";
  10. }

输出:tom jack

2.3传递自定义对象(可多个):

url:http://localhost/mvc/test/toPerson3.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

User 定义的属性有:name,age,并且有各自属性的对应的set方法以及toString方法

Person定义的属性有:name,age.address,birthday,并且有各自属性的对应的set方法以及toString方法

  1. /**
  2. *
  3. * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分
  4. * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到
  5. *
  6. */
  7. @RequestMapping("/toPerson3.do")
  8. public String toPerson3(Person person, User user) {
  9. System.out.println(person);
  10. System.out.println(user);
  11. return "jsp1/index";
  12. }

输出:

Person [name=zhangsan, age=14, address=china, birthday=Fri Feb 11 00:00:00 CST 2000]
User [name=zhangsan, age=14]

自动封装了对象,并且被分别注入进来!

三、注解形式的结果返回

1. 数据写到页面,方法的返回值采用ModelAndView, new ModelAndView("index", map);,相当于把结果数据放到response里面

url:http://localhost/mvc/test/toPerson41.do

url:http://localhost/mvc/test/toPerson42.do

url:http://localhost/mvc/test/toPerson43.do

url:http://localhost/mvc/test/toPerson44.do

  1. /**
  2. * HttpServletRequest可以直接定义在参数的列表,并且带回返回结果
  3. *
  4. */
  5. @RequestMapping("/toPerson41.do")
  6. public String toPerson41(HttpServletRequest request) throws Exception {
  7. request.setAttribute("p", newPesion());
  8. return "index";
  9. }
  10. /**
  11. *
  12. * 方法的返回值采用ModelAndView, new ModelAndView("index", map);
  13. * ,相当于把结果数据放到Request里面,不建议使用
  14. *
  15. */
  16. @RequestMapping("/toPerson42.do")
  17. public ModelAndView toPerson42() throws Exception {
  18. Map<String, Object> map = new HashMap<String, Object>();
  19. map.put("p", newPesion());
  20. return new ModelAndView("index", map);
  21. }
  22. /**
  23. *
  24. * 直接在方法的参数列表中来定义Map,这个Map即使ModelAndView里面的Map,
  25. * 由视图解析器统一处理,统一走ModelAndView的接口,也不建议使用
  26. */
  27. @RequestMapping("/toPerson43.do")
  28. public String toPerson43(Map<String, Object> map) throws Exception {
  29. map.put("p", newPesion());
  30. return "index";
  31. }
  32. /**
  33. *
  34. * 在参数列表中直接定义Model,model.addAttribute("p", person);
  35. * 把参数值放到request类里面去,建议使用
  36. *
  37. */
  38. @RequestMapping("/toPerson44.do")
  39. public String toPerson44(Model model) throws Exception {
  40. // 把参数值放到request类里面去
  41. model.addAttribute("p", newPesion());
  42. return "index";
  43. }
  44. /**
  45. * 为了测试,创建一个Persion对象
  46. *
  47. */
  48. public Person newPesion(){
  49. Person person = new Person();
  50. person.setName("james");
  51. person.setAge(29);
  52. person.setAddress("maami");
  53. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  54. Date date = format.parse("1984-12-28");
  55. person.setBirthday(date);
  56. return person;
  57. }

以上四种方式均能达到相同的效果,但在参数列表中直接定义Model,model.addAttribute("p", person);把参数值放到request类里面去,建议使用

2. Ajax调用springmvc的方法:直接在参数的列表上定义PrintWriter,out.write(result);把结果写到页面,建议使用的

url:http://localhost/mvc/test/toAjax.do

  1. /**
  2. *
  3. * ajax的请求返回值类型应该是void,参数列表里直接定义HttpServletResponse,
  4. * 获得PrintWriter的类,最后可把结果写到页面 不建议使用
  5. */
  6. @RequestMapping("/ajax1.do")
  7. public void ajax1(String name, HttpServletResponse response) {
  8. String result = "hello " + name;
  9. try {
  10. response.getWriter().write(result);
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. /**
  16. *
  17. * 直接在参数的列表上定义PrintWriter,out.write(result);
  18. * 把结果写到页面,建议使用的
  19. *
  20. */
  21. @RequestMapping("/ajax2.do")
  22. public void ajax2(String name, PrintWriter out) {
  23. String result = "hello " + name;
  24. out.write(result);
  25. }
  26. /**
  27. * 转向ajax.jsp页面
  28. */
  29. @RequestMapping("/toAjax.do")
  30. public String toAjax() {
  31. return "ajax";
  32. }

ajax页面代码如下:

  1. <script type="text/javascript" src="js/jquery-1.6.2.js"></script>
  2. <script type="text/javascript">
  3. $(function(){
  4. $("#mybutton").click(function(){
  5. $.ajax({
  6. url:"test/ajax1.do",
  7. type:"post",
  8. dataType:"text",
  9. data:{
  10. name:"zhangsan"
  11. },
  12. success:function(responseText){
  13. alert(responseText);
  14. },
  15. error:function(){
  16. alert("system error");
  17. }
  18. });
  19. });
  20. });
  21. </script>
  22. </head>
  23. <body>
  24. <input id="mybutton" type="button" value="click">
  25. </body>

四、表单提交和重定向

1、表单提交:

请求方式的指定:@RequestMapping( method=RequestMethod.POST )可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误

表单jsp页面:

  1. <html>
  2. <head>
  3. <base href="<%=basePath%>">
  4. <title>SpringMVC Form</title>
  5. </head>
  6. <body>
  7. <form action="test/toPerson5.do" method="post">
  8. name:<input name="name" type="text"><br>
  9. age:<input name="age" type="text"><br>
  10. address:<input name="address" type="text"><br>
  11. birthday:<input name="birthday" type="text"><br>
  12. <input type="submit" value="submit"><br>
  13. </form>
  14. </body>
  15. </html>

对应方法为:

  1. /**
  2. * 转向form.jsp页面
  3. * @return
  4. */
  5. @RequestMapping("/toform.do")
  6. public String toForm() {
  7. return "form";
  8. }
  9. /**
  10. *
  11. * @RequestMapping( method=RequestMethod.POST)
  12. * 可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误 a
  13. *
  14. */
  15. @RequestMapping(value = "/toPerson5.do", method = RequestMethod.POST)
  16. public String toPerson5(Person person) {
  17. System.out.println(person);
  18. return "jsp1/index";
  19. }

url:http://localhost/mvc/test/toform.do  

2. 重定向:controller内部重定向,redirect:加上同一个controller中的requestMapping的值,controller之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值,redirect:后必须要加/,是从根目录开始
  1. /**
  2. *
  3. * controller内部重定向
  4. * redirect:加上同一个controller中的requestMapping的值
  5. *
  6. */
  7. @RequestMapping("/redirectToForm.do")
  8. public String redirectToForm() {
  9. return "redirect:toform.do";
  10. }
  11. /**
  12. *
  13. * controller之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值,
  14. * redirect:后必须要加/,是从根目录开始
  15. */
  16. @RequestMapping("/redirectToForm1.do")
  17. public String redirectToForm1() {
  18. //test1表示另一个Controller的命名空间
  19. return "redirect:/test1/toForm.do";
  20. }

参考资料: http://elf8848.iteye.com/blog/875830/

springmvc入门基础之注解和参数传递的更多相关文章

  1. SpringMVC入门(基于注解方式实现)

    ---------------------siwuxie095                             SpringMVC 入门(基于注解方式实现)         SpringMVC ...

  2. Springmvc入门基础(五) ---controller层注解及返回类型解说

    0.@Controller注解 作用:通过@Controller注解,注明该类为controller类,即控制器类,需要被spring扫描,然后注入到IOC容器中,作为Spring的Bean来管理,这 ...

  3. SpringMVC入门和常用注解

    SpringMVC的基本概念 关于 三层架构和 和 MVC 三层架构 我们的开发架构一般都是基于两种形式,一种是 C/S 架构,也就是客户端/服务器,另一种是 B/S 架构,也就 是浏览器服务器.在 ...

  4. Springmvc入门基础(四) ---参数绑定

    1.默认支持的参数类型 处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值. 除了ModelAndView以外,还可以使用Model来向页面传递数据, Model是一个接口,在参数里直接声明 ...

  5. Springmvc入门基础(一) ---基于idea创建demo项目

    Springmvc是什么 Springmvc和Struts2都属于表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来,如下图: Springmvc处理流程 ---- ...

  6. <SpringMvc>入门二 常用注解

    1.@RequestMapping @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME ...

  7. Springmvc入门基础(三) ---与mybatis框架整合

    1.创建数据库springmvc及表items,且插入一些数据 DROP TABLE IF EXISTS `items`; CREATE TABLE `items` ( `id` int(11) NO ...

  8. Springmvc入门基础(二) ---架构详解

    1.框架结构图 架构流程文字说明 用户发送请求至前端控制器DispatcherServlet DispatcherServlet收到请求调用HandlerMapping处理器映射器. 处理器映射器根据 ...

  9. Springmvc入门基础(六) ---拦截器应用demo

    1.拦截器定义 Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理. 2.拦截器demo demo需求: 拦截用户请求,判断用 ...

随机推荐

  1. BI 项目管理之生命周期跟踪和任务区域

    DW/BI 系统是复杂的实体,构建这种系统的方法必须有助于简化复杂性.13 个方框显示了构建成功的数据仓库的主要任务区域,以及这些任务之间的主要依赖关系.       在生命周期这一级可以进行多方观察 ...

  2. 使用git进行团队合作开发

    1.git 和 svn 的差异 git和svn 最大的差异在于git是分布式的管理方式而svn是集中式的管理方式.如果不习惯用代码管理工具,可能比较难理解分布式管理和集中式管理的概念.下面介绍两种工具 ...

  3. 团队作业-第一周-NABCD竞争性需求分析

      1.  Need 需求 随着科技信息的发展,传统的课堂点名亟待步入信息处理的轨道,移动校园课堂点名软件恰好的切入了这个需求点,市场中词类软件也为数不多,因此需求也是比较强烈. 2. Approac ...

  4. android 入门-引用库项目

    http://blog.csdn.net/arui319/article/details/6831164

  5. Windows Phone中获取UserAgent

    进入WP8时代后,通过DeviceExtendedProperties获取到的DeviceName不再是手机型号了,这对于需要获得手机型号做一些事情的应用(如新浪微博的小尾巴)来说,影响是比较大的. ...

  6. (C#基础) byte[] 之初始化, 赋值,转换。(转)

    byte[] 之初始化赋值 用for loop 赋值当然是最基本的方法,不过在C#里面还有其他的便捷方法. 1. 创建一个长度为10的byte数组,并且其中每个byte的值为0. byte[] myB ...

  7. 实现Web验证码图片-原理

    实现验证码的基础 GDI+ graphics device interface plus的缩写,即图形设备接口.GDI+为开发者提供了一组实现与各种设备(具有图形化能力但不涉及图形细节的设备)进行交互 ...

  8. DSP using MATLAB 示例Example2.12

    代码: b = [1]; a = [1, -0.9]; n = [-5:50]; h = impz(b,a,n); set(gcf,'Color','white'); %subplot(2,1,1); ...

  9. CSS3-margin,padding,border

    margin  padding  border: 1.当属性值为0的时候,不需要在后面添加单位 2.当同时出现top margin以及bottom magin的时候,浏览器应用较大的哪一个 3.不能在 ...

  10. 从新注册 .DLL CMD 运行regsvr32 *.dll注册该DLL 或 regsvr32 /s *.DLL 求证

    从新注册 .DLL  CMD 运行regsvr32  *.dll注册该DLL  或 regsvr32 /s  *.DLL 求证