利用Spring 3實(shí)現(xiàn)Rest配置與開發(fā)
最近項(xiàng)目要用到Rest,選擇了Spring 3,關(guān)于Rest的介紹:
?
?
?REST關(guān)鍵原則
REST定義了應(yīng)該如何正確地使用(這和大多數(shù)人的實(shí)際使用方式有很大不同)Web標(biāo)準(zhǔn),例如HTTP和URI。如果你在設(shè)計(jì)應(yīng)用程序時(shí)能堅(jiān)持REST原則,那就預(yù)示著你將會(huì)得到一個(gè)使用了優(yōu)質(zhì)Web架構(gòu)(這將讓你受益)的系統(tǒng)。總之,五條關(guān)鍵原則列舉如下:
- 為所有“事物”定義ID
- 將所有事物鏈接在一起
- 使用標(biāo)準(zhǔn)方法
- 資源多重表述
- 無狀態(tài)通信
?
Spring 3.0開始將全面支持Rest,而且配置實(shí)現(xiàn)起來也相當(dāng)簡(jiǎn)單,利用Spring MVC在web.xml定義片段:
?
?
<servlet> <servlet-name>mydemo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mydemo</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
?
繼而在Web-INF目錄下增加mydemo-servlet.xml,內(nèi)容如下:
?
?
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Auto scan, declare the location path --> <context:component-scan base-package="com.mydemo.springmvc.rest" /> <!-- Using annontation --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- Resolve the view, declare the prefix and suffix --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/view/" p:suffix=".jsp" p:viewClass="org.springframework.web.servlet.view.JstlView" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" /> </beans>
?
這里我們定義了JSP文件的標(biāo)簽庫用jstl,并啟動(dòng)了注解功能,并自動(dòng)掃描com.mydemo.springmvc.rest下的controller,接著我們就可以在com.mydemo.springmvc.rest包下編寫controller代碼
并可以使用注解功能,如類似的代碼如下:
?
?
@Controller public class MyDemoController { private CommonDAO commonDAO; @Autowired public void setCommonDAO(CommonDAO commonDAO) { this.commonDAO = commonDAO; } private MyDemoController (){} @RequestMapping(value="/home", method=RequestMethod.GET) public String welcome(){ return "/home"; } }?
然后就可以在view目錄下通過增加home.jsp來實(shí)現(xiàn)顯示層代碼的編寫工作,所有的步驟就以上這些,接下去你就可以通過類似:http://localhost:8080/mydemo/home,來訪問了(這里Controller通過注解的方式注入DAO以便進(jìn)行數(shù)據(jù)庫的訪問)
已有 0 人發(fā)表留言,猛擊->>這里<<-參與討論
JavaEye推薦
posted on 2010-09-28 13:19 徐靈 閱讀(577) 評(píng)論(0) 編輯 收藏