一. RestFul WebService的创建:
本例使用SpringMVC来写RestFul Web Service。
1.创建【Dynamic Web Prject】
2.添加代码:
RestFul.java:
[java]view plaincopy
- packagecom.webservice;
- importjava.io.OutputStreamWriter;
- importjava.io.PrintWriter;
- importjava.util.ArrayList;
- importjava.util.List;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- importnet.sf.json.JSONArray;
- importorg.springframework.stereotype.Controller;
- importorg.springframework.web.bind.annotation.PathVariable;
- importorg.springframework.web.bind.annotation.RequestMapping;
- importorg.springframework.web.bind.annotation.RequestMethod;
- importorg.springframework.web.bind.annotation.RequestParam;
- @Controller
- @RequestMapping(value="/getData")
- publicclassRestFul{
- //http://localhost:8080/RestWebService/getData?userName=sun方式的调用
- @RequestMapping
- publicvoidprintData1(HttpServletRequestrequest,HttpServletResponseresponse,
- @RequestParam(value="userName",defaultValue="User")Stringname){
- Stringmsg="Welcome"+name;
- printData(response,msg);
- }
- //http://localhost:8080/RestWebService/getData/Sun/Royi方式的调用
- @RequestMapping(value="/{firstName}/{lastName}")
- publicvoidprintData2(HttpServletRequestrequest,HttpServletResponseresponse,
- @PathVariableStringfirstName,@PathVariableStringlastName){
- Stringmsg="Welcome"+firstName+""+lastName;
- printData(response,msg);
- }
- //转换成HTML形式返回
- privatevoidprintData(HttpServletResponseresponse,Stringmsg){
- try{
- response.setContentType("text/html;charset=utf-8");
- response.setCharacterEncoding("UTF-8");
- PrintWriterout=newPrintWriter(newOutputStreamWriter(response.getOutputStream(),"UTF-8"));
- out.println(msg);
- out.close();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- //http://localhost:8080/RestWebService/getData/json?item=0方式的调用
- @RequestMapping(value="/json")
- publicvoidprintData3(HttpServletRequestrequest,HttpServletResponseresponse,
- @RequestParam(value="item",defaultValue="0")Stringitem){
- printDataJason(response,item);
- }
- //http://localhost:8080/RestWebService/getData/json/1方式的调用
- @RequestMapping(value="/json/{item}")
- publicvoidprintData4(HttpServletRequestrequest,HttpServletResponseresponse,
- @PathVariableStringitem){
- printDataJason(response,item);
- }
- //JSON格式化
- privatevoidprintDataJason(HttpServletResponseresponse,Stringitem){
- try{
- response.setContentType("text/html;charset=utf-8");
- response.setCharacterEncoding("UTF-8");
- PrintWriterout=newPrintWriter(newOutputStreamWriter(response.getOutputStream(),"UTF-8"));
- List<UserInfo>uiList=newArrayList<UserInfo>();
- for(inti=0;i<3;i++)
- {
- UserInfoui=newUserInfo();
- ui.ID=i;
- ui.Name="SUN"+i;
- ui.Position="Position"+i;
- uiList.add(ui);
- if(!item.equals("0")){
- JSONArrayjsonArr=JSONArray.fromObject(uiList.get(0));
- out.println(jsonArr);
- }
- else{
- JSONArrayjsonArr=JSONArray.fromObject(uiList);
- out.println(jsonArr);
- //out.println(uiList);
- }
- out.close();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- }
UserInfo.java
[java]view plaincopy
- packagecom.webservice;
- publicclassUserInfo{
- IntegerID;
- StringName;
- StringPosition;
- publicIntegergetID(){
- returnID;
- }
- publicvoidsetID(IntegeriD){
- ID=iD;
- }
- publicStringgetName(){
- returnName;
- }
- publicvoidsetName(Stringname){
- Name=name;
- }
- publicStringgetPosition(){
- returnPosition;
- }
- publicvoidsetPosition(Stringposition){
- Position=position;
- }
- }
3.SpringMVC框架需要修改一些配置:
web.xml
[html]view plaincopy
- <?xmlversion="1.0"encoding="UTF-8"?>
- <web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0">
- <display-name>RestWebService</display-name>
- <!--spring-->
- <servlet>
- <servlet-name>springMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
- </init-param>
- <load-on-startup>2</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springMVC</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- </web-app>
[html]view plaincopy
- springmvc-servlet.xml:
- <prename="code"><?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
- <context:annotation-config/>
- <mvc:default-servlet-handler/>
- <!--默认访问跳转到登录页面-->
- <mvc:view-controllerpath="/"view-name="redirect:/getData"/>
- <!--Scanstheclasspathofthisapplicationfor@Componentstodeployasbeans-->
- <context:component-scanbase-package="com.webservice">
- <context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- <!--采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解-->
- <bean>
- <propertyname="messageConverters">
- <list>
- <refbean="stringHttpMessageConverter"/>
- <refbean="jsonHttpMessageConverter"/>
- </list>
- </property>
- </bean>
- <bean>
- <propertyname="supportedMediaTypes">
- <list>
- <value>text/plain;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- <!--Configuresthe@Controllerprogrammingmodel-->
- <mvc:annotation-driven/>
- </beans>
rest-servlet.xml
[html]view plaincopy
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beans:beansxmlns="http://www.springframework.org/schema/mvc"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:beans="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd
- http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd">
- <!--EnablestheSpringMVC@Controllerprogrammingmodel-->
- <annotation-driven/>
- <!--forprocessingrequestswithannotatedcontrollermethodsandsetMessageConvertorsfromthelistofconvertors-->
- <beans:bean>
- <beans:propertyname="messageConverters">
- <beans:list>
- <beans:refbean="jsonMessageConverter"/>
- </beans:list>
- </beans:property>
- </beans:bean>
- <!--ToconvertJSONtoObjectandviceversa-->
- <beans:bean>
- </beans:bean>
- <context:component-scanbase-package="net.javaonline.spring.restful"/>
- </beans:beans>
4.用到的Jar包:
[plain]view plaincopy
- commons-beanutils-1.8.0.jar
- commons-collections-3.2.1.jar
- commons-lang-2.5.jar
- commons-logging-1.1.1.jar
- commons-logging-1.1.3.jar
- ezmorph-1.0.6.jar
- jackson-all-1.9.0.jar
- jackson-annotations-2.2.1.jar
- jackson-core-2.2.1.jar
- jackson-core-asl-1.7.1.jar
- jackson-core-asl-1.8.8.jar
- jackson-databind-2.2.1.jar
- jackson-jaxrs-1.7.1.jar
- jackson-mapper-asl-1.7.1.jar
- jackson-mapper-asl-1.8.8.jar
- jackson-module-jaxb-annotations-2.2.1.jar
- json-lib-2.4-jdk15.jar
- jstl-1.2.jar
- servlet-api-2.5.jar
- spring-aop-3.2.4.RELEASE.jar
- spring-beans-3.2.4.RELEASE.jar
- spring-context-3.2.4.RELEASE.jar
- spring-core-3.2.4.RELEASE.jar
- spring-expression-3.2.4.RELEASE.jar
- spring-jdbc-3.2.4.RELEASE.jar
- spring-orm-3.2.4.RELEASE.jar
- spring-test-3.2.4.RELEASE.jar
- spring-tx-3.2.4.RELEASE.jar
- spring-web-3.2.4.RELEASE.jar
- spring-webmvc-3.2.4.RELEASE.jar
5.将RestWebService项目部署到Tomcat即可。
(部署方法略)
二. RestFul WebService的调用:
方法1:用HttpClient调用:
1.创建【Java Project】:
方法1:用HttpClient调用:
1.创建【Java Project】:
Rest.java:
[java]view plaincopy
- packagecom.httpclientforrest;
- importjava.util.ArrayList;
- importjava.util.List;
- importorg.apache.http.HttpEntity;
- importorg.apache.http.NameValuePair;
- importorg.apache.http.client.entity.UrlEncodedFormEntity;
- importorg.apache.http.client.methods.CloseableHttpResponse;
- importorg.apache.http.client.methods.HttpPost;
- importorg.apache.http.impl.client.CloseableHttpClient;
- importorg.apache.http.impl.client.HttpClients;
- importorg.apache.http.message.BasicNameValuePair;
- importorg.apache.http.util.EntityUtils;
- publicclassRest{
- publicstaticvoidmain(String[]args){
- List<NameValuePair>params=newArrayList<NameValuePair>();
- params.add(newBasicNameValuePair("userName","Sun"));
- Stringurl="http://localhost:8080/RestWebService/getData";
- System.out.println(getRest(url,params));
- }
- publicstaticStringgetRest(Stringurl,List<NameValuePair>params){
- //创建默认的httpClient实例.
- CloseableHttpClienthttpclient=HttpClients.createDefault();
- //创建httppost
- HttpPosthttppost=newHttpPost(url);
- UrlEncodedFormEntityuefEntity;
- try{
- uefEntity=newUrlEncodedFormEntity(params,"UTF-8");
- httppost.setEntity(uefEntity);
- CloseableHttpResponseresponse=httpclient.execute(httppost);
- HttpEntityentity=response.getEntity();
- Stringjson=EntityUtils.toString(entity,"UTF-8");
- intcode=response.getStatusLine().getStatusCode();
- if(code==200||code==204){
- returnjson;
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
- return"";
- }
- }
执行结果:
[plain]view plaincopy
- WelcomeSun
[html]view plaincopy
- 方法2:在JSP页面用JQuery调用:
- 1.创建【DynamicWebPrject】
- 相关配置文件和创建RestFulWebService相同。
- 2.建一个JSP页面:
- rest.jsp:
- <prename="code"><%@pagelanguage="java"import="java.util.*"pageEncoding="ISO-8859-1"%>
- <%
- Stringpath=request.getContextPath();
- StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
- <html>
- <head>
- <basehref="<%=basePath%>">
- <title>RestfilWebService</title>
- <metahttp-equiv="pragma"content="no-cache">
知识推荐
- 应用开发者必须了解的Kubernetes网络二三事
- web基础,用html元素制作web页面
- riot.js教程【一】简介
- 基于display:table的CSS布局
- 2017前端面试题之Html篇(1)
- CSS实现四种loading动画效果
- hibernate入门
- Vue.js常用指令汇总(v-if//v-show//v-else//v-for//v-bind//v-on等)
- php 文档操作
- webacula root登陆密码错误解决方案
- Charles关于Https SSLHandshake解决备忘录
- html、css和js原生写一个模态弹出框,顺便解决父元素半透明子元素不透明效果
- 使用 jquery 替换 网页某部分的图片内容
- kubernetes通过私有仓库harbor拉取镜像
- Lucene查看分词结果
- Golang开发支持平滑升级(优雅重启)的HTTP服务
- php 类中的变量的定义
- Web代理工具NProxy