@Controller和@RequestMapping和@RequestParam注解理解和區別


    在SpringMVC 中,控制器Controller 負責處理由DispatcherServlet 分發的請求,它把用戶請求的數據經過業務處理層處理之后封裝成一個Model ,
然后再把該Model 返回給對應的View 進行展示。在SpringMVC 中提供了一個非常簡便的定義Controller 的方法,你無需繼承特定的類或實現特定的接口,
只需使用@Controller 標記一個類是Controller ,
然后使用@RequestMapping 和@RequestParam 等一些注解用以定義URL 請求和Controller 方法之間的映射,這樣的Controller 就能被外界訪問到

 @Controller 

   用於標記在一個類上,使用它標記的類就是一個SpringMVC Controller 類。需要在springmvc中進行配置,告訴Spring 該到哪里去找標記為@Controller 的Controller 控制器。

    < context:component-scan base-package = "com.host.app.web.controller" >
       < context:exclude-filter type = "annotation"
           expression = "org.springframework.stereotype.Service" />
    </ context:component-scan > 

@RequestMapping

  映射 Request 請求與處理器,可以定義在類上,也可以定義在方法上。如果定義在類上,訪問的就是相對路徑,相對於類而言。如果定義在方法上,相對於方法的映射而言

@Controller
@RequestMapping("/main")
public class MainController {
    
    @RequestMapping(value="index")
    public String index(HttpSession session) {
        session.invalidate();
        return "index";
    }

@RequestParam

當需要從request 中綁定的參數和方法的參數名不相同的時候,也需要在@RequestParam 中明確指出是要綁定哪個參數。在@RequestParam 中除了指定綁定哪個參數的屬性value 之外,還有一個屬性required ,它表示所指定的參數是否必須在request 屬性中存在,默認是true ,表示必須存在,當不存在時就會報錯。

   @RequestMapping ( "requestParam" )
   public String testRequestParam( @RequestParam(required=false) String name, @RequestParam ( "age" ) int age) {
       return "requestParam" ;
    } 

其他更多詳細的注解https://www.cnblogs.com/jpfss/p/8047628.html

 


免責聲明!

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



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