SpringMVC 常用注解


本文參考了博客,具體請見:http://www.cnblogs.com/leskang/p/5445698.html

 

Spring MVC的常用注解

1.@Controller
@Controller用於標記在一個類上,使用它標記的類就是一個SpringMVCController對象。分發處理器將會掃描使用了該注解的類的 方法,並檢測該方法是否使用了@RequestMapping 注解。@Controller只是定義了一個控制器類,而使用@RequestMapping注解的方法才是真正處理請求的處理器。單單使用 @Controller標記在一個類上還不能真正意義上的說它就是SpringMVC的一個控制器類,因為這個時候Spring還不認識它。那么要如何做 Spring才能認識它呢?這個時候就需要我們把這個控制器類交給Spring來管理。有兩種方式:
  (1)在SpringMVC 的配置文件中定義MyController 的bean 對象。
  (2)在SpringMVC 的配置文件中告訴Spring 該到哪里去找標記為@Controller 的Controller 控制器。
<!--方式一-->
<bean class="com.host.app.web.controller.MyController"/>
<!--方式二-->
< context:component-scan base-package = "com.host.app.web" />

 

2、@RequestMapping
RequestMapping注解有六個屬性,下面我們把它分成三類進行說明
(1)value,method
value:指定請求的實際地址,指定的地址可以是URI Template模式;
method:指定請求的method類型, GET、POST、PUT、DELETE等;
value的uri值可以為以下三類:普通的具體值;含有某變量的一類值;含有正則表達式的一類值;

@RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
    return new AppointmentForm();
}
@RequestMapping(value="/owners/{ownerId}", method={RequestMethod.GET , RequestMethod.DELETE })
public String findOwner(@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);  
  model.addAttribute("owner", owner);  
  return "displayOwner";
}
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
  public void handle(@PathVariable String version, @PathVariable String extension) {    
    // ...
  }
}

(2)consumes,produces
consumes:指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;
produces:指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回;

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {    
    // implementation omitted
}
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {    
    // implementation omitted
}

(3)params,headers
params:指定request中必須包含某些參數值時,才讓該方法處理。
headers:指定request中必須包含某些指定的header值,才能讓該方法處理請求。

@RequestMapping (value= "testParams" , params={ "param1=value1" , "param2" , "!param3" })
    public String testParams() {
       System. out .println( "test Params..........." );
       return "testParams" ;
    }

用@RequestMapping的params屬性指定了三個參數,這些參數都是針對請求參數而言的,它們分別表示參數param1的值必須等於 value1,參數param2必須存在,值無所謂,參數param3必須不存在,只有當請求/testParams.do並且滿足指定的三個參數條件的 時候才能訪問到該方法。所以當請求/testParams.do?param1=value1&param2=value2的時候能夠正確訪問到 該testParams方法,當請求/testParams.do?param1=value1&param2=value2& param3=value3的時候就不能夠正常的訪問到該方法

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
    // implementation omitted
  }
}

僅處理request的header中包含了指定“Refer”請求頭和對應值為“http://www.ifeng.com/”的請求;

 

3.@Resource和@Autowired
@Resource和@Autowired都是做bean的注入時使用,其實@Resource並不是Spring的注解,它的包是javax.annotation.Resource,需要導入,但是Spring支持該注解的注入。
(1)共同點
兩者都可以寫在字段和setter方法上。兩者如果都寫在字段上,那么就不需要再寫setter方法。
(2)不同點
@Autowired
@Autowired為Spring提供的注解,需要導入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入。

public class TestServiceImpl {
    // 下面兩種@Autowired只要使用一種即可
    @Autowired
    private UserDao userDao; // 用於字段上
    
    @Autowired
    public void setUserDao(UserDao userDao) { // 用於屬性的方法上
        this.userDao = userDao;
    }
}

@Autowired注解是按照類型(byType)裝配依賴對象,默認情況下它要求依賴對象必須存在,如果允許null值,可以設置它的 required屬性為false。如果我們想使用按照名稱(byName)來裝配,可以結合@Qualifier注解一起使用。如下:

public class TestServiceImpl {
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;
}

@Resource
@Resource默認按照ByName自動注入,由J2EE提供,需要導入包javax.annotation.Resource。@Resource 有兩個重要的屬性:name和type,而Spring將@Resource注解的name屬性解析為bean的名字,而type屬性則解析為bean的 類型。所以,如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不制定name也不 制定type屬性,這時將通過反射機制使用byName自動注入策略。

public class TestServiceImpl {
    // 下面兩種@Resource只要使用一種即可
    @Resource(name="userDao")
    private UserDao userDao; // 用於字段上
    
    @Resource(name="userDao")
    public void setUserDao(UserDao userDao) { // 用於屬性的setter方法上
        this.userDao = userDao;
    }
}

注:最好是將@Resource放在setter方法上,因為這樣更符合面向對象的思想,通過set、get去操作屬性,而不是直接去操作屬性。

 

4.@PathVariable
用於將請求URL中的模板變量映射到功能處理方法的參數上,即取出uri模板中的變量作為參數。

@Controller  
public class TestController {  
     @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)  
     public String getLogin(@PathVariable("userId") String userId,  
         @PathVariable("roleId") String roleId){  
         System.out.println("User Id : " + userId);  
         System.out.println("Role Id : " + roleId);  
         return "hello";  
     }  
     @RequestMapping(value="/product/{productId}",method = RequestMethod.GET)  
     public String getProduct(@PathVariable("productId") String productId){  
           System.out.println("Product Id : " + productId);  
           return "hello";  
     }  
     @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",  
           method = RequestMethod.GET)  
     public String getRegExp(@PathVariable("regexp1") String regexp1){  
           System.out.println("URI Part 1 : " + regexp1);  
           return "hello";  
     }  
}

 

5.@ResponseBody
作用: 該注解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式后,寫入到Response對象的body數據區。
使用時機:返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json、xml等)使用

@Controller
@RequestMapping ( "/test/{variable1}" )
public class MyController {

    @RequestMapping ( "/showView/{variable2}" )
    public ModelAndView showView( @PathVariable String variable1, @PathVariable ( "variable2" ) int variable2) {
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.setViewName( "viewName" );
       modelAndView.addObject( " 需要放到 model 中的屬性名稱 " , " 對應的屬性值,它是一個對象 " );
       return modelAndView;
    }
}

在上面的代碼中我們可以看到在標記variable1 為path 變量的時候我們使用的是@PathVariable ,而在標記variable2 的時候使用的是@PathVariable(“variable2”) 。這兩者有什么區別呢?第一種情況就默認去URI 模板中找跟參數名相同的變量,但是這種情況只有在使用debug 模式進行編譯的時候才可以,而第二種情況是明確規定使用的就是URI 模板中的variable2 變量。當不是使用debug 模式進行編譯,或者是所需要使用的變量名跟參數名不相同的時候,就要使用第二種方式明確指出使用的是URI 模板中的哪個變量。

 

6.@RestController
我們經常見到一些控制器實現了REST的API,只為服務於JSON,XML或其它自定義的類型內 容,@RestController用來創建REST類型的控制器,與@Controller類型。@RestController就是這樣一種類型,它 避免了你重復的寫@RequestMapping與@ResponseBody。

@RestController
public class FavRestfulController {

    @RequestMapping(value="/getUserName",method=RequestMethod.POST)
    public String getUserName(@RequestParam(value="name") String name){
        return name;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM