springmvc常用註解以及參數傳遞

轉載地址:http://alog2012.iteye.com/blog/2040214

一、SpringMVC註解入門

1. 創建web項目
2. 在springmvc的配置文件中指定註解驅動,配置掃描器

Xml代碼  收藏代碼
  1. <!-- mvc的註解驅動 -->  
  2. <mvc:annotation-driven />  
  3.   
  4. <!--只要定義了掃描器,註解驅動就不需要,掃描器已經有了註解驅動的功能 -->  
  5. <context:component-scan base-package="org.study1.mvc.controller" />  
  6.   
  7. <!-- 前綴+ viewName +後綴 -->  
  8. <bean  
  9.     class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  10.     <!-- WebContent(WebRoot)到某一指定的文件夾的路徑 ,如下表示/WEB-INF/view/*.jsp -->  
  11.     <property name="prefix" value="/WEB-INF/view/"></property>  
  12.     <!-- 視圖名稱的後綴 -->  
  13.     <property name="suffix" value=".jsp"></property>  
  14. </bean>  

<context:component-scan/> 掃描指定的包中的類上的註解,常用的註解有:

@Controller 聲明Action組件
@Service    聲明Service組件    @Service("myMovieLister") 
@Repository 聲明Dao組件
@Component   泛指組件, 當不好歸類時. 
@RequestMapping("/menu")  請求映射
@Resource  用於注入,( j2ee提供的 ) 默認按名稱裝配,@Resource(name="beanName") 
@Autowired 用於注入,(srping提供的) 默認按類型裝配 
@Transactional( rollbackFor={Exception.class}) 事務管理
@ResponseBody
@Scope("prototype")   設定bean的作用

3. @controller:標識當前類是控制層的一個具體的實現
4. @requestMapping:放在方法上面用來指定某個方法的路徑,當它放在類上的時候相當於命名空間需要組合方法上的requestmapping來訪問。

Java代碼  收藏代碼
  1. @Controller // 用來標註當前類是springmvc的控制層的類  
  2. @RequestMapping("/test"// RequestMapping表示 該控制器的唯一標識或者命名空間  
  3. public class TestController {  
  4.   
  5.     /** 
  6.      * 方法的返回值是ModelAndView中的 
  7.      */  
  8.     @RequestMapping("/hello.do"// 用來訪問控制層的方法的註解  
  9.     public String hello() {  
  10.         System.out.println("springmvc annotation... ");  
  11.         return "jsp1/index";  
  12.     }  
  13.   
  14.     //*****  
  15. }  

在本例中,項目部署名爲mvc,tomcat url爲 http://localhost,所以實際爲:http://localhos/mvc

在本例中,因爲有命名空間 /test,所以請求hello方法地址爲:http://localhost/mvc/test/hello.do

輸出:springmvc annotation...

二、註解形式的參數接收

1. HttpServletRequest可以直接定義在參數的列表,通過該請求可以傳遞參數

url:http://localhost/mvc/test/toPerson.do?name=zhangsan

Java代碼  收藏代碼
  1. /** 
  2.  * HttpServletRequest可以直接定義在參數的列表, 
  3.  *  
  4.  */  
  5. @RequestMapping("/toPerson.do")  
  6. public String toPerson(HttpServletRequest request) {  
  7.     String result = request.getParameter("name");  
  8.     System.out.println(result);  
  9.     return "jsp1/index";  
  10. }  

 可以從HttpServletRequest 取出“name”屬性,然後進行操作!如上,可以取出 “name=zhangsan”

輸出:zhangsan
2. 在參數列表上直接定義要接收的參數名稱,只要參數名稱能匹配的上就能接收所傳過來的數據, 可以自動轉換成參數列表裏面的類型,注意的是值與類型之間是可以轉換的

2.1傳遞多種不同類型的參數:

url:http://localhost/mvc/test/toPerson1.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

Java代碼  收藏代碼
  1. /** 
  2.  * 傳遞的參數的名字必須要與實體類的屬性set方法後面的字符串匹配的上才能接收到參數,首字符的大小寫不區分 
  3.  * 請求中傳的參數只要是能和參數列表裏面的變量名或者實體裏面的set後面的字符串匹配的上就能接收到 a 
  4.  *  
  5.  */  
  6. @RequestMapping("/toPerson1.do")  
  7. public String toPerson1(String name, Integer age, String address,  
  8.              Date birthday) {  
  9.            System.out.println(name + " " + age + " " + address + " " + birthday);  
  10.            return "jsp1/index";  
  11. }  
  12.   
  13. /** 
  14.  * 註冊時間類型的屬性編輯器,將String轉化爲Date 
  15.  */  
  16. @InitBinder  
  17. public void initBinder(ServletRequestDataBinder binder) {  
  18.     binder.registerCustomEditor(Date.classnew CustomDateEditor(  
  19.             new SimpleDateFormat("yyyy-MM-dd"), true));  
  20. }  

