Spring MVC中@RequestMapping 6個基本用法小結

 

小結下spring mvc中的@RequestMapping的用法。 


1)最基本的,方法級別上應用,例如: 
   

Java代碼  收藏代碼

  1. @RequestMapping(value="/departments")  
  2. public String simplePattern(){  
  3.   
  4.   System.out.println("simplePattern method was called");  
  5.   return "someResult";  
  6.   
  7. }  


   則訪問http://localhost/xxxx/departments的時候,會調用 simplePattern方法了 

2) 參數綁定 
  

Java代碼  收藏代碼

  1. @RequestMapping(value="/departments")  
  2. public String findDepatment(  
  3.   @RequestParam("departmentId") String departmentId){  
  4.     
  5.     System.out.println("Find department with ID: " + departmentId);  
  6.     return "someResult";  
  7.   
  8. }  


   
  形如這樣的訪問形式: 

   /departments?departmentId=23就可以觸發訪問findDepatment方法了 

3 REST風格的參數 
  

Java代碼  收藏代碼

  1. @RequestMapping(value="/departments/{departmentId}")  
  2. public String findDepatment(@PathVariable String departmentId){  
  3.   
  4.   System.out.println("Find department with ID: " + departmentId);  
  5.   return "someResult";  
  6.   
  7. }  


  
  形如REST風格的地址訪問,比如: 
/departments/23,其中用(@PathVariable接收rest風格的參數 

4 REST風格的參數綁定形式之2 
   先看例子,這個有點象之前的: 

 

Java代碼  收藏代碼

  1. @RequestMapping(value="/departments/{departmentId}")  
  2. public String findDepatmentAlternative(  
  3.   @PathVariable("departmentId") String someDepartmentId){  
  4.   
  5.     System.out.println("Find department with ID: " + someDepartmentId);  
  6.     return "someResult";  
  7.   
  8. }  



   這個有點不同,就是接收形如/departments/23的URL訪問,把23作爲傳入的departmetnId,,但是在實際的方法findDepatmentAlternative中,使用 
@PathVariable("departmentId") String someDepartmentId,將其綁定爲 
someDepartmentId,所以這裏someDepartmentId爲23 

5 url中同時綁定多個id 

Java代碼  收藏代碼

  1. @RequestMapping(value="/departments/{departmentId}/employees/{employeeId}")  
  2. public String findEmployee(  
  3.   @PathVariable String departmentId,  
  4.   @PathVariable String employeeId){  
  5.   
  6.     System.out.println("Find employee with ID: " + employeeId +   
  7.       " from department: " + departmentId);  
  8.     return "someResult";  
  9.   
  10. }  

 


   這個其實也比較好理解了。 

6 支持正則表達式 
  

 

Java代碼  收藏代碼

  1. @RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}")  
  2. public String regularExpression(  
  3.   @PathVariable String textualPart,  
  4.   @PathVariable String numericPart){  
  5.   
  6.     System.out.println("Textual part: " + textualPart +   
  7.       ", numeric part: " + numericPart);  
  8.     return "someResult";  
  9. }  

 


   比如如下的URL:/sometext.123,則輸出: 

 

 

Textual part: sometext, numeric part: 123. 

 

 

轉載自:http://jackyrong.iteye.com/blog/1806326 

 

另外一篇介紹Spring mvc中@RequestMapping,可參考:http://blog.csdn.net/aini201/article/details/18734245 

 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

一個實際應用:

原文出處:http://www.cnblogs.com/leiOOlei/p/3658147.html

 

 

 

Spring3 MVC請求參數獲取的幾種方法

一、      通過@PathVariabl獲取路徑中的參數

複製代碼

    @RequestMapping(value="user/{id}/{name}",method=RequestMethod.GET)
    public String printMessage1(@PathVariable String id,@PathVariable String name, ModelMap model) {
        
        System.out.println(id);
        System.out.println(name);
        model.addAttribute("message", "111111");
        return "users";
    }

複製代碼

 

例如,訪問user/123/lei路徑時,執行以上方法,其中,參數id=123,name=lei

 

二、      @ModelAttribute獲取POST請求的FORM表單數據

JSP表單如下

<form method="post" action="hao.do">
    a: <input id="a" type="text"   name="a"/>
    b: <input id="b" type="text"   name="b"/>
    <input type="submit" value="Submit" />
 </form>

 

Java  Pojo如下

    public class Pojo{
        private String a;
        private int b;
    }

 

Java Controller如下

@RequestMapping(method = RequestMethod.POST) 
public String processSubmit(@ModelAttribute("pojo") Pojo pojo) { 
    
    return "helloWorld"; 
}

三、      直接用HttpServletRequest獲取

