webService与Controller的用法
Posted 文刀水告
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webService与Controller的用法相关的知识,希望对你有一定的参考价值。
一. RestFul WebService的创建:
本例使用SpringMVC来写RestFul Web Service。
1.创建【Dynamic Web Prject】
2.添加代码:
RestFul.java:
- package com.webservice;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import net.sf.json.JSONArray;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- @Controller
- @RequestMapping(value = "/getData")
- public class RestFul {
- // http://localhost:8080/RestWebService/getData?userName=sun 方式的调用
- @RequestMapping
- public void printData1(HttpServletRequest request, HttpServletResponse response,
- @RequestParam(value="userName", defaultValue="User") String name) {
- String msg = "Welcome "+ name;
- printData(response, msg);
- }
- // http://localhost:8080/RestWebService/getData/Sun/Royi 方式的调用
- @RequestMapping(value = "/{firstName}/{lastName}")
- public void printData2(HttpServletRequest request, HttpServletResponse response,
- @PathVariable String firstName, @PathVariable String lastName) {
- String msg = "Welcome "+ firstName + " " + lastName;
- printData(response, msg);
- }
- // 转换成html形式返回
- private void printData(HttpServletResponse response, String msg) {
- try {
- response.setContentType("text/html;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();
- }
- }
- // http://localhost:8080/RestWebService/getData/json?item=0 方式的调用
- @RequestMapping(value = "/json")
- public void printData3(HttpServletRequest request, HttpServletResponse response,
- @RequestParam(value="item", defaultValue="0") String item) {
- printDataJason(response, item);
- }
- // http://localhost:8080/RestWebService/getData/json/1 方式的调用
- @RequestMapping(value = "/json/{item}")
- public void printData4(HttpServletRequest request, HttpServletResponse response,
- @PathVariable String item) {
- printDataJason(response, item);
- }
- // JSON格式化
- private void printDataJason(HttpServletResponse response, String item) {
- try {
- response.setContentType("text/html;charset=utf-8");
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
- List<UserInfo> uiList = new ArrayList<UserInfo>();
- for (int i=0; i<3; i++)
- {
- UserInfo ui = new UserInfo();
- ui.ID = i;
- ui.Name = "SUN" + i;
- ui.Position = "Position" + i;
- uiList.add(ui);
- if (!item.equals("0")){
- JSONArray jsonArr = JSONArray.fromObject(uiList.get(0));
- out.println(jsonArr);
- }
- else{
- JSONArray jsonArr = JSONArray.fromObject(uiList);
- out.println(jsonArr);
- //out.println(uiList);
- }
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
UserInfo.java
- package com.webservice;
- public class UserInfo{
- Integer ID;
- String Name;
- String Position;
- public Integer getID() {
- return ID;
- }
- public void setID(Integer iD) {
- ID = iD;
- }
- public String getName() {
- return Name;
- }
- public void setName(String name) {
- Name = name;
- }
- public String getPosition() {
- return Position;
- }
- public void setPosition(String position) {
- Position = position;
- }
- }
3.SpringMVC框架需要修改一些配置:
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns: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/javaee http://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>
- springmvc-servlet.xml:
- <pre name="code" class="html"><?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:mvc="http://www.springframework.org/schema/mvc"
- 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
- <context:annotation-config/>
- <mvc:default-servlet-handler/>
- <!-- 默认访问跳转到登录页面 -->
- <mvc:view-controller path="/" view-name="redirect:/getData" />
- <!-- Scans the classpath of this application for @Components to deploy as beans -->
- <context:component-scan base-package="com.webservice">
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- <!-- 采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解 -->
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="messageConverters">
- <list>
- <ref bean="stringHttpMessageConverter" />
- <ref bean="jsonHttpMessageConverter" />
- </list>
- </property>
- </bean>
- <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
- <property name ="supportedMediaTypes">
- <list>
- <value>text/plain;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- <!-- Configures the @Controller programming model -->
- <mvc:annotation-driven/>
- </beans>
rest-servlet.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans:beans xmlns="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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- Enables the Spring MVC @Controller programming model -->
- <annotation-driven />
- <!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->
- <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
- <beans:property name="messageConverters">
- <beans:list>
- <beans:ref bean="jsonMessageConverter"/>
- </beans:list>
- </beans:property>
- </beans:bean>
- <!-- To convert JSON to Object and vice versa -->
- <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
- </beans:bean>
- <context:component-scan base-package="net.javaonline.spring.restful" />
- </beans:beans>
4.用到的Jar包:
- 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:
- package com.httpclientforrest;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- public class Rest{
- public static void main(String[] args){
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("userName", "Sun"));
- String url = "http://localhost:8080/RestWebService/getData";
- System.out.println(getRest(url, params));
- }
- public static String getRest(String url,List<NameValuePair> params){
- // 创建默认的httpClient实例.
- CloseableHttpClient httpclient = HttpClients.createDefault();
- // 创建httppost
- HttpPost httppost = new HttpPost(url);
- UrlEncodedFormEntity uefEntity;
- try{
- uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
- httppost.setEntity(uefEntity);
- CloseableHttpResponse response = httpclient.execute(httppost);
- HttpEntity entity = response.getEntity();
- String json= EntityUtils.toString(entity, "UTF-8");
- int code= response.getStatusLine().getStatusCode();
- if(code==200 ||code ==204){
- return json;
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return "";
- }
- }
执行结果:
- Welcome Sun
- 方法2:在JSP页面用JQuery调用:
- 1.创建【Dynamic Web Prject】
- 相关配置文件和创建RestFulWebService相同。
- 2.建一个JSP页面:
- rest.jsp:
- <pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>Restfil WebService</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is Restfil WebService Test">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <div>
- <button id="callPrintDataWithoutParam">PrintDataWithoutParam</button>
- <button id="callPrintDataWithParam">PrintDataWithParam</button>
- <button id="callJsonWithoutParam">JsonWithoutParam</button>
- <button id="callJsonWithParam">JsonWithParam</button>
- </div>
- <div id=‘divContext‘>
- </div>
- </body>
- <script src="./script/jquery-1.8.3.min.js" type="text/javascript"></script>
- <script type="text/javascript">
- $(function(){
- $(‘#callPrintDataWithoutParam‘).click(function(event){
- document.getElementById("divContext").innerHTML = "";
- var webserviceUrl="http://localhost:8080/RestWebService/getData" + "?userName=Sun";
- //var webserviceUrl="http://localhost:8080/RestWebService/getData";
- $.ajax({
- type: ‘POST‘,
- contentType: ‘application/json‘,
- url: webserviceUrl,
- //data: {"userName":"Sun"},
- dataType: ‘html‘,
- success: function (result) {
- document.getElementById("divContext").innerHTML = result;
- },
- error:function(){
- alert("error");
- }
- });
- //取消事件的默认行为。比如:阻止对表单的提交。IE下不支持,需用window.event.returnValue = false;来实现
- event.preventDefault();
- });
- $(‘#callPrintDataWithParam‘).click(function(event){
- document.getElementById("divContext").innerHTML = "";
- var webserviceUrl="http://localhost:8080/RestWebService/getData" + "/Sun/Royi";
- $.ajax({
- type: ‘POST‘,
- contentType: ‘application/json‘,
- url: webserviceUrl,
- //data: "{firstName:Sun,lastName:Royi}",
- dataType: ‘html‘,
- success: function (result) {
- document.getElementById("divContext").innerHTML = result;
- },
- error:function(){
- alert("error");
- }
- });
- event.preventDefault();
- });
- $(‘#callJsonWithoutParam‘).click(function(event){
- document.getElementById("divContext").innerHTML = "";
- $.ajax({
- type: ‘POST‘,
- contentType: ‘application/json‘,
- url: ‘http://localhost:8080/RestWebService/getData/json‘,
- data: "{}",
- dataType: ‘json‘,
- success: function (result) {
- document.getElementById("divContext").innerHTML = "json:" + "<br>";
- document.getElementById("divContext").innerHTML += result + "<br><br>";
- document.getElementById("divContext").innerHTML += "Changed:" + "<br>";
- for(i=0;i<result.length;i++){
- document.getElementById("divContext").innerHTML += "ID:" + result[i].ID + "<br>";
- document.getElementById("divContext").innerHTML += "Name:" + result[i].name + "<br>";
- document.getElementById("divContext").innerHTML += "position:" + result[i].position + "<br>";
- document.getElementById("divContext").innerHTML += "-------------------------------<br>";
- }
- },
- error:function(){
- alert("error");
- }
- });
- event.preventDefault();
- });
- $(‘#callJsonWithParam‘).click(function(event){
- document.getElementById("divContext").innerHTML = "";
- $.ajax({
- type: ‘POST‘,
- contentType: ‘application/json‘,
- url: ‘http://localhost:8080/RestWebService/getData/json/1‘,
- //data: ‘{"item":1}‘,
- dataType: ‘html‘,
- success: function (result) {
- document.getElementById("divContext").innerHTML = result;
- },
- error:function(){
- alert("error");
- }
- });
- event.preventDefault();
- });
- });
- </script>
- </html>
- </span>
执行结果:PrintDataWithoutParam:
- Welcome Sun
- PrintDataWithParam:
- <pre name="code" class="plain">Welcome Sun Royi
- json:
- [object Object],[object Object],[object Object]
- Changed:
- ID:0
- Name:SUN0
- position:Position0
- -------------------------------
- ID:1
- Name:SUN1
- position:Position1
- -------------------------------
- ID:2
- Name:SUN2
- position:Position2
- -------------------------------
JsonWithParam:
- [{"ID":0,"name":"SUN0","position":"Position0"}]
相关文章:
WSDL WebService和RestFul WebService的个人理解:
http://blog.csdn.net/sunroyi666/article/details/51939802
WSDL WebService的创建和使用实例:
http://blog.csdn.net/sunroyi666/article/details/51917991
WSDL WebService和RestFul WebService的Sample代码:
http://download.csdn.net/detail/sunroyi666/9577143
转载:http://blog.csdn.net/sunroyi666/article/details/51918675
以上是关于webService与Controller的用法的主要内容,如果未能解决你的问题,请参考以下文章
webService 客户端调用及异常信息First Element must contain the local name, Envelope , but found definitions(示例代
java WebServiceMockImpl,单个系统范围的WebService Mock,带有用法示例。
Application windows are expected to have a root view controller at the end of application launch(示例代