<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆 - 2  文章 - 2  trackbacks - 0
    <2025年5月>
    27282930123
    45678910
    11121314151617
    18192021222324
    25262728293031
    1234567

    留言簿

    隨筆檔案(1)

    文章分類(16)

    最新隨筆

    搜索

    •  

    最新評論

    一、概述

    SpringMVC在2.5版本后新增了注解功能,2.5版本以前的基本通過繼承Controller體系來開發(fā)業(yè)務(wù)控制器,2.5版本后Controller體系中
    BaseCommandController及其子類AbstractCommandController、AbstractFormController、AbstractWizardFormController、
    SimpleFormController、CancellableFormController等都已經(jīng)被標(biāo)示為@Deprecated,建議不再使用。

    相比傳統(tǒng)的繼承Controller體系中某些類的方式,SpringMVC的注解具有以下優(yōu)點:
    1、Controller不再需要繼承某個特定類,只是簡單的POJO。
    2、請求映射的配置非常方便靈活。
    3、參數(shù)綁定機制非常方便豐富。
    4、可以根據(jù)不同的http方法或者參數(shù),細(xì)粒度處理不同的http請求

    二、示例

    下面通過對SpringMVC注解的詳細(xì)介紹來看一下上述優(yōu)點。

    首先需要在應(yīng)用的dispatcher-servlet.xml 啟動注解機制
    <context:annotation-config />
    <!-- 設(shè)置注解驅(qū)動 -->
    <mvc:annotation-driven />
     
    <!-- 設(shè)置掃描的包 -->
    <context:component-scan base-package="com.demo.web.controller" />
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    注:雖然我們的Controller不需要再繼承任何類,但出于規(guī)范,我們?nèi)匀幻麨?**Controller.java,并統(tǒng)一放在com.demo.web.controller包中。

    1、@Controller注解

    簡單示例
    package com.demo.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    class IndexController {
        @RequestMapping(
    "/index")
        String index() {
            
    return "index";
        }
    }

    在一個POJO上面使用 @Controller 就可以標(biāo)注該POJO是一個Controller,就這么簡單。 @Controller注解定義在org.springframework.steretype包中。
    使用方式: @Controller 或者 @Controller("indexController)。 org.springframework.steretype包中還包含 @Componenet @Service @Respository
    三個注解。@Component是通用標(biāo)注,@Controller標(biāo)注web控制器,@Service標(biāo)注Servicec層的服務(wù),@Respository標(biāo)注DAO層的數(shù)據(jù)訪問。

    2、使用@RequestMapping注解處理請求映射

        SpringMVC中注解基本都包含在 org.springframework.web.bind.annotation 包中。先看一下@RequestMapping 注解的源碼。
    @Target( { ElementType.METHOD, ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Mapping
    public @interface RequestMapping {

        
    /**
         * 指定映射的URL.可以在類層次和方法層次使用。方式如下:
         * @RequestMapping("/add_")或 @RequestMapping(value = "/add")
         * 支持Ant風(fēng)格的URL映射,如 @RequestMapping("/myPath/*.htm")
         * 在類層次指定了映射后,可以在方法層次再指定相對路徑
         
    */
        String[] value() 
    default {};

        
    /**
         * 指定HttpRequest的方法, 如:GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE.
         * 使用舉例: @RequestMapping(value = "/add_activity", method = RequestMethod.GET)
         
    */
        RequestMethod[] method() 
    default {};

        
    /**
         * 指定HttpRequest中包含的參數(shù),使用方式如下:
         * @RequestMapping(value = "/something",params="myParam") 請求包含myParam參數(shù)
         * @RequestMapping(value = "/something",params="myParam=myValue")請求包含myParam參數(shù),并且該參數(shù)值為myValue
         * @RequestMapping(value = "/something",params="!myParam") 請求不包含myParam參數(shù)
         
    */
        String[] params() 
    default {};

        
    /**
         * 指定HttpRequest中包含的頭部信息,使用方式如下:
         * @RequestMapping(value = "/something", headers="content-type")請求包含該頭部
         * @RequestMapping(value = "/something", headers="content-type=text/*")請求包含特定值的頭部
         * @RequestMapping(value = "/something", headers="!content-type")請求不包含該頭部
         
    */
        String[] headers() 
    default {};

    }
    注:如果在類層次指定了映射,則方法層次上都將繼承類層次的映射

    3、獲取HttpRequest中得參數(shù)

    @RequestMapping("active")
    public @ResponseBody boolean active(Long accountId) {
        return accountService.activeAccount(accountId);
    }

    @RequestMapping("active")
    public @ResponseBody boolean active(Account account) {
        return accountService.activeAccount(accountId);
    }
    @RequestMapping(
    "inactive")
    public @ResponseBody boolean inactive(@RequestParam("accountId") Long accountId,
                @RequestHeader(
    "User-Agent") String userAgent,
                @CookieValue(
    "loginId") String loginId) {
        
    return accountService.inactiveAccount(accountId);
    }

    @RequestMapping(value 
    = "list/{pageNo}", method = RequestMethod.GET)
    public String list(@PathVariable int pageNo) {
         
    return "/account/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(@RequestBody String body) {
         return "/account/add";
    }


    active方法的入?yún)?accountId,如果請求中有名為 accountId的參數(shù),則會進行默認(rèn)綁定,不僅基本類型,javabean的屬性也可以默認(rèn)進行綁定;
    如果需要明確綁定,使用@RequestParam。 一般建議進行明確指定。

    3.1 @RequestParam 綁定httpRequest中參數(shù),@RequestParam("accountId") 完整形式為  @RequestParam(value="accountId",required=true,defaultValue=null)
    3.2 @RequestHeader 綁定httpRequest頭部信息,@RequestHeader("User-Agent") 完整形式為 @RequestHeader(value="User-Agebt",required=true, defaultValue=null)
    3.3 @CookieValue 綁定一個Cookie值,@CookieValue("loginId") 完整形式為 @CookieValue(value="loginId",required=true,defaultValue=null)
    3.4 @RequestBody 將httpRequest的body綁定到方法參數(shù)上
    3.5 @ModelAttribute 有兩種使用方式: 1)在方法級別,指定方法的返回值綁定到model中; 2)方法參數(shù)級別,指定model中的值綁定到方法的入?yún)⑸?示例如下:
     @ModelAttribute("countryList")
        
    public List<String> getCountries() {
            
    return new ArrayList<String>();
        }

    @RequestMapping(value 
    = "search", method = RequestMethod.POST)
        
    public String searchAccount(@ModelAttribute("accountId") Long accountId) {
            
    return "/search";
        }

    4、使用@ResponseBody 生成response

        適用于webservice的數(shù)據(jù)交換,或ajax異步請求,text、json或者xml格式的數(shù)據(jù)交換。
        例如訪問: http://localhost:8080/accounts/info.htm
     

    @RequestMapping(value = "info")
    public @ResponseBody Account getAccount() {
            Account a 
    = new Account();
            a.setId(
    123L);
            a.setName(
    "zhangsan");
            
    return a;
     }

    返回數(shù)據(jù)如下:
    {"name":"zhangsan","id":123}
    從上面例子可以看出,使用@ResponseBody后,返回的javabean默認(rèn)被序列化成json格式的數(shù)據(jù)并被寫入到response body中。

    @Request 和 @ReponseBody 使用了HttpMessageConverter機制。下面是HttpMessageConverter的繼承體系。


    常用的有如下幾個:
    StringHttpMessageConverter ---字符串
    MappingJacksonHttpMessageConverter ----json
    ByteArrayHttpMessageConverter ----字節(jié)數(shù)組
    MarshallingHttpMessageConverter -----xml

    5、使用模板技術(shù)生成response

        適用于一般頁面請求??梢允褂胿elocity freemarker等模板技術(shù),在dispatcher-servlet.xml中需要設(shè)置viewResolver。
       

    @RequestMapping("/index")
    public String index(ModelMap modelMap) {
            modelMap.put(
    "name""liucs");
            
    return "index";
    }

    @RequestMapping(
    "/index")
    public String index2(Model model) {
            model.addAttribute(
    "name","liucs");
            
    return "index";
    }

    @RequestMapping("/index")
    public ModelAndView index3() throws Exception {
          ModelAndView mav = new ModelAndView("index");
          mav.addObject("name", "liucs");
          return mav;
    }

    如上面代碼index1和index2所示,不使用@ResponseBody注解。 返回一個String類型,這個String是viewname, 如果是重定向,return "redirect:/index.htm".
    入?yún)⒖梢园琈odelMap或者Model,其實這兩者是一個東西,作用一樣。也可以采用index3式的傳統(tǒng)寫法,返回一個ModelAndView對象。

    6、數(shù)據(jù)驗證

    @InitBinder標(biāo)注
    @InitBinder
        
    public void myInitBinder(WebDataBinder binder){
          binder.setDisallowedFields(
    new String[]{"id"});
        }
    通過在方法中聲明一個BindingResult參數(shù)來啟動綁定和驗證
    @RequestMapping("update")
        
    public void update(@ModelAttribute("account") Account account,BindingResult bindResult) {
            
    if(bindResult.hasErrors()){
                
    //……
            }
        }
    需要注意以下限制:
    1、BindingResult參數(shù)必須跟在一個JavaBean參數(shù)后面
    2、錯誤會被自動的綁定到model中,便于渲染模板時使用
    3、不支持@RequestBody等類型的參數(shù)形式

    7、異常處理

    @ExceptionHandler


    posted on 2011-09-05 16:42 liucs 閱讀(8510) 評論(2)  編輯  收藏 所屬分類: Spring框架學(xué)習(xí)

    FeedBack:
    # re: 基于注解的SpringMVC 2014-08-10 11:23 zuidaima
    # re: 基于注解的SpringMVC 2015-03-09 13:50 zuidaima
    spring mvc demo教程源代碼下載:http://zuidaima.com/share/kspringmvc-p1-s1.htm  回復(fù)  更多評論
      

    只有注冊用戶登錄后才能發(fā)表評論。


    網(wǎng)站導(dǎo)航:
     
    主站蜘蛛池模板: 日本视频免费在线| 久久亚洲精品成人AV| 中文字幕a∨在线乱码免费看| 久久亚洲国产欧洲精品一| 四虎永久在线精品免费观看视频| 久久精品国产亚洲av瑜伽| 亚洲精品无码成人AAA片| 24小时免费直播在线观看| 一级做a爰性色毛片免费| 亚洲fuli在线观看| 亚洲精品国产自在久久 | 亚洲AV永久无码精品成人| 无人影院手机版在线观看免费| 污污污视频在线免费观看| 亚洲精品mv在线观看| 亚洲国产成人精品91久久久| 18观看免费永久视频| 精品熟女少妇aⅴ免费久久| 亚洲国产区男人本色在线观看| 国产亚洲大尺度无码无码专线 | 亚洲人成电影福利在线播放| 日本免费高清一本视频| 97在线视频免费| caoporm超免费公开视频| 亚洲女子高潮不断爆白浆| 亚洲国产国产综合一区首页| 免费国产真实迷j在线观看| jjizz全部免费看片| 大地影院MV在线观看视频免费| 精品一区二区三区免费毛片| 亚洲成在人线电影天堂色| 亚洲乱色熟女一区二区三区丝袜| 日本高清免费不卡视频| 无码国产精品一区二区免费虚拟VR | 亚洲国产精品自产在线播放| 亚洲第一成年免费网站| 亚洲精品视频免费在线观看| a级毛片在线免费看| aa级毛片毛片免费观看久| 激情吃奶吻胸免费视频xxxx| 亚洲人成网站色在线观看|