有没有tp3.2 的php restful api 例子的例子

12823人阅读
技术文章(48)
最近在研究spring3.0以及传说中的restful,还好研究出来一个例子,现在贴出来望广大网友能一起讨论下,错误的地方恳请大家指点。项目采用SPRING3.0+HIBERNATE2.5。数据库是oracle只有一个表。
create table LMDZ
KH_NUM VARCHAR2(20),
LM_NUM NUMBER(2)
首先在eclipse下新建web工程。web.xml文件配置如下:
&?xml version="1.0" encoding="UTF-8"?&
&web-app version="2.5" xmlns="/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_2_5.xsd"&
该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问
http://localhost/foo.css ,现在http://localhost/static/foo.css
&servlet-mapping&
&servlet-name&default&/servlet-name&
&url-pattern&/static/*&/url-pattern&
&/servlet-mapping&
&servlet-name&demorestsms&/servlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&
&load-on-startup&1&/load-on-startup&
&/servlet&
Key of the system property that should specify the root directory of this
web app. Applied by WebAppRootListener or Log4jConfigListener.
&context-param&
&param-name&webAppRootKey&/param-name&
&param-value&demorestsms.root&/param-value&
&/context-param&
Location of the Log4J config file, for initialization and refresh checks.
Applied by Log4jConfigListener.
&context-param&
&param-name&log4jConfigLocation&/param-name&
&param-value&/WEB-INF/classes/log4j.properties&/param-value&
&/context-param&
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderServlet.
- Can be set to:
- "/WEB-INF/applicationContext-hibernate.xml" for the Hibernate implementation,
- "/WEB-INF/applicationContext-jpa.xml" for the JPA one, or
- "/WEB-INF/applicationContext-jdbc.xml" for the JDBC one.
&context-param&
&param-name&contextConfigLocation&/param-name&
&param-value&/WEB-INF/applicationContext.xml&/param-value&
&param-value&/WEB-INF/applicationContext-hibernate.xml&/param-value&
&param-value&/WEB-INF/applicationContext-jpa.xml&/param-value&
To use the JPA variant above, you will need to enable Spring load-time
weaving in your server environment. See PetClinic's readme and/or
Spring's JPA documentation for information on how to do this.
&/context-param&
- Configures Log4J for this web app.
- As this context specifies a context-param "log4jConfigLocation", its file path
- is used to load the Log4J configuration, including periodic refresh checks.
- Would fall back to default Log4J initialization (non-refreshing) if no special
- context-params are given.
- Exports a "web app root key", i.e. a system property that specifies the root
- directory of this web app, for usage in log file paths.
- This web app specifies "petclinic.root" (see log4j.properties file).
&!-- Leave the listener commented-out if using JBoss --&
&listener&
&listener-class&org.springframework.web.util.Log4jConfigListener&/listener-class&
&/listener&
- Loads the root application context of this web app at startup,
- by default from "/WEB-INF/applicationContext.xml".
- Note that you need to fall back to Spring's ContextLoaderServlet for
- J2EE servers that do not follow the Servlet 2.4 initialization order.
- Use WebApplicationContextUtils.getWebApplicationContext(servletContext)
- to access it anywhere in the web application, outside of the framework.
- The root context is the parent of all servlet-specific contexts.
- This means that its beans are automatically available in these child contexts,
- both for getBean(name) calls and (external) bean references.
&listener&
&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class&
&/listener&
- Maps the petclinic dispatcher to "*.do". All handler mappings in
- petclinic-servlet.xml will by default be applied to this subpath.
- If a mapping isn't a /* subpath, the handler mappings are considered
- relative to the web app root.
- NOTE: A single dispatcher can be mapped to multiple paths, like any servlet.
&servlet-mapping&
&servlet-name&zszqrestsms&/servlet-name&
&url-pattern&/&/url-pattern&
&/servlet-mapping&
&session-config&
&session-timeout&10&/session-timeout&
&/session-config&
&welcome-file-list&
&!-- Redirects to "welcome.htm" for dispatcher handling --&
&welcome-file&index.jsp&/welcome-file&
&/welcome-file-list&
&!--error-page&
&exception-type&java.lang.Exception&/exception-type&
&location&/WEB-INF/jsp/uncaughtException.jsp&/location&
&/error-page--&
&!-- 浏览器不支持put,delete等method,由该filter将/blog?_method=delete转换为标准的http delete方法 --&
&filter-name&HiddenHttpMethodFilter&/filter-name&
&filter-class&org.springframework.web.filter.HiddenHttpMethodFilter&/filter-class&
&filter-mapping&
&filter-name&HiddenHttpMethodFilter&/filter-name&
&servlet-name&demorestsms&/servlet-name&
&/filter-mapping&
&/web-app&
在WEB-INF下面的applicationContext.xml文件如下:
&?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"&
&bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" /&
&bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /&
&!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) --&
&!-- Hibernate SessionFactory --&
&bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" p:mappingResources="zszqlmdz.hbm.xml"&
&property name="hibernateProperties"&
&prop key="hibernate.dialect"&${hibernate.dialect}&/prop&
&prop key="hibernate.show_sql"&${hibernate.show_sql}&/prop&
&prop key="hibernate.generate_statistics"&${hibernate.generate_statistics}&/prop&
&/property&
&property name="eventListeners"&
&entry key="merge"&
&bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/&
&/property&
&!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --&
&bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/&
&!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) --&
&bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/&
&!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= --&
Activates various annotations to be detected in bean classes:
Spring's @Required and @Autowired, as well as JSR 250's @Resource.
&context:annotation-config/&
Instruct Spring to perform declarative transaction management
automatically on annotated classes.
&tx:annotation-driven/&
Exporter that exposes the Hibernate statistics service via JMX. Autodetects the
service MBean, using its bean name as JMX object name.
&context:mbean-export/&
&!-- PetClinic's central data access object: Hibernate implementation --&
&bean id="clinic" class="com.cssweb.zszq.lmdz.hibernate.HibernateClinic"/&
&!-- Hibernate's JMX statistics service --&
&bean name="demorestsms:type=HibernateStatistics" class="org.hibernate.jmx.StatisticsService" autowire="byName"/&
在WEB-INF下面的demorestsms-servlet.xml文件如下:
&?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"&
- The controllers are autodetected POJOs labeled with the @Controller annotation.
&context:component-scan base-package="com.cssweb.zszq.lmdz.web"/&
- The form-based controllers within this application provide @RequestMapping
- annotations at the type level for path mapping URLs and @RequestMapping
- at the method level for request type mappings (e.g., GET and POST).
- In contrast, ClinicController - which is not form-based - provides
- @RequestMapping only at the method level for path mapping URLs.
- DefaultAnnotationHandlerMapping is driven by these annotations and is
- enabled by default with Java 5+.
&bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /&
- This bean processes annotated handler methods, applying PetClinic-specific PropertyEditors
- for request parameter binding. It overrides the default AnnotationMethodHandlerAdapter.
&bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&
&property name="webBindingInitializer"&
&bean class="com.cssweb.zszq.lmdz.web.ClinicBindingInitializer"/&
&/property&
- This bean resolves specific types of exceptions to corresponding logical
- view names for error views. The default behaviour of DispatcherServlet
- is to propagate all exceptions to the servlet container: this will happen
- here with all other types of exceptions.
&bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"&
&property name="exceptionMappings"&
&prop key="org.springframework.dao.DataAccessException"&dataAccessFailure&/prop&
&prop key="org.springframework.transaction.TransactionException"&dataAccessFailure&/prop&
&/property&
- This bean configures the 'prefix' and 'suffix' properties of
- InternalResourceViewResolver, which resolves logical view names
- returned by Controllers. For example, a logical view name of "vets"
- will be mapped to "/WEB-INF/jsp/vets.jsp".
&bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"/&
- Message source for this context, loaded from localized "messages_xx" files.
- Could also reside in the root application context, as it is generic,
- but is currently just used within PetClinic's web tier.
&bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages"/&
在WEB-INF下面的jdbc.properties文件如下:
# To change this template, choose Tools | Templates
# and open the template in the editor.
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=scott
jdbc.password=tiger
hibernate.generate_statistics=true
hibernate.show_sql=true
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
配置大致就这些,下面给出连接hibernate的接口
* To change this template, choose Tools | Templates
* and open the template in the editor.
package com.cssweb.zszq.
import java.util.C
import org.springframework.dao.DataAccessE
import com.cssweb.zszq.lmdz.pojo.K
import com.cssweb.zszq.lmdz.pojo.LmdzN
* @author HUJUN
public interface Clinic {
Collection&LmdzNew& findLmdzs(String fundid) throws DataAccessE
void save(String fundid, String[] no) throws DataAccessE
int delete(String fundid) throws DataAccessE
Khzl findKh(String clientId) throws DataAccessE
int updateTelById(String fundid, String mobile) throws DataAccessE
连接hibernate的service类
* To change this template, choose Tools | Templates
* and open the template in the editor.
package com.cssweb.zszq.lmdz.
import java.util.C
import org.hibernate.S
import org.hibernate.SessionF
import org.hibernate.T
import org.springframework.beans.factory.annotation.A
import org.springframework.transaction.annotation.T
import com.cssweb.zszq.lmdz.C
import com.cssweb.zszq.lmdz.pojo.K
import com.cssweb.zszq.lmdz.pojo.LmdzN
* @author HUJUN
public class HibernateClinic implements Clinic {
@Autowired
private SessionFactory sessionF
@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public Collection&LmdzNew& findLmdzs(String fundid) {
return sessionFactory.getCurrentSession().createQuery("from LmdzNew lmdz where lmdz.khNum = :fundid")
.setString("fundid", fundid).list();
public void save(String fundid, String[] no) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for (int i = 0; i & no. i++) {
LmdzNew lmdzNes = new LmdzNew(fundid, Integer.parseInt(no[i]));
session.save(lmdzNes);
if (i % 20 == 0) {
session.flush();
session.clear();
tx.commit();
session.close();
public int delete(String fundid) {
return sessionFactory.openSession().createQuery("delete from LmdzNew lmdz where lmdz.khNum = :fundid")
.setString("fundid", fundid).executeUpdate();
@Transactional(readOnly = true)
public Khzl findKh(String clientId) {
return (Khzl) sessionFactory.openSession().load(Khzl.class, clientId);
public int updateTelById(String fundid, String mobile) {
return sessionFactory.openSession().createQuery("update Khzl set mobileTel = :mobile where clientId = :fundid")
.setString("fundid", fundid)
.setString("mobile", mobile)
.executeUpdate();
再来看action这一层的东西:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package com.cssweb.zszq.lmdz.
import java.io.OutputStreamW
import java.io.PrintW
import java.util.C
import java.util.I
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.C
import org.springframework.web.bind.annotation.PathV
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import mon.util.CollectionD
import com.cssweb.zszq.lmdz.C
import com.cssweb.zszq.lmdz.pojo.K
import com.cssweb.zszq.lmdz.pojo.LmdzN
* @author HUJUN
@Controller
@RequestMapping("/zszqsms")
public class LmdzForm {
private final C
@Autowired
public LmdzForm(Clinic clinic) {
this.clinic =
@RequestMapping(value="/{fundid}", method = RequestMethod.GET)
public void get(HttpServletRequest request, HttpServletResponse response, @PathVariable("fundid") String fundid) throws Exception {
System.out.println("&&&&&&&&&&getList&&&&&&&&&&&&&&"+fundid);
StringBuilder msg = new StringBuilder();
Khzl khzl = this.clinic.findKh(fundid);
if(khzl!=null) {
Collection&LmdzNew& lm = CollectionData.getLmList();
Collection&LmdzNew& results = this.clinic.findLmdzs(fundid);
Iterator&LmdzNew& it = lm.iterator();
String json = "{total:"+lm.size()+",root:[";
int i = 0;
while(it.hasNext()) {
LmdzNew lmdz = it.next();
lmdz.setState(1);
json += "{lmid:'" + lmdz.getLmNum() + "',lmname:'" + lmdz.getLmName() + "',lmstate:'" + lmdz.getState() + "'}";
if (i != lm.size() - 1) {
json += ",";
json += "]}";
msg.append("{/"msg/":/""+json+"/"}");
msg.append("{/"msg/":/"帐号不存在/"}");
printData(response, msg);
@RequestMapping(value = "/{fundid}/{no}", method = RequestMethod.POST)
public void save(HttpServletRequest request, HttpServletResponse response, @PathVariable("fundid") String fundid,
@PathVariable("no") String no) throws Exception {
System.out.println(fundid + "&&&&&&&&&&save&&&&&&&&&&&&&&"+no);
StringBuilder msg = new StringBuilder();
this.clinic.save(fundid, no.split(","));
msg.append("{/"msg/":/"成功/"}");
printData(response, msg);
@RequestMapping(value = "/{fundid}/{no}", method = RequestMethod.PUT)
public void update(HttpServletRequest request, HttpServletResponse response, @PathVariable("fundid") String fundid,
@PathVariable("no") String no) throws Exception {
System.out.println(fundid + "&&&&&&&&&&update&&&&&&&&&&&&&&"+no);
StringBuilder msg = new StringBuilder();
int i = this.clinic.updateTelById(fundid, no);
msg.append("{/"msg/":/"成功/"}");
msg.append("{/"msg/":/"失败/"}");
printData(response, msg);
@RequestMapping(value = "/{fundid}", method = RequestMethod.DELETE)
public void delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("fundid") String fundid)
throws Exception {
System.out.println("&&&&&&&&&&delete&&&&&&&&&&&&&&"+fundid);
StringBuilder msg = new StringBuilder();
int i = this.clinic.delete(fundid);
msg.append("{/"msg/":/"成功/"}");
msg.append("{/"msg/":/"失败/"}");
printData(response, msg);
private void printData(HttpServletResponse response, StringBuilder msg){
response.setContentType("text/charset=utf-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
out.println( msg );
out.close();
} catch (Exception e) {
e.printStackTrace();
最后还有个POJO类,呵呵:
package com.cssweb.zszq.lmdz.
* LmdzNew entity. @author MyEclipse Persistence Tools
public class LmdzNew implements java.io.Serializable {
private static final long serialVersionUID = -9588033L;
private String khN
private int lmN
private String lmN
// Constructors
/** default constructor */
public LmdzNew() {
/** full constructor */
public LmdzNew(String khNum, int lmNum) {
this.khNum = khN
this.lmNum = lmN
public String getKhNum() {
return this.khN
public void setKhNum(String khNum) {
this.khNum = khN
public int getLmNum() {
return this.lmN
public void setLmNum(int lmNum) {
this.lmNum = lmN
public String getLmName() {
return lmN
public void setLmName(String lmName) {
this.lmName = lmN
public int getState() {
public void setState(int state) {
this.state =
public boolean equals(Object other) {
if ((this == other))
if ((other == null))
public int hashCode() {
int result = 17;
result = 37 * result
+ (getKhNum() == null ? 0 : this.getKhNum().hashCode());
好了,所有的源代码都贴出来了。整个服务端的程序可以跑在tomcat下做测试。接下来我们只需要提供rest客户端的接口让别的应用调用即可。下面再给出个调用的demo。这个项目比较简单。
还望大家多多指教,大家互相学习学习。
package com.cssweb.zszq.
import java.io.BufferedR
import java.io.IOE
import java.io.InputStreamR
import java.net.HttpURLC
import java.net.URL;
public class ClientTest {
public static void main(String[] args) throws IOException {
* 查询栏目定制
* 为资金帐号
public static void select() {
URL url = new URL("http://localhost:8080/zszqrestsms/zszqsms/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "text/json");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
while ((line = rd.readLine()) != null) {
System.out.println(line);
rd.close();
} catch (Exception e) {
System.out.println("Error" + e);
* 删除定制栏目
* 为资金帐号
public static void delete() {
URL url = new URL("http://localhost:8080/zszqrestsms/zszqsms/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("DELETE");
conn.setRequestProperty("Content-Type", "text/json");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
while ((line = rd.readLine()) != null) {
System.out.println(line);
rd.close();
} catch (Exception e) {
System.out.println("Error" + e);
* 修改手机号码
* 为资金帐号
public static void update() {
URL url = new URL("http://localhost:8080/zszqrestsms/zszqsms/2345677");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "text/json");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
while ((line = rd.readLine()) != null) {
System.out.println(line);
rd.close();
} catch (Exception e) {
System.out.println("Error" + e);
* 保存定制的栏目
* 为资金帐号
public static void save() {
URL url = new URL("http://localhost:8080/zszqrestsms/zszqsms/,2,3,4");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/json");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
while ((line = rd.readLine()) != null) {
System.out.println(line);
rd.close();
} catch (Exception e) {
System.out.println("Error" + e);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:156277次
积分:2118
积分:2118
排名:第14973名
原创:45篇
转载:23篇
评论:76条
(1)(1)(2)(1)(2)(1)(2)(1)(5)(2)(2)(1)(1)(4)(2)(2)(3)(4)(1)(1)(1)(3)(3)(1)(1)(1)(1)(8)(8)(2)

我要回帖

更多关于 restful 例子 的文章

 

随机推荐