<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)

    最新隨筆

    搜索

    •  

    最新評(píng)論

    一、概述

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

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

    二、示例

    下面通過(guò)對(duì)SpringMVC注解的詳細(xì)介紹來(lái)看一下上述優(yōu)點(diǎn)。

    首先需要在應(yīng)用的dispatcher-servlet.xml 啟動(dòng)注解機(jī)制
    <context:annotation-config />
    <!-- 設(shè)置注解驅(qū)動(dòng) -->
    <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注解

    簡(jiǎn)單示例
    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";
        }
    }

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

    2、使用@RequestMapping注解處理請(qǐng)求映射

        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")
         * 在類層次指定了映射后,可以在方法層次再指定相對(duì)路徑
         
    */
        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") 請(qǐng)求包含myParam參數(shù)
         * @RequestMapping(value = "/something",params="myParam=myValue")請(qǐng)求包含myParam參數(shù),并且該參數(shù)值為myValue
         * @RequestMapping(value = "/something",params="!myParam") 請(qǐng)求不包含myParam參數(shù)
         
    */
        String[] params() 
    default {};

        
    /**
         * 指定HttpRequest中包含的頭部信息,使用方式如下:
         * @RequestMapping(value = "/something", headers="content-type")請(qǐng)求包含該頭部
         * @RequestMapping(value = "/something", headers="content-type=text/*")請(qǐng)求包含特定值的頭部
         * @RequestMapping(value = "/something", headers="!content-type")請(qǐng)求不包含該頭部
         
    */
        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,如果請(qǐng)求中有名為 accountId的參數(shù),則會(huì)進(jìn)行默認(rèn)綁定,不僅基本類型,javabean的屬性也可以默認(rèn)進(jìn)行綁定;
    如果需要明確綁定,使用@RequestParam。 一般建議進(jìn)行明確指定。

    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 綁定一個(gè)Cookie值,@CookieValue("loginId") 完整形式為 @CookieValue(value="loginId",required=true,defaultValue=null)
    3.4 @RequestBody 將httpRequest的body綁定到方法參數(shù)上
    3.5 @ModelAttribute 有兩種使用方式: 1)在方法級(jí)別,指定方法的返回值綁定到model中; 2)方法參數(shù)級(jí)別,指定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異步請(qǐng)求,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;
     }

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

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


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

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

        適用于一般頁(yè)面請(qǐng)求。可以使用velocity 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注解。 返回一個(gè)String類型,這個(gè)String是viewname, 如果是重定向,return "redirect:/index.htm".
    入?yún)⒖梢园琈odelMap或者M(jìn)odel,其實(shí)這兩者是一個(gè)東西,作用一樣。也可以采用index3式的傳統(tǒng)寫法,返回一個(gè)ModelAndView對(duì)象。

    6、數(shù)據(jù)驗(yàn)證

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

    7、異常處理

    @ExceptionHandler


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

    FeedBack:
    # re: 基于注解的SpringMVC 2014-08-10 11:23 zuidaima
    # re: 基于注解的SpringMVC 2015-03-09 13:50 zuidaima

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


    網(wǎng)站導(dǎo)航:
     
    主站蜘蛛池模板: 亚洲人成网站免费播放| 久久久久成人片免费观看蜜芽| 本免费AV无码专区一区| 国产精品亚洲成在人线| 免费观看的毛片大全| 粉色视频成年免费人15次| 国产1024精品视频专区免费| 亚洲经典在线中文字幕| 高清一区二区三区免费视频| 亚洲日本国产乱码va在线观看| 在线观看国产情趣免费视频| 亚洲色中文字幕在线播放| 亚洲欧洲日本在线| 希望影院高清免费观看视频| 天堂亚洲免费视频| 久久久久亚洲?V成人无码| 最近免费最新高清中文字幕韩国| 国产亚洲视频在线| 中文字幕亚洲精品| www国产亚洲精品久久久| 久久久久久精品免费免费自慰| 免费人成视频在线观看免费| 亚洲色图.com| 久久久久亚洲AV成人网| 成年女人免费视频播放77777| 免费无码作爱视频| 婷婷亚洲综合一区二区| 亚洲日韩涩涩成人午夜私人影院 | 午夜免费国产体验区免费的| 2022年亚洲午夜一区二区福利| 亚洲第一区精品观看| 国产日本一线在线观看免费| 天黑黑影院在线观看视频高清免费 | 国产精品免费视频一区| 无套内谢孕妇毛片免费看看| 亚洲免费黄色网址| 亚洲av综合avav中文| 亚洲伊人久久成综合人影院| 日韩在线天堂免费观看| 久久久久久国产a免费观看黄色大片| 9久热精品免费观看视频|