• springmvc常见注解模式


      

      1 常用注解元素
      2 @Controller
      3          标注在Bean的类定义处
      4 @RequestMapping
      5 真正让Bean具备 Spring MVC Controller 功能的是 @RequestMapping 这个注解
      6 @RequestMapping 可以标注在类定义处,将 Controller 和特定请求关联起来;
      7 还可以标注在方法签名处,以便进一步对请求进行分流
      8  
      9    配套的属性有:
     10    value 需要跳转的地址
     11    method 基于RestFul的跳转参数,有RequestMethod.get  post  put  delete等
     12    params 符合某个参数的时候才调用该方法
     13    Headers 符合头信息的时候才调用
     14  
     15 @SessionAttributes
     16          将结果放入session内
     17 @ModelAttribute
     18 存储在响应内容ModelMap或者ModelAndView进行保存值传到前台,当如果你需要保存值比较少
     19 的时候可以采用这种方式进行保存值并且保存到前台显示
     20  
     21 在默认情况下,ModelMap 中的属性作用域是 request 级别,相当于HttpServletRequest中的request.setAttribute() 一样, 在 JSP 视图页面中通过 request.getAttribute(“attribute name”) 或者通过
     22 ${ attribute name } EL 表达式访问模型对象中的 属性对象
     23  
     24 如果希望在ModelMap 的作用域范围为 session,可以有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现 如:
     25  
     26 @Controller
     27 @RequestMapping("/login.do")
     28 @SessionAttributes("currUser")   
     29 public class BbtForumController {。。。。。}
     30  
     31  
     32 @ResponseBody
     33          标注后  返回String对象的结果为response内容体,不标注的话  作为dispatcher url使用
     34  
     35 @PathVariable
     36    允许将请求路径的制定内容当做求情的参数使用
     37 返回类型
     38 请求处理方法入参的可选类型                                                   说明
     39 void                                       此时逻辑视图名由请求处理方法对应的 URL 确定,如以下的方法:
     40 @RequestMapping("/welcome.do")
     41 public void welcomeHandler() {
     42 }
     43 对应的逻辑视图名为“welcome”
     44  
     45 String                                    此时逻辑视图名为返回的字符,如以下的方法:
     46 @RequestMapping(method = RequestMethod.GET)
     47 public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
     48      Owner owner = this.clinic.loadOwner(ownerId);
     49      model.addAttribute(owner);
     50      return "ownerForm";
     51 }
     52                                               对应的逻辑视图名为“ownerForm”
     53  
     54 ModelMap                            和返回类型为 void 一样,逻辑视图名取决于对应请求的 URL,
     55 如下面的例子:
     56 @RequestMapping("/vets.do")
     57 public ModelMap vetsHandler() {
     58      return new ModelMap(this.clinic.getVets());
     59 }
     60  
     61 对应的逻辑视图名为“vets”,返回的 ModelMap 将被作为请求对应的模型对象,
     62 可以在 JSP 视图页面中访问到。
     63 ModelAndView                  
     64 返回方式
     65 1 使用无返回方法跳转,如果使用返回方法进行跳转的话,则会通过视图解析器进行以
     66 prefix(前缀)+方法名+suffix(后缀)组成的页面文件名称.
     67  
     68 2 使用一个返回的字符串方法作为跳转,使用字符串跳转的话好处就是在return的时候可
     69 以自己指定返回的名字,JSP组成是prefix(前缀)+返回的字符串+suffix(后缀)
     70  
     71 3 返回一个ModelAndView类型,使用setViewName方法则可以跳转到指定的页面.
     72  
     73 路径匹配形式
     74          1、单一Controller   对应 单一的请求路径
     75                     
     76 2、单一Controller   对应多个请求路径
     77  
     78 3、单一Controller  对应多个请求路径,且路径内可以含有参数的形式
     79 Demo code and UseCase
     80 @Controller
     81 @RequestMapping("/login.do")
     82 public class SinglePathWithController {}
     83  
     84 @Controller
     85 @SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})
     86 public class AdapterMultiPathController {}
     87  
     88 @Controller
     89 @RequestMapping(value = "/rest")
     90 public class RestWithController {}
     91 无返回
     92 //无返回值  无参数返回的是根据 prefix前缀+@RequestMapping value +suffix
     93 后缀组成
     94       @RequestMapping("/springmvc/common")
     95       public voidnovoid(HttpServletRequest request) {
     96          request.setAttribute("message", "novoid方法被调用");
     97       }
     98 
     99 
    100 返回字符串
    101 1、  作为视图路径方式
    102  
    103 //根据路径直接匹配
    104 @RequestMapping("/springmvc/multiReqPath1.do")
    105     public String multiReqPath1(HttpServletRequest request){
    106        request.setAttribute("message", "multiReqPath1方法被调用");
    107        return "springmvc/common";
    108     }
    109  
    110     @RequestMapping("/springmvc/multiReqPath2.do")
    111     public String multiReqPath2(HttpServletRequest request){
    112        request.setAttribute("message", "multiReqPath2方法被调用");
    113        return "/springmvc/common";
    114     }
    115  
    116 //根据参数匹配
    117     @RequestMapping(params = "m=method1",method = RequestMethod.GET)
    118     public String method1(){
    119        return "login/success";
    120 }
    121  
    122 //有参数  参数名和请求url内的变量名一致
    123     @RequestMapping(params = "m=method2")
    124     public String method2(String name,String pwd){
    125        return name;
    126 }
    127 //有参数 参数名和请求url内的变量名不一致
    128     @RequestMapping(params = "m=method3",method = RequestMethod.GET)
    129     public String method3(@RequestParam("loginName")String name,@RequestParam("loginPwd")String pwd,HttpServletRequest request){
    130        request.setAttribute("message",(name + " " + pwd));
    131        return "login/"+name;
    132     }
    133 
    134  
    135 2、  作为Response内容方式
    136 //无参数
    137     @ResponseBody
    138     @RequestMapping(params = "m=method4")
    139     public String method4(){
    140        return "hello,guys";
    141 }
    142  
    143 //处理方法入参如何绑定 URL 参数
    144     @ResponseBody
    145     @RequestMapping(params = "m=method5",method = RequestMethod.GET)
    146     public String method5(String name,String pwd,int delay){
    147        return "name:"+name+","+"pwd:"+pwd+","+"delay:"+delay;
    148 }
    149  
    150 @ResponseBody
    151     @RequestMapping(params = "m=method6",method = RequestMethod.GET)
    152     public String method6(@RequestParam("userName")String name,DnTest test){
    153        return "DnTest:"+test.toString();
    154     }
    155  
    156 URL 参数: userName参数将绑定到name上  其他与DnTest类内属性名称一致的参数将绑定到test的对应的属性上,如果参数不全  也不会报错
    157 返回ModelAndView
    158 @RequestMapping("/springmvc/modelAndView")
    159     public ModelAndView modelAndView(){
    160        ModelAndView mav = new ModelAndView();
    161        mav.setViewName("/springmvc/common");
    162        mav.addObject("message", "modelAndView 方法被调用");
    163        return mav;
    164     }
    165 返回ModelMap
    166     @RequestMapping("/springmvc/modelMap")
    167     public ModelMap modelMap(ModelMap modMap){
    168        List<String> names = new ArrayList<String>();
    169        names.add("Rick");
    170        names.add("Austin");
    171         modMap.put("names", names);
    172        
    173         modMap.put("message", "hello guys");
    174         modMap.put("comment", "hello guys");
    175        
    176         return modMap;
    177     }
    178 返回ModelMap
    179 @RequestMapping("/springmvc/modelMap")
    180     public ModelMap modelAndView(ModelMap modMap){
    181        List<String> names = new ArrayList<String>();
    182        names.add("Rick");
    183        names.add("Austin");
    184       
    185         modMap.put("hello", "hello guys");
    186         modMap.put("names", names);
    187         return modMap;
    188     }
    189 @SessionAttribute & ModMap
    190 //注解方式
    191 @Controller
    192 @SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})
    193 public class AdapterMultiPathController {}
    194  
    195 //方法体
    196 @RequestMapping("/springmvc/modelMap2")
    197     public ModelMap modelMapWithSession(ModelMap modMap,HttpServletRequest request){
    198        List<String> names = new ArrayList<String>();
    199        names.add("Rick");
    200        names.add("Austin");
    201        modMap.put("names",names);
    202       
    203         modMap.put("message", "hello guys");
    204         modMap.put("comment", "hello guys");
    205        
    206         UserBean user = new UserBean();
    207         user.setName("Rick");
    208         user.setMobile("18938900256");
    209         user.setTelephone(request.getParameter("userPhone"));
    210         user.setNumber(request.getParameter("userNumber"));
    211         modMap.put("currentUser", user);
    212        
    213         return modMap;
    214     }  
    215 //初次请求
    216 spring mvc & reverse ajax
    217 @ResponseBody
    218     @RequestMapping(params = "m=method7",method = RequestMethod.GET)
    219     public String method7(String name,String pwd,int delay,HttpServletRequest req){
    220        req.startAsync();
    221       
    222        Date startTime = new Date();
    223        try {
    224            Thread.currentThread().sleep(delay);
    225        } catch (InterruptedException e) {
    226            e.printStackTrace();
    227        }
    228        Date entTime = new Date();
    229       
    230        return "name:"+name+","+"pwd:"+pwd+","+"delay:"+delay+",startTime:"+
    231               DateUtils.formatDate(startTime, "yyyy-MM-dd HH:mm:ss:SSS")+",endTime:"+
    232               DateUtils.formatDate(entTime, "yyyy-MM-dd HH:mm:ss:SSS");
    233     }
    234  
    235 RestFull
    236 @Controller
    237 @RequestMapping(value = "/rest")
    238 public class RestWithController {}
    239  
    240 @ResponseBody
    241     @RequestMapping(value = "/{msg}", method = RequestMethod.GET)
    242     public String restString(@PathVariable String msg) {
    243        return msg;
    244     }
    245  
    246     @ResponseBody
    247     @RequestMapping(value = "/{path}/{value}", method = RequestMethod.GET)
    248     public String restXml(@PathVariable String path,@PathVariable String value) {
    249        return "path:"+path+",value:"+value;
    250     }
    251     @ResponseBody
    252     @RequestMapping(value = "/xml/{filename}", method = RequestMethod.GET)
    253     public String restFile(@PathVariable String filename) {
    254        if (filename!=null) {
    255            ProjectInits init = ProjectInits.getInstance();
    256            String dir = init.get("resource.dir", "C:/Projects/VoyagerWeb/resources");
    257            FileUtility fUtil = new FileUtility();
    258            String content = fUtil.readFile(dir+"/"+filename+".xml");
    259            return content;
    260        }
    261        else
    262            return "Invalid xml file name ["+filename+"]";
    263     }
    264  
    265  
    266 验证 是否支持Overload
    267 方式一
    268 //验证 是否支持Overload
    269     @ResponseBody
    270     @RequestMapping(value = "/validate/overload1", method = RequestMethod.GET)
    271     public String overloadMethod(String name){
    272        return name;
    273     }
    274     @ResponseBody
    275     @RequestMapping(value = "/validate/overload2", method = RequestMethod.GET)
    276     public String overloadMethod(String name,DnTest test){
    277        return "DnTest:"+test.toString();
    278     }
    279  
    280 方式二
    281 /验证 是否支持Overload
    282         @ResponseBody
    283          @RequestMapping(params = "m=method11")
    284        public String method11(String name){
    285            return name;
    286        }
    287        
    288         @ResponseBody
    289          @RequestMapping(params = "m=method11")
    290        public String method11(int age,DnTest test){
    291            return "DnTest:"+test.toString();
    292        }
    ---- 动动手指关注我!或许下次你又能在我这里找到你需要的答案!ZZZZW与你一起学习,一起进步!
  • 相关阅读:
    html总结:背景图片拉伸
    html总结:表格中的文字居中
    html总结:float实现span和input输入框同行
    servlet总结:Servlet基础
    js总结:JavaScript入门
    河北科技创新平台年报系统涉众分析
    确定业务问题的范围-上下文的范围模型
    问题账户需求分析
    Struts2------OGNL表达式
    Struts入门
  • 原文地址:https://www.cnblogs.com/zzzzw/p/4849754.html
Copyright © 2020-2023  润新知