SpringMVC学习(五) @RequestMapping使用及Controller层方法返回值

1. @RequestMapping的使用

     用@RequestMapping注解可以定义不同的处理器映射的规则

     (1)URL路径映射(添加在方法上)

            @RequestMapping(value = " URL"),其中value=可以省略。 如@RequestMapping(value = " /WEB-INF/login.jsp")

             value是一个数组,可以将多个URL映射到同一个方法。如@RequestMapping(value = { "itemList", "itemListAll" })

     (2)添加在类上用于指定通用请求前缀

              在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头

             

 

                此时需要进入queryItemList()方法的请求url为:

                 http://127.0.0.1:8080/springmvc-web2/item/itemList.action

                 或者

                  http://127.0.0.1:8080/springmvc-web2/item/itemListAll.action

         (3)指定请求方法

                @RequestMapping(value = "URL", method = RequestMethod.GET):限定GET请求映射到该方法,用POST提交则报错

                @RequestMapping(value = "URL", method = RequestMethod.POST):限定POST请求映射到该方法,用GET提交则报错

                method也是一个数组,可以指定多种请求方式:

                @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST})   GET和POST提交都可以

2. Controller返回值

       (1) 返回ModelAndView

                 controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。

                 添加Model数据用addObject(key, value)方法

                 指定View用setViewName(String)方法

                

     (2)返回void         

              在Controller方法形参上可以定义request和response,使用request或response指定响应结果:
             a、使用request转发页面,如下:request.getRequestDispatcher("页面路径").forward(request, response);
                   request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);

              b、可以通过response页面重定向:response.sendRedirect("url")
                   response.sendRedirect("/springmvc-web2/itemEdit.action");

              c、可以通过response指定响应结果,例如响应json数据如下:
                   response.getWriter().print("{\"abc\":123}");

       (3)返回字符串

             a.  controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。 

                   

            b. Redirect重定向

               Contrller方法返回字符串可以重定向到一个url地址

               如:return "redirect:/itemEdit.action?itemId=" + item.getId();

            c. forward转发

               Controller方法执行后继续执行另一个Controller方法

               如: return "forward:/itemEdit.action";

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值