pring3.0支持restful实例

最近在研究spring3.0以及传说中的restful,还好研究出来一个例子,现在贴出来望广大网友能一起讨论下,错误的地方恳请大家指点。项目采用SPRING3.0+HIBERNATE2.5。数据库是oracle只有一个表。

[java] view plain copy
  1. create table LMDZ  
  2. (  
  3.   KH_NUM VARCHAR2(20 ),  
  4.   LM_NUM NUMBER(2 )  
  5. );  

首先在eclipse下新建web工程。web.xml文件配置如下:

[java] view plain copy
  1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
  2. <web-app version="2.5"  xmlns= "http://java.sun.com/xml/ns/javaee"  xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >  
  3.     <!--  
  4.         该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static /目录,如原来访问  
  5.         http://localhost/foo.css ,现在http://localhost/static/foo.css   
  6.     -->  
  7.     <servlet-mapping>  
  8.         <servlet-name>default </servlet-name>  
  9.         <url-pattern>/static /*</url-pattern>  
  10.     </servlet-mapping>  
  11.     <servlet>  
  12.         <servlet-name>demorestsms</servlet-name>  
  13.         <servlet-class >org.springframework.web.servlet.DispatcherServlet</servlet- class >  
  14.         <load-on-startup>1 </load-on-startup>  
  15.     </servlet>  
  16.    <!--  
  17.         Key of the system property that should specify the root directory of this   
  18.         web app. Applied by WebAppRootListener or Log4jConfigListener.  
  19.     -->  
  20.     <context-param>  
  21.         <param-name>webAppRootKey</param-name>  
  22.         <param-value>demorestsms.root</param-value>  
  23.     </context-param>  
  24.   
  25.     <!--  
  26.         Location of the Log4J config file, for  initialization and refresh checks.  
  27.         Applied by Log4jConfigListener.  
  28.     -->  
  29.     <context-param>  
  30.         <param-name>log4jConfigLocation</param-name>  
  31.         <param-value>/WEB-INF/classes/log4j.properties</param-value>  
  32.     </context-param>  
  33.   
  34.     <!--  
  35.         - Location of the XML file that defines the root application context.  
  36.         - Applied by ContextLoaderServlet.  
  37.         -  
  38.         - Can be set to:  
  39.         - "/WEB-INF/applicationContext-hibernate.xml"   for  the Hibernate implementation,  
  40.         - "/WEB-INF/applicationContext-jpa.xml"   for  the JPA one, or  
  41.         - "/WEB-INF/applicationContext-jdbc.xml"   for  the JDBC one.  
  42.     -->  
  43.     <context-param>  
  44.         <param-name>contextConfigLocation</param-name>  
  45.   
  46.         <param-value>/WEB-INF/applicationContext.xml</param-value>  
  47.         <!--  
  48.         <param-value>/WEB-INF/applicationContext-hibernate.xml</param-value>  
  49.         <param-value>/WEB-INF/applicationContext-jpa.xml</param-value>  
  50.         -->  
  51.   
  52.         <!--  
  53.                 To use the JPA variant above, you will need to enable Spring load-time  
  54.                 weaving in your server environment. See PetClinic's readme and/or  
  55.                 Spring's JPA documentation for  information on how to  do   this .  
  56.         -->  
  57.     </context-param>  
  58.     <!--  
  59.         - Configures Log4J for   this  web app.  
  60.         - As this  context specifies a context-param  "log4jConfigLocation" , its file path  
  61.         - is used to load the Log4J configuration, including periodic refresh checks.  
  62.         -  
  63.         - Would fall back to default  Log4J initialization (non-refreshing)  if  no special  
  64.         - context-params are given.  
  65.         -  
  66.         - Exports a "web app root key" , i.e. a system property that specifies the root  
  67.         - directory of this  web app,  for  usage in log file paths.  
  68.         - This web app specifies "petclinic.root"  (see log4j.properties file).  
  69.     -->  
  70.     <!-- Leave the listener commented-out if  using JBoss -->  
  71.     <!--  
  72.     <listener>  
  73.         <listener-class >org.springframework.web.util.Log4jConfigListener</listener- class >  
  74.     </listener>  
  75.     -->  
  76.   
  77.     <!--  
  78.         - Loads the root application context of this  web app at startup,  
  79.         - by default  from  "/WEB-INF/applicationContext.xml" .  
  80.         - Note that you need to fall back to Spring's ContextLoaderServlet for   
  81.         - J2EE servers that do  not follow the Servlet  2.4  initialization order.  
  82.         -  
  83.         - Use WebApplicationContextUtils.getWebApplicationContext(servletContext)  
  84.         - to access it anywhere in the web application, outside of the framework.  
  85.         -  
  86.         - The root context is the parent of all servlet-specific contexts.  
  87.         - This means that its beans are automatically available in these child contexts,  
  88.         - both for  getBean(name) calls and (external) bean references.  
  89.     -->  
  90.     <listener>  
  91.         <listener-class >org.springframework.web.context.ContextLoaderListener</listener- class >  
  92.     </listener>  
  93.   
  94.     <!--  
  95.         - Maps the petclinic dispatcher to "*.do" . All handler mappings in  
  96.         - petclinic-servlet.xml will by default  be applied to  this  subpath.  
  97.         - If a mapping isn't a /* subpath, the handler mappings are considered  
  98.         - relative to the web app root.  
  99.         -  
  100.         - NOTE: A single dispatcher can be mapped to multiple paths, like any servlet.  
  101.     -->  
  102.     <servlet-mapping>  
  103.         <servlet-name>zszqrestsms</servlet-name>  
  104.         <url-pattern>/</url-pattern>  
  105.     </servlet-mapping>  
  106.   
  107.     <session-config>  
  108.         <session-timeout>10 </session-timeout>  
  109.     </session-config>  
  110.   
  111.     <welcome-file-list>  
  112.         <!-- Redirects to "welcome.htm"   for  dispatcher handling -->  
  113.         <welcome-file>index.jsp</welcome-file>  
  114.     </welcome-file-list>  
  115.       
  116.     <!--error-page>  
  117.         <exception-type>java.lang.Exception</exception-type>  
  118.         <location>/WEB-INF/jsp/uncaughtException.jsp</location>  
  119.     </error-page-->  
  120.       
  121.     <!-- 浏览器不支持put,delete等method,由该filter将/blog?_method=delete转换为标准的http delete方法 -->     
  122.     <filter>     
  123.         <filter-name>HiddenHttpMethodFilter</filter-name>     
  124.         <filter-class >org.springframework.web.filter.HiddenHttpMethodFilter</filter- class >     
  125.     </filter>     
  126.          
  127.     <filter-mapping>     
  128.         <filter-name>HiddenHttpMethodFilter</filter-name>     
  129.         <servlet-name>demorestsms</servlet-name>     
  130.     </filter-mapping>  
  131.   
  132. </web-app>  

在WEB-INF下面的applicationContext.xml文件如下:

[java] view plain copy
  1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"   
  3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:context= "http://www.springframework.org/schema/context"   
  4.   xmlns:tx="http://www.springframework.org/schema/tx"  xmlns:jdbc= "http://www.springframework.org/schema/jdbc"   
  5.   xmlns:p="http://www.springframework.org/schema/p"   
  6.   xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  8.     http://www.springframework.org/schema/context   
  9.     http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  10.     http://www.springframework.org/schema/tx   
  11.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
  12.     http://www.springframework.org/schema/jdbc   
  13.     http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">   
  14.       
  15.     <bean id="propertyConfigurer"   
  16.           class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"   
  17.           p:location="/WEB-INF/jdbc.properties"  />  
  18.       
  19.     <bean id="dataSource"   
  20.           class = "org.springframework.jdbc.datasource.DriverManagerDataSource"   
  21.           p:driverClassName="${jdbc.driverClassName}"   
  22.           p:url="${jdbc.url}"   
  23.           p:username="${jdbc.username}"   
  24.           p:password="${jdbc.password}"  />  
  25.       
  26.     <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->  
  27.     <!-- Hibernate SessionFactory -->  
  28.     <bean id="sessionFactory"   class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"   
  29.                 p:dataSource-ref="dataSource"  p:mappingResources= "zszqlmdz.hbm.xml" >  
  30.         <property name="hibernateProperties" >  
  31.                 <props>  
  32.                         <prop key="hibernate.dialect" >${hibernate.dialect}</prop>  
  33.                         <prop key="hibernate.show_sql" >${hibernate.show_sql}</prop>  
  34.                         <prop key="hibernate.generate_statistics" >${hibernate.generate_statistics}</prop>  
  35.                 </props>  
  36.         </property>  
  37.         <property name="eventListeners" >  
  38.                 <map>  
  39.                         <entry key="merge" >  
  40.                                 <bean class = "org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />  
  41.                         </entry>  
  42.                 </map>  
  43.         </property>  
  44.     </bean>  
  45.   
  46.     <!-- Transaction manager for  a single Hibernate SessionFactory (alternative to JTA) -->  
  47.     <bean id="transactionManager"   class = "org.springframework.orm.hibernate3.HibernateTransactionManager"   
  48.                 p:sessionFactory-ref="sessionFactory" />  
  49.   
  50.     <!-- Transaction manager that delegates to JTA (for  a transactional JNDI DataSource) -->  
  51.     <!--  
  52.     <bean id="transactionManager"   class = "org.springframework.transaction.jta.JtaTransactionManager" />  
  53.     -->  
  54.   
  55.   
  56.     <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->  
  57.   
  58.     <!--  
  59.         Activates various annotations to be detected in bean classes:  
  60.         Spring's @Required and @Autowired, as well as JSR 250'@Resource .  
  61.     -->  
  62.     <context:annotation-config/>  
  63.   
  64.     <!--  
  65.         Instruct Spring to perform declarative transaction management  
  66.         automatically on annotated classes.  
  67.     -->  
  68.     <tx:annotation-driven/>  
  69.   
  70.     <!--  
  71.         Exporter that exposes the Hibernate statistics service via JMX. Autodetects the  
  72.         service MBean, using its bean name as JMX object name.  
  73.     -->  
  74.     <context:mbean-export/>  
  75.   
  76.     <!-- PetClinic's central data access object: Hibernate implementation -->  
  77.     <bean id="clinic"   class = "com.cssweb.zszq.lmdz.hibernate.HibernateClinic" />  
  78.   
  79.     <!-- Hibernate's JMX statistics service -->  
  80.     <bean name="demorestsms:type=HibernateStatistics"   class = "org.hibernate.jmx.StatisticsService"  autowire= "byName" />  
  81. </beans>  

在WEB-INF下面的demorestsms-servlet.xml文件如下:

[java] view plain copy
  1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"   
  3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:context= "http://www.springframework.org/schema/context"   
  4.   xmlns:aop="http://www.springframework.org/schema/aop"  xmlns:p= "http://www.springframework.org/schema/p"   
  5.   xmlns:tx="http://www.springframework.org/schema/tx"  xmlns:jdbc= "http://www.springframework.org/schema/jdbc"   
  6.    
  7.   xsi:schemaLocation="http://www.springframework.org/schema/beans   
  8.            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  9.            http://www.springframework.org/schema/context   
  10.            http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  11.            http://www.springframework.org/schema/tx   
  12.            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
  13.            http://www.springframework.org/schema/jdbc   
  14.            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">   
  15.   
  16.     <!--  
  17.         - The controllers are autodetected POJOs labeled with the @Controller  annotation.  
  18.     -->  
  19.     <context:component-scan base-package = "com.cssweb.zszq.lmdz.web" />  
  20.   
  21.     <!--  
  22.         - The form-based controllers within this  application provide  @RequestMapping    
  23.         - annotations at the type level for  path mapping URLs and  @RequestMapping    
  24.         - at the method level for  request type mappings (e.g., GET and POST).   
  25.         - In contrast, ClinicController - which is not form-based - provides   
  26.         - @RequestMapping  only at the method level  for  path mapping URLs.  
  27.         -  
  28.         - DefaultAnnotationHandlerMapping is driven by these annotations and is   
  29.         - enabled by default  with Java  5 +.  
  30.     -->  
  31.     <bean class = "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"  />  
  32.     <!--  
  33.         - This bean processes annotated handler methods, applying PetClinic-specific PropertyEditors  
  34.         - for  request parameter binding. It overrides the  default  AnnotationMethodHandlerAdapter.  
  35.     -->  
  36.     <bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
  37.         <property name="webBindingInitializer" >  
  38.             <bean class = "com.cssweb.zszq.lmdz.web.ClinicBindingInitializer" />  
  39.         </property>  
  40.     </bean>  
  41.   
  42.     <!--  
  43.         - This bean resolves specific types of exceptions to corresponding logical   
  44.         - view names for  error views. The  default  behaviour of DispatcherServlet   
  45.         - is to propagate all exceptions to the servlet container: this  will happen   
  46.         - here with all other types of exceptions.  
  47.     -->  
  48.     <bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >  
  49.         <property name="exceptionMappings" >  
  50.             <props>  
  51.                 <prop key="org.springframework.dao.DataAccessException" >dataAccessFailure</prop>  
  52.                 <prop key="org.springframework.transaction.TransactionException" >dataAccessFailure</prop>  
  53.             </props>  
  54.         </property>  
  55.     </bean>  
  56.   
  57.     <!--  
  58.         - This bean configures the 'prefix'  and  'suffix'  properties of   
  59.         - InternalResourceViewResolver, which resolves logical view names   
  60.         - returned by Controllers. For example, a logical view name of "vets"    
  61.         - will be mapped to "/WEB-INF/jsp/vets.jsp" .  
  62.     -->  
  63.     <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver"  p:prefix= "/WEB-INF/jsp/"   
  64.             p:suffix=".jsp" />  
  65.   
  66.     <!--  
  67.         - Message source for   this  context, loaded from localized  "messages_xx"  files.  
  68.         - Could also reside in the root application context, as it is generic,  
  69.         - but is currently just used within PetClinic's web tier.  
  70.     -->  
  71.     <bean id="messageSource"   class = "org.springframework.context.support.ResourceBundleMessageSource"   
  72.             p:basename="messages" />  
  73.   
  74. </beans>  

在WEB-INF下面的jdbc.properties文件如下:

[java] view plain copy
  1. # To change  this  template, choose Tools | Templates  
  2. # and open the template in the editor.  
  3. jdbc.driverClassName=oracle.jdbc.driver.OracleDriver  
  4. jdbc.url=jdbc:oracle:thin:@localhost : 1521 :orcl  
  5. jdbc.username=scott  
  6. jdbc.password=tiger  
  7. hibernate.generate_statistics=true   
  8. hibernate.show_sql=true   
  9. hibernate.dialect=org.hibernate.dialect.Oracle10gDialect  

配置大致就这些,下面给出连接hibernate的接口

[java] view plain copy
  1. /*  
  2.  * To change this template, choose Tools | Templates  
  3.  * and open the template in the editor.  
  4.  */   
  5.   
  6. package  com.cssweb.zszq.lmdz;  
  7.   
  8. import  java.util.Collection;  
  9.   
  10. import  org.springframework.dao.DataAccessException;  
  11.   
  12. import  com.cssweb.zszq.lmdz.pojo.Khzl;  
  13. import  com.cssweb.zszq.lmdz.pojo.LmdzNew;  
  14.   
  15. /**  
  16.  *  
  17.  * @author HUJUN  
  18.  */   
  19. public   interface  Clinic {  
  20.     Collection<LmdzNew> findLmdzs(String fundid) throws  DataAccessException;  
  21.       
  22.     void  save(String fundid, String[] no)  throws  DataAccessException;  
  23.       
  24.     int  delete(String fundid)  throws  DataAccessException;  
  25.       
  26.     Khzl findKh(String clientId) throws  DataAccessException;  
  27.       
  28.     int  updateTelById(String fundid, String mobile)  throws  DataAccessException;  
  29. }  