輸出:zhangsan 14 china Fri Feb 11 00:00:00 CST 2000

2.2傳遞數組:

url:http://localhost/mvc/test/toPerson2.do?name=tom&name=jack  

Java代碼  收藏代碼
  1. /** 
  2.  * 對數組的接收,定義爲同名即可  
  3.  */  
  4. @RequestMapping("/toPerson2.do")  
  5. public String toPerson2(String[] name) {  
  6.     for (String result : name) {  
  7.         System.out.println(result);  
  8.     }  
  9.     return "jsp1/index";  
  10. }  

 輸出:tom jack

2.3傳遞自定義對象(可多個):

url:http://localhost/mvc/test/toPerson3.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

 User 定義的屬性有:name,age,並且有各自屬性的對應的set方法以及toString方法

 Person定義的屬性有:name,age.address,birthday,並且有各自屬性的對應的set方法以及toString方法

Java代碼  收藏代碼
  1. /** 
  2.  *  
  3.  * 傳遞的參數的名字必須要與實體類的屬性set方法後面的字符串匹配的上才能接收到參數,首字符的大小寫不區分 
  4.  * 請求中傳的參數只要是能和參數列表裏面的變量名或者實體裏面的set後面的字符串匹配的上就能接收到  
  5.  *  
  6.  */  
  7. @RequestMapping("/toPerson3.do")  
  8. public String toPerson3(Person person, User user) {  
  9.     System.out.println(person);  
  10.     System.out.println(user);  
  11.     return "jsp1/index";  
  12. }  

  輸出:

Person [name=zhangsan, age=14, address=china, birthday=Fri Feb 11 00:00:00 CST 2000]
User [name=zhangsan, age=14]
 

自動封裝了對象,並且被分別注入進來!

 

三、註解形式的結果返回

 1. 數據寫到頁面,方法的返回值採用ModelAndView, new ModelAndView("index", map);,相當於把結果數據放到response裏面

url:http://localhost/mvc/test/toPerson41.do

url:http://localhost/mvc/test/toPerson42.do

url:http://localhost/mvc/test/toPerson43.do

url:http://localhost/mvc/test/toPerson44.do 

Java代碼  收藏代碼
  1. /** 
  2.  * HttpServletRequest可以直接定義在參數的列表,並且帶回返回結果 
  3.  *  
  4.  */  
  5. @RequestMapping("/toPerson41.do")  
  6. public String toPerson41(HttpServletRequest request) throws Exception {  
  7.     request.setAttribute("p", newPesion());  
  8.     return "index";  
  9. }  
  10.   
  11. /** 
  12.  *  
  13.  * 方法的返回值採用ModelAndView, new ModelAndView("index", map); 
  14.  * ,相當於把結果數據放到Request裏面,不建議使用 
  15.  *  
  16.  */  
  17. @RequestMapping("/toPerson42.do")  
  18. public ModelAndView toPerson42() throws Exception {  
  19.     Map<String, Object> map = new HashMap<String, Object>();  
  20.     map.put("p", newPesion());  
  21.     return new ModelAndView("index", map);  
  22. }  
  23.   
  24. /** 
  25.  *  
  26.  * 直接在方法的參數列表中來定義Map,這個Map即使ModelAndView裏面的Map, 
  27.  * 由視圖解析器統一處理,統一走ModelAndView的接口,也不建議使用 
  28.  */  
  29. @RequestMapping("/toPerson43.do")  
  30. public String toPerson43(Map<String, Object> map) throws Exception {  
  31.     map.put("p", newPesion());  
  32.     return "index";  
  33. }  
  34.   
  35. /** 
  36.  *  
  37.  * 在參數列表中直接定義Model,model.addAttribute("p", person); 
  38.  * 把參數值放到request類裏面去,建議使用 
  39.  *  
  40.  */  
  41. @RequestMapping("/toPerson44.do")  
  42. public String toPerson44(Model model) throws Exception {  
  43.     // 把參數值放到request類裏面去  
  44.     model.addAttribute("p", newPesion());  
  45.     return "index";  
  46. }  
  47.   
  48. /** 
  49.  * 爲了測試,創建一個Persion對象 
  50.  *  
  51.  */  
  52. public Person newPesion(){  
  53.     Person person = new Person();  
  54.     person.setName("james");  
  55.     person.setAge(29);  
  56.     person.setAddress("maami");  
  57.     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
  58.     Date date = format.parse("1984-12-28");  
  59.     person.setBirthday(date);  
  60.     return person;  
  61. }  

  以上四種方式均能達到相同的效果,但在參數列表中直接定義Model,model.addAttribute("p", person);把參數值放到request類裏面去,建議使用

 

2. Ajax調用springmvc的方法:直接在參數的列表上定義PrintWriter,out.write(result);把結果寫到頁面,建議使用的

 url:http://localhost/mvc/test/toAjax.do 

 