@RequestMapping(method = RequestMethod.GET) 
public String get(HttpServletRequest request, HttpServletResponse response) { 
   System.out.println(request.getParameter("a")); 
    return "helloWorld"; 
}

 

四、      用註解@RequestParam綁定請求參數

用註解@RequestParam綁定請求參數a到變量a

當請求參數a不存在時會有異常發生,可以通過設置屬性required=false解決,

例如: @RequestParam(value="a", required=false)

Controller如下

@RequestMapping(value = "/requestParam", method = RequestMethod.GET) 
public String setupForm(@RequestParam("a") String a, ModelMap model) { 
   System.out.println(a); 
return "helloWorld";
}

 

 

 

 

 

spring mvc controller間跳轉 重定向 傳參 :

http://zghbwjl.blog.163.com/blog/static/12033667220137795252845/

 

spring mvc controller間跳轉 重定向 傳參  

 

1. 需求背景

    需求:spring MVC框架controller間跳轉,需重定向。有幾種情況:不帶參數跳轉,帶參數拼接url形式跳轉,帶參數不拼接參數跳轉,頁面也能顯示。

本來以爲挺簡單的一件事情,並且個人認爲比較常用的一種方式,一百度全都有了,這些根本不是問題,但是一百度居然出乎我的意料,一堆都不是我想要的結果。無奈啊,自己寫一篇比較全都供以後大家一百度吧,哈哈哈。。。是這些寫的不是很全都人們給了我寫這篇博客的動力。

2. 解決辦法

    需求有了肯定是解決辦法了,一一解決,說明下spring的跳轉方式很多很多,我這裏只是說一些自我認爲好用的,常用的,spring分裝的一些類和方法。

    (1)我在後臺一個controller跳轉到另一個controller,爲什麼有這種需求呢,是這樣的。我有一個列表頁面,然後我會進行新增操作,新增在後臺完成之後我要跳轉到列表頁面,不需要傳遞參數,列表頁面默認查詢所有的。

        方式一:使用ModelAndView

        return new ModelAndView("redirect:/toList");

        這樣可以重定向到toList這個方法

        方式二:返回String

                    return "redirect:/ toList "; 

        其它方式:其它方式還有很多,這裏不再做介紹了,比如說response等等。這是不帶參數的重定向。

    (2)第二種情況,列表頁面有查詢條件,跳轉後我的查詢條件不能丟掉,這樣就需要帶參數的了,帶參數可以拼接url

        方式一:自己手動拼接url

                    new ModelAndView("redirect:/toList?param1="+value1+"&param2="+value2);

                    這樣有個弊端,就是傳中文可能會有亂碼問題。

        方式二:用RedirectAttributes,這個是發現的一個比較好用的一個類

                    這裏用它的addAttribute方法,這個實際上重定向過去以後你看url,是它自動給你拼了你的url。

                    使用方法:

                     attr.addAttribute("param", value);

                    return "redirect:/namespace/toController";

                    這樣在toController這個方法中就可以通過獲得參數的方式獲得這個參數,再傳遞到頁面。過去的url還是和方式一一樣的。

    (3)帶參數不拼接url頁面也能拿到值(重點是這個)

            一般我估計重定向到都想用這種方式:

            @RequestMapping("/save")

    public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)

                   throws Exception {

 

        String code =  service.save(form);

        if(code.equals("000")){

            attr.addFlashAttribute("name", form.getName());  

            attr.addFlashAttribute("success", "添加成功!");

            return "redirect:/index";

        }else{

            attr.addAttribute("projectName", form.getProjectName());  

            attr.addAttribute("enviroment", form.getEnviroment());  

            attr.addFlashAttribute("msg", "添加出錯!錯誤碼爲:"+rsp.getCode().getCode()+",錯誤爲:"+rsp.getCode().getName());

            return "redirect:/maintenance/toAddConfigCenter";

        }

    }

 

@RequestMapping("/index")

      

    public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)

                   throws Exception {

            return "redirect:/main/list";

    }

頁面取值不用我說了吧,直接用el表達式就能獲得到,這裏的原理是放到session中,session在跳到頁面後馬上移除對象。所以你刷新一下後這個值就會丟掉。

3. 總結

    最底層還是兩種跳轉,只是spring又進行了封裝而已,所以說跳轉的方式其實有很多很多種,你自己也可以封一個,也可以用最原始的response來,也沒有問題。好了,就到這兒。

    其實也沒有什麼,但是知道了這個就很簡單了,之前沒搞懂,現在搞懂了,和大家分享。有問題的給我留言。

 

 

相關視頻課程推薦《站長必修課:網站是怎樣做出來的?》https://edu.51cto.com/sd/3be5b

網站是怎樣做出來的?

 

 

 

 

發佈了20 篇原創文章 · 獲贊 8 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章