连接hibernate的service类

[java] view plain copy
  1. /*  
  2.  * To change this template, choose Tools | Templates  
  3.  * and open the template in the editor.  
  4.  */   
  5.   
  6. package  com.cssweb.zszq.lmdz.hibernate;  
  7.   
  8. import  java.util.Collection;  
  9.   
  10. import  org.hibernate.Session;  
  11. import  org.hibernate.SessionFactory;  
  12. import  org.hibernate.Transaction;  
  13. import  org.springframework.beans.factory.annotation.Autowired;  
  14. import  org.springframework.transaction.annotation.Transactional;  
  15.   
  16. import  com.cssweb.zszq.lmdz.Clinic;  
  17. import  com.cssweb.zszq.lmdz.pojo.Khzl;  
  18. import  com.cssweb.zszq.lmdz.pojo.LmdzNew;  
  19. /**  
  20.  *  
  21.  * @author HUJUN  
  22.  */   
  23. public   class  HibernateClinic  implements  Clinic {  
  24.     @Autowired   
  25.     private  SessionFactory sessionFactory;  
  26.   
  27.     @Transactional (readOnly =  true )  
  28.     @SuppressWarnings ( "unchecked" )  
  29.     public  Collection<LmdzNew> findLmdzs(String fundid) {  
  30.         return  sessionFactory.getCurrentSession().createQuery( "from LmdzNew lmdz where lmdz.khNum = :fundid" )  
  31.                 .setString("fundid" , fundid).list();  
  32.     }  
  33.   
  34.     public   void  save(String fundid, String[] no) {  
  35.         Session session = sessionFactory.openSession();  
  36.         Transaction tx = session.beginTransaction();  
  37.         for  ( int  i =  0 ; i < no.length; i++) {  
  38.             LmdzNew lmdzNes = new  LmdzNew(fundid, Integer.parseInt(no[i]));  
  39.             session.save(lmdzNes);  
  40.             if  (i %  20  ==  0 ) {  
  41.                 session.flush();  
  42.                 session.clear();  
  43.             }  
  44.         }  
  45.         tx.commit();  
  46.         session.close();  
  47.     }  
  48.       
  49.     public   int  delete(String fundid) {  
  50.         return  sessionFactory.openSession().createQuery( "delete from LmdzNew lmdz where lmdz.khNum = :fundid" )  
  51.                 .setString("fundid" , fundid).executeUpdate();  
  52.     }  
  53.       
  54.     @Transactional (readOnly =  true )  
  55.     public  Khzl findKh(String clientId) {  
  56.         return  (Khzl) sessionFactory.openSession().load(Khzl. class , clientId);  
  57.     }  
  58.       
  59.     public   int  updateTelById(String fundid, String mobile) {  
  60.         return  sessionFactory.openSession().createQuery( "update Khzl set mobileTel = :mobile where clientId = :fundid" )  
  61.         .setString("fundid" , fundid)  
  62.         .setString("mobile" , mobile)  
  63.         .executeUpdate();  
  64.     }  
  65. }  