Java代碼  收藏代碼
  1.     /** 
  2.      *  
  3.      * ajax的請求返回值類型應該是void,參數列表裏直接定義HttpServletResponse, 
  4.      * 獲得PrintWriter的類,最後可把結果寫到頁面 不建議使用  
  5.      */  
  6.     @RequestMapping("/ajax1.do")  
  7.     public void ajax1(String name, HttpServletResponse response) {  
  8.         String result = "hello " + name;  
  9.         try {  
  10.             response.getWriter().write(result);  
  11.         } catch (IOException e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15.   
  16.     /** 
  17.      *  
  18.      * 直接在參數的列表上定義PrintWriter,out.write(result); 
  19.      * 把結果寫到頁面,建議使用的  
  20.      *  
  21.      */  
  22.     @RequestMapping("/ajax2.do")  
  23.     public void ajax2(String name, PrintWriter out) {  
  24.         String result = "hello " + name;  
  25.         out.write(result);  
  26.     }  
  27.     /** 
  28.      * 轉向ajax.jsp頁面 
  29.      */  
  30.   
  31.     @RequestMapping("/toAjax.do")  
  32.    
  33.     public String toAjax() {  
  34.         return "ajax";  
  35.    }  

ajax頁面代碼如下:

Html代碼  收藏代碼
  1. <script type="text/javascript" src="js/jquery-1.6.2.js"></script>  
  2. <script type="text/javascript">  
  3.         $(function(){  
  4.             $("#mybutton").click(function(){  
  5.                 $.ajax({  
  6.                     url:"test/ajax1.do",  
  7.                     type:"post",  
  8.                     dataType:"text",  
  9.                     data:{  
  10.                         name:"zhangsan"  
  11.                     },  
  12.                     success:function(responseText){  
  13.                         alert(responseText);  
  14.                     },  
  15.                     error:function(){  
  16.                         alert("system error");  
  17.                     }  
  18.                 });  
  19.             });  
  20.         });  
  21.     </script>  
  22. </head>  
  23. <body>  
  24.     <input id="mybutton" type="button" value="click">  
  25. </body>  
  26.    

四、表單提交和重定向

1、表單提交:

請求方式的指定:@RequestMapping( method=RequestMethod.POST )可以指定請求方式,前臺頁面就必須要以它制定好的方式來訪問,否則出現405錯誤

 表單jsp頁面: 
Html代碼  收藏代碼
  1. <html>  
  2.   <head>  
  3.     <base href="<%=basePath%>">  
  4.     <title>SpringMVC Form</title>  
  5.   </head>  
  6.   <body>  
  7.     <form action="test/toPerson5.do" method="post">  
  8.         name:<input name="name" type="text"><br>  
  9.         age:<input name="age" type="text"><br>  
  10.         address:<input name="address" type="text"><br>  
  11.         birthday:<input name="birthday" type="text"><br>  
  12.         <input type="submit" value="submit"><br>  
  13.     </form>  
  14.   </body>  
  15. </html>  
 對應方法爲:
Java代碼  收藏代碼
  1. /** 
  2.  * 轉向form.jsp頁面 
  3.  * @return 
  4.  */  
  5. @RequestMapping("/toform.do")  
  6. public String toForm() {  
  7.     return "form";  
  8. }  
  9.   
  10. /** 
  11.  *  
  12.  * @RequestMapping( method=RequestMethod.POST) 
  13.  * 可以指定請求方式,前臺頁面就必須要以它制定好的方式來訪問,否則出現405錯誤 a 
  14.  *  
  15.  */  
  16. @RequestMapping(value = "/toPerson5.do", method = RequestMethod.POST)  
  17. public String toPerson5(Person person) {  
  18.     System.out.println(person);  
  19.     return "jsp1/index";  
  20. }  
 url:http://localhost/mvc/test/toform.do  
2. 重定向:controller內部重定向,redirect:加上同一個controller中的requestMapping的值,controller之間的重定向:必須要指定好controller的命名空間再指定requestMapping的值,redirect:後必須要加/,是從根目錄開始
Java代碼  收藏代碼
  1. /** 
  2.  *  
  3.  * controller內部重定向 
  4.  * redirect:加上同一個controller中的requestMapping的值  
  5.  *  
  6.  */  
  7. @RequestMapping("/redirectToForm.do")  
  8. public String redirectToForm() {  
  9.     return "redirect:toform.do";  
  10. }  
  11.   
  12. /** 
  13.  *  
  14.  * controller之間的重定向:必須要指定好controller的命名空間再指定requestMapping的值, 
  15.  * redirect:後必須要加/,是從根目錄開始 
  16.  */  
  17. @RequestMapping("/redirectToForm1.do")  
  18. public String redirectToForm1() {  
  19.               //test1表示另一個Controller的命名空間  
  20.     return "redirect:/test1/toForm.do";  
  21. }  

 

 參考資料: http://elf8848.iteye.com/blog/875830/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章