spring mvc獲取路徑參數的幾種方式

SpringMVC是一個基於DispatcherServlet的MVC框架,每個請求最早訪問的都是DispatcherServlet,DispatcherServlet負責轉發每個Request請求給相應的Handler,Handler處理之後再返回相應的視圖(View)和模型(Model),返回的視圖和模型均可以不指定,便可以只返回Model或只返回View或都不返回。在使用註解的SpringMVC中,處理器Handler是基於@Controller和@RequestMapping這兩個註解的,@Controller聲明一個處理器類,@RequestMapping聲明對應請求的映射關係,這樣就能夠提供一個很是靈活的匹配和處理方式。java

 

DispatcherServlet是繼承自HttpServlet的,既然SpringMVC是基於DispatcherServlet的,那麼咱們先來配置一下DispatcherServlet,好讓它可以管理咱們但願它管理的內容。HttpServlet是在web.xml文件中聲明的。web


1、從視圖向controller傳遞值,  controller <--- 視圖spring

一、經過@PathVariabl註解獲取路徑中傳遞參數 
app

1     @RequestMapping(value = "/{id}/{str}") 
2     public ModelAndView helloWorld(@PathVariable String id, 
3             @PathVariable String str) { 
4         System.out.println(id); 
5         System.out.println(str); 
6         return new ModelAndView("/helloWorld"); 
7     }

二、
 
1)簡單類型,如int, String, 應在變量名前加@RequestParam註解,
例如:
框架

       @RequestMapping("hello3")
       public String hello3( @RequestParam("name" ) String name,
                               @RequestParam("hobby" ) String hobby){
            System. out.println("name=" +name);
            System. out.println("hobby=" +hobby);      
             return "hello" ;
      }


但這樣就要求輸入裏面必須有這兩個參數了,能夠用required=false來取消,例如:
@RequestParam(value="name",required=false) String name
但經測試也能夠徹底不寫這些註解,即方法的參數寫String name,效果與上面相同。
 
2)對象類型:

測試

       @RequestMapping("/hello4" )
       public String hello4(User user){
            System.out.println("user.getName()=" +user.getName());
            System.out.println("user.getHobby()=" +user.getHobby());
            return "hello";
      }


Spring MVC會按:
     「HTTP請求參數名=  命令/表單對象的屬性名」
    的規則自動綁定請求數據,支持「級聯屬性名」,自動進行基本類型數據轉換。
此外,還能夠限定提交方法爲POST,即修改方法的@RequestMapping註解爲
@RequestMapping(value="/hello4",method=RequestMethod.POST)
 
最後,注意,若是這裏提交過來的字符出現亂碼,應該在web.xml里加入以下filter:
 

ui

<filter>
   <filter-name>encodingFilter</filter-name>
   <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
   <init-param>
      <param-name>encoding</param-name>
      <param-value>utf8</param-value>
   </init-param>
</filter>
 
<filter-mapping>
   <filter-name>encodingFilter</filter-name >
   <url-pattern>/*</url-pattern>
</filter-mapping>



返回數據到頁面幾種方式:      url

  1.     //返回頁面參數的第二種方式,在形參中放入一個Model  
        @RequestMapping(value = "/hello2.htm")  
        public String hello2(int id,Model model){  
            System.out.println("hello2 action:"+id);  
            model.addAttribute("name", "huangjie");  
            //這個只有值沒有鍵的狀況下,使用Object的類型做爲key,String-->string  
            model.addAttribute("ok");  
            return "hello";  
        }
  1.    //返回頁面參數的第一種方式,在形參中放入一個map  
        @RequestMapping(value = "/hello1.htm")  
        public String hello(int id,Map<String,Object> map){  
            System.out.println("hello1 action:"+id);  
            map.put("name", "huangjie");  
            return "hello";  
        }
相關文章
相關標籤/搜索