再来看action这一层的东西:

[java] view plain copy
  1. /*  
  2.  * To change this template, choose Tools | Templates  
  3.  * and open the template in the editor.  
  4.  */   
  5.   
  6. package  com.cssweb.zszq.lmdz.web;  
  7.   
  8. import  java.io.OutputStreamWriter;  
  9. import  java.io.PrintWriter;  
  10. import  java.util.Collection;  
  11. import  java.util.Iterator;  
  12.   
  13. import  javax.servlet.http.HttpServletRequest;  
  14. import  javax.servlet.http.HttpServletResponse;  
  15.   
  16. import  org.springframework.beans.factory.annotation.Autowired;  
  17. import  org.springframework.stereotype.Controller;  
  18. import  org.springframework.web.bind.annotation.PathVariable;  
  19. import  org.springframework.web.bind.annotation.RequestMapping;  
  20. import  org.springframework.web.bind.annotation.RequestMethod;  
  21.   
  22. import  com.cssweb.common.util.CollectionData;  
  23. import  com.cssweb.zszq.lmdz.Clinic;  
  24. import  com.cssweb.zszq.lmdz.pojo.Khzl;  
  25. import  com.cssweb.zszq.lmdz.pojo.LmdzNew;  
  26.   
  27. /**  
  28.  *  
  29.  * @author HUJUN  
  30.  */   
  31. @Controller      
  32. @RequestMapping ( "/zszqsms" )  
  33. public   class  LmdzForm {  
  34.     private   final  Clinic clinic;  
  35.   
  36.     @Autowired   
  37.     public  LmdzForm(Clinic clinic) {  
  38.         this .clinic = clinic;  
  39.     }  
  40.       
  41.       
  42.     @RequestMapping (value= "/{fundid}" , method = RequestMethod.GET)     
  43.     public   void  get(HttpServletRequest request, HttpServletResponse response,  @PathVariable ( "fundid" ) String fundid)  throws  Exception {  
  44.         System.out.println(">>>>>>>>>>getList>>>>>>>>>>>>>>" +fundid);  
  45.         StringBuilder msg = new  StringBuilder();  
  46.         Khzl khzl = this .clinic.findKh(fundid);  
  47.         if (khzl!= null ) {  
  48.             Collection<LmdzNew> lm = CollectionData.getLmList();  
  49.             Collection<LmdzNew> results = this .clinic.findLmdzs(fundid);  
  50.             Iterator<LmdzNew> it = lm.iterator();  
  51.             String json = "{total:" +lm.size()+ ",root:[" ;  
  52.             int  i =  0 ;  
  53.             while (it.hasNext()) {  
  54.                 LmdzNew lmdz = it.next();  
  55.                 lmdz.setState(1 );  
  56.                 json += "{lmid:'"  + lmdz.getLmNum() +  "',lmname:'"  + lmdz.getLmName() +  "',lmstate:'"  + lmdz.getState() +  "'}" ;  
  57.                 i++;  
  58.                 if  (i != lm.size() -  1 ) {  
  59.                      json += "," ;  
  60.                 }  
  61.             }  
  62.             json += "]}" ;  
  63.             msg.append("{/" msg/ ":/" "+json+" / "}" );  
  64.         }  
  65.         else  {  
  66.             msg.append("{/" msg/ ":/" 帐号不存在/ "}" );  
  67.         }  
  68.         printData(response, msg);  
  69.     }  
  70.       
  71.     @RequestMapping (value =  "/{fundid}/{no}" , method = RequestMethod.POST)  
  72.     public   void  save(HttpServletRequest request, HttpServletResponse response,  @PathVariable ( "fundid" ) String fundid,   
  73.             @PathVariable ( "no" ) String no)  throws  Exception {  
  74.         System.out.println(fundid + ">>>>>>>>>>save>>>>>>>>>>>>>>" +no);  
  75.         StringBuilder msg = new  StringBuilder();  
  76.         this .clinic.save(fundid, no.split( "," ));  
  77.         msg.append("{/" msg/ ":/" 成功/ "}" );  
  78.         printData(response, msg);  
  79.     }  
  80.       
  81.     @RequestMapping (value =  "/{fundid}/{no}" , method = RequestMethod.PUT)  
  82.     public   void  update(HttpServletRequest request, HttpServletResponse response,  @PathVariable ( "fundid" ) String fundid,   
  83.             @PathVariable ( "no" ) String no)  throws  Exception {  
  84.         System.out.println(fundid + ">>>>>>>>>>update>>>>>>>>>>>>>>" +no);  
  85.         StringBuilder msg = new  StringBuilder();  
  86.         int  i =  this .clinic.updateTelById(fundid, no);  
  87.         if (i> 0 ) {  
  88.             msg.append("{/" msg/ ":/" 成功/ "}" );  
  89.         }  
  90.         msg.append("{/" msg/ ":/" 失败/ "}" );  
  91.         printData(response, msg);  
  92.     }  
  93.       
  94.     @RequestMapping (value =  "/{fundid}" , method = RequestMethod.DELETE)  
  95.     public   void  delete(HttpServletRequest request, HttpServletResponse response,  @PathVariable ( "fundid" ) String fundid)  
  96.             throws  Exception {  
  97.         System.out.println(">>>>>>>>>>delete>>>>>>>>>>>>>>" +fundid);  
  98.         StringBuilder msg = new  StringBuilder();  
  99.         int  i =  this .clinic.delete(fundid);  
  100.         if (i> 0 ) {  
  101.             msg.append("{/" msg/ ":/" 成功/ "}" );  
  102.         }  
  103.         msg.append("{/" msg/ ":/" 失败/ "}" );  
  104.         printData(response, msg);  
  105.     }  
  106.       
  107.     private   void  printData(HttpServletResponse response, StringBuilder msg){  
  108.         try  {  
  109.             response.setContentType("text/html;charset=utf-8" );  
  110.             response.setCharacterEncoding("UTF-8" );  
  111.             PrintWriter out = new  PrintWriter( new  OutputStreamWriter(response.getOutputStream(),  "UTF-8" ));  
  112.             out.println( msg );  
  113.             out.close();  
  114.         } catch  (Exception e) {  
  115.             e.printStackTrace();  
  116.         }  
  117.     }  
  118. }  

最后还有个POJO类,呵呵:

[java] view plain copy
  1. package  com.cssweb.zszq.lmdz.pojo;  
  2.   
  3.   
  4. /**  
  5.  * LmdzNew entity. @author MyEclipse Persistence Tools  
  6.  */   
  7.   
  8. public   class  LmdzNew  implements  java.io.Serializable {  
  9.   
  10.     // Fields   
  11.   
  12.     /**  
  13.      *   
  14.      */   
  15.     private   static   final   long  serialVersionUID = -5138845755309588033L;  
  16.       
  17.     private  String khNum;  
  18.     private   int  lmNum;  
  19.       
  20.     private  String lmName;  
  21.     private   int  state;  
  22.   
  23.     // Constructors   
  24.   
  25.     /** default constructor */   
  26.     public  LmdzNew() {  
  27.     }  
  28.       
  29.     /** full constructor */   
  30.     public  LmdzNew(String khNum,  int  lmNum) {  
  31.         this .khNum = khNum;  
  32.         this .lmNum = lmNum;  
  33.     }  
  34.       
  35.     public  String getKhNum() {  
  36.         return   this .khNum;  
  37.     }  
  38.   
  39.     public   void  setKhNum(String khNum) {  
  40.         this .khNum = khNum;  
  41.     }  
  42.   
  43.     public   int  getLmNum() {  
  44.         return   this .lmNum;  
  45.     }  
  46.   
  47.     public   void  setLmNum( int  lmNum) {  
  48.         this .lmNum = lmNum;  
  49.     }  
  50.       
  51.     public  String getLmName() {  
  52.         return  lmName;  
  53.     }  
  54.   
  55.     public   void  setLmName(String lmName) {  
  56.         this .lmName = lmName;  
  57.     }  
  58.   
  59.     public   int  getState() {  
  60.         return  state;  
  61.     }  
  62.   
  63.     public   void  setState( int  state) {  
  64.         this .state = state;  
  65.     }  
  66.       
  67.     public   boolean  equals(Object other) {  
  68.         if  (( this  == other))  
  69.             return   true ;  
  70.         if  ((other ==  null ))  
  71.             return   false ;  
  72.         return   false ;  
  73.     }  
  74.       
  75.     public   int  hashCode() {  
  76.         int  result =  17 ;  
  77.   
  78.         result = 37  * result  
  79.                 + (getKhNum() == null  ?  0  :  this .getKhNum().hashCode());  
  80.         return  result;  
  81.     }  
  82. }  

好了,所有的源代码都贴出来了。整个服务端的程序可以跑在tomcat下做测试。接下来我们只需要提供rest客户端的接口让别的应用调用即可。下面再给出个调用的demo。这个项目比较简单。

还望大家多多指教,大家互相学习学习。

[java] view plain copy
  1. package  com.cssweb.zszq.client;  
  2.   
  3. import  java.io.BufferedReader;  
  4. import  java.io.IOException;  
  5. import  java.io.InputStreamReader;  
  6. import  java.net.HttpURLConnection;  
  7. import  java.net.URL;  
  8.   
  9. public   class  ClientTest {  
  10.   
  11.     public   static   void  main(String[] args)  throws  IOException {  
  12.         delete();  
  13.         update();  
  14.         save();  
  15.         select();  
  16.     }  
  17.       
  18.     /**  
  19.      * 查询栏目定制  
  20.      * 68008610为资金帐号  
  21.      */   
  22.     public   static   void  select() {  
  23.         try  {  
  24.             URL url = new  URL( "http://localhost:8080/zszqrestsms/zszqsms/68008610" );  
  25.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  26.             conn.setDoOutput(true );  
  27.             conn.setRequestMethod("GET" );  
  28.             conn.setRequestProperty("Content-Type""text/json" );  
  29.             BufferedReader rd = new  BufferedReader( new  InputStreamReader(conn  
  30.                     .getInputStream()));  
  31.             String line;  
  32.             while  ((line = rd.readLine()) !=  null ) {  
  33.                 System.out.println(line);  
  34.             }  
  35.   
  36.             rd.close();  
  37.         } catch  (Exception e) {  
  38.             System.out.println("Error"  + e);  
  39.         }  
  40.     }  
  41.       
  42.     /**  
  43.      * 删除定制栏目  
  44.      * 68008610为资金帐号  
  45.      */   
  46.     public   static   void  delete() {  
  47.         try  {  
  48.             URL url = new  URL( "http://localhost:8080/zszqrestsms/zszqsms/68008610" );  
  49.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  50.             conn.setDoOutput(true );  
  51.             conn.setRequestMethod("DELETE" );  
  52.             conn.setRequestProperty("Content-Type""text/json" );  
  53.             BufferedReader rd = new  BufferedReader( new  InputStreamReader(conn  
  54.                     .getInputStream()));  
  55.             String line;  
  56.             while  ((line = rd.readLine()) !=  null ) {  
  57.                 System.out.println(line);  
  58.             }  
  59.   
  60.             rd.close();  
  61.         } catch  (Exception e) {  
  62.             System.out.println("Error"  + e);  
  63.         }  
  64.     }  
  65.       
  66.     /**  
  67.      * 修改手机号码  
  68.      * 68008610为资金帐号  
  69.      */   
  70.     public   static   void  update() {  
  71.         try  {  
  72.             URL url = new  URL( "http://localhost:8080/zszqrestsms/zszqsms/68008610/1342345677" );  
  73.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  74.             conn.setDoOutput(true );  
  75.             conn.setRequestMethod("PUT" );  
  76.             conn.setRequestProperty("Content-Type""text/json" );  
  77.             BufferedReader rd = new  BufferedReader( new  InputStreamReader(conn  
  78.                     .getInputStream()));  
  79.             String line;  
  80.             while  ((line = rd.readLine()) !=  null ) {  
  81.                 System.out.println(line);  
  82.             }  
  83.   
  84.             rd.close();  
  85.         } catch  (Exception e) {  
  86.             System.out.println("Error"  + e);  
  87.         }  
  88.     }  
  89.       
  90.     /**  
  91.      * 保存定制的栏目  
  92.      * 68008610为资金帐号  
  93.      */   
  94.     public   static   void  save() {  
  95.         try  {  
  96.             URL url = new  URL( "http://localhost:8080/zszqrestsms/zszqsms/68008617/1,2,3,4" );  
  97.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  98.             conn.setDoOutput(true );  
  99.             conn.setRequestMethod("POST" );  
  100.             conn.setRequestProperty("Content-Type""text/json" );  
  101.             BufferedReader rd = new  BufferedReader( new  InputStreamReader(conn  
  102.                     .getInputStream()));  
  103.             String line;  
  104.             while  ((line = rd.readLine()) !=  null ) {  
  105.                 System.out.println(line);  
  106.             }  
  107.   
  108.             rd.close();  
  109.         } catch  (Exception e) {  
  110.             System.out.println("Error"  + e);  
  111.         }  
  112.     }  
  113. }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值