jsp实现的webservice的简单实例

Prediction类(javabean)

package predictions;
import java.io.Serializable;
/**
 * Created by AlexY on 2016/6/28.
 */
public class Prediction implements Serializable {
    private static final long serialVersionUID = 7570089771880396982L;
    private String who;  // 人
    private String what; //他的prediction
    public Prediction() {
    }
    public String getWhat() {
        return what;
    }
    public void setWhat(String what) {
        this.what = what;
    }
    public String getWho() {
        return who;
    }
    public void setWho(String who) {
        this.who = who;
    }
}

Predictions类(javabean)

从predictions.db文件中读取文本内容到predictions数组,然后将数组序列化为xml

package predictions;
import javax.servlet.ServletContext;
import java.beans.XMLEncoder;
import java.io.*;
/**
 * Created by AlexY on 2016/6/28.
 */
public class Predictions {
    private int n = 32;
    private Prediction[] predictions;
    private ServletContext servletContext;
    public Predictions() {
    }
    //    Servlet被用来从war文件中的text文件中读取数据
    public ServletContext getServletContext() {
        return servletContext;
    }
    public void setServletContext(ServletContext sctx) {
        this.servletContext = sctx;
    }
    //空实现
    public void setPredictions(Prediction[] ps){}
//    getPredictions返回一个表示Predictions 数组的xml文件
    public String getPredictions(){
//        检测是否设置了ServletContext
        if ( getServletContext() == null){
            return null;
        }
//        检测是否已经读取了数据
        if ( predictions ==null){
            populate();
        }
//        将Predictions数组转换为xml文档
        return toXML();
    }
//      将Predictions数组转换为xml文档
    private String toXML() {
        String xml = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLEncoder encoder = new XMLEncoder(out);
        encoder.writeObject(predictions);  //序列化为xml
        encoder.close();
        xml = out.toString();
        return xml;
    }
//    将文本中的内容读取到predictions数组
    private void populate() {
        String filename = "/WEB-INF/data/predictions.db";
        InputStream in = servletContext.getResourceAsStream(filename);
//        将文本文件中的内容读取到predictions数组
        if ( null != in){
//            因为文件中每条记录就是一行,而每一行who和what字段是通过"!"分隔的
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(isr);
            String line = null;
            int i = 0;
            try {
                predictions = new Prediction[n];
                while ( null != ( line = reader.readLine())){
                    String[] parts =  line.split("!");
                    Prediction p = new Prediction();
                    p.setWho(parts[0]);
                    p.setWhat(parts[1]);
                    predictions[i++] = p;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

predictions.db:

被读取的文本文件,一条记录一行,每行的内容都有"!"分隔为两部分。

Cornelius Tillman!Managed holistic contingency will grow killer action-items.
Conner Kulas!Vision-oriented zero administration time-frame will generate back-end interfaces.
Loraine Ryan!Triple-buffered scalable function will productize visionary infomediaries.
Patricia Zulauf!Reactive radical knowledge base will aggregate extensible vortals.
River Wiza!Face to face client-server pricing structure will whiteboard robust communities.
Jarred Wehner!Future-proofed 5th generation protocol will strategize web-enabled networks.
Emily Roob!Cross-group fresh-thinking encoding will reinvent dot-com systems.
Elvis Ernser!Customizable assymetric database will visualize virtual action-items.
Kathryn Hilpert!User-centric non-volatile open architecture will iterate world-class vortals.
Tanner Dietrich!Enhanced zero tolerance system engine will evolve turn-key deliverables.
Linnie Funk!Distributed dynamic moratorium will iterate magnetic e-commerce.
Emery Ward!Synergistic demand-driven functionalities will visualize compelling vortals.
Craig Leuschke!Robust intermediate extranet will facilitate best-of-breed synergies.
Shayna Lehner!Digitized optimal conglomeration will exploit proactive relationships.
Hollis McCullough!Universal fault-tolerant architecture will synthesize bleeding-edge channels.
Mina Hayes!Cloned assymetric intranet will enable innovative functionalities.
River Friesen!Decentralized 24/7 hub will target robust web-readiness.
Carmel Becker!Synergistic disintermediate policy will expedite back-end experiences.
Bartholome Walsh!Triple-buffered didactic emulation will visualize integrated channels.
Russel Robel!Configurable intangible alliance will scale sexy ROI.
Charlene Mertz!Triple-buffered neutral collaboration will incubate B2B deliverables.
Letitia Pacocha!User-centric multi-state success will transform proactive convergence.
Lottie Marks!Open-source multi-tasking time-frame will monetize rich partnerships.
Kaden Crona!Optional static definition will unleash dynamic e-tailers.
Everardo Lind!De-engineered systematic emulation will deploy out-of-the-box partnerships.
Lilyan Thompson!Synergistic 24/7 website will transition 24/7 methodologies.
Alessia O'Connell!Reactive value-added middleware will engineer next-generation partnerships.
Reymundo Champlin!Self-enabling reciprocal synergy will generate seamless portals.
Immanuel Bergstrom!Assimilated intermediate superstructure will drive vertical methodologies.
Dahlia Robel!Proactive demand-driven open architecture will innovate impactful networks.
Deven Blanda!Balanced clear-thinking utilisation will expedite collaborative initiatives.
Hiram Gulgowski!Versatile tangible application will maximize rich e-business.
predictions.jsp:

显示生成xml文档,这里去掉了html的body等内容。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="predictions.Prediction" %>
    <jsp:useBean id="preds" class="predictions.Predictions"   > </jsp:useBean>
    <%
        String verb = request.getMethod();
//        判断客户端http请求的类型
        if (!verb.equalsIgnoreCase("GET")){
            response.sendError(response.SC_METHOD_NOT_ALLOWED,"只允许GET请求");
        }else {
//            设置prediction的ervletContext
            preds.setServletContext(application);
//            输出xml到网页
            out.print(preds.getPredictions());
        }
 %>

测试:使用curl访问:

$ curl --request GET http://localhost:8080/predictions.jsp

时间: 2024-11-29 22:43:15

jsp实现的webservice的简单实例的相关文章

js跨域调用WebService的简单实例_AJAX相关

步骤1.   在web.config中的system.web节点里加入 <!--此节点可允许脚本跨域调用webservice--> <webServices> <protocols> <add name="HttpPost"/> <add name="HttpGet"/> </protocols> </webServices> <!--此节点可允许脚本跨域调用webservic

js跨域调用WebService的简单实例

步骤1.   在web.config中的system.web节点里加入 <!--此节点可允许脚本跨域调用webservice--> <webServices> <protocols> <add name="HttpPost"/> <add name="HttpGet"/> </protocols> </webServices> <!--此节点可允许脚本跨域调用webservic

关于webservice的异步调用简单实例

web|异步 关于webservice的异步调用简单实例无论在任何情况下,被调用方的代码无论是被异步调用还是同步调用的情况下,被调用方的代码都是一样的, 下面,我们就以异步调用一个webservice 为例作说明.这是一个webservice <WebMethod(Description:="试验")> _ Public Function delCurTable(ByVal tbName As String) As Boolean Try Return True Catch

PHP调用.NET的WebService 简单实例

 这篇文章主要介绍了使用PHP调用.NET的WebService的一个简单实例,十分的简单,有需要的小伙伴可以自己扩展下,如有疑问请留言.     创建一个C#的web service,这个就不多说了,我用vs2008的wizard创建了一个最简单的,让它运行在:http://localhost/webservice1/service1.asmx 其中有个web method像这样的:   代码如下: [WebMethod] public string HelloWorld() { return

PHP调用JAVA的WebService简单实例

 本篇文章主要是对PHP调用JAVA的WebService简单实例进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助 使用PHP调用JAVA语言开发的WebService. 客户端提交两个String类型的参数,服务端返回一个对象类型. 服务端使用AXIS-1.4作为SOAP引擎.客户端为PHP5.2.9,使用NuSOAP作为SOAP引擎.   服务端   对象类    代码如下: import java.io.Serializable;   public class Person imp

jsp页面中两种方法显示当前时间的简单实例_JSP编程

在jsp页面实现显示当前的日期时间,我们可以用一下两种方式实现: 1. 通过在jsp页面添加Java代码实现,主要代码如下所示 java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); java.util.Date currentTime = new java.util.Date(); String time = simpleDateForm

JQuery Ajax WebService传递参数的简单实例_jquery

Asp.NET中利用jQuery实现Ajax时,在服务器端可以使用aspx,ashx,以及WebService等方式.最近研究了一下WebService方式,jQuery Ajax 方法调用 jQuery Ajax方法调用 Asp.Net WebService 的详细实例代码这篇帖子给出了很详细的例子,不过没有给出详细解释.其中有几个细节问题开始没注意,费老劲才调通: 1)客户端data数据中的key字段名称必须和服务器端方法参数严格一致. 如客户端: //有参数调用 $(document).r

PHP调用.NET的WebService 简单实例_php实例

创建一个C#的web service,这个就不多说了,我用vs2008的wizard创建了一个最简单的,让它运行在:http://localhost/webservice1/service1.asmx 其中有个web method像这样的: 复制代码 代码如下: [WebMethod] public string HelloWorld() {     return "Hello World"; } ok,一切就绪.在某php文件中如下写法: php5本身就支持SOAP调用Web Ser

jsp输出九九乘法表的简单实例_JSP编程

<% String st = ""; for(int i = 1; i <= 9; i++){ for(int j = 1; j <= i; j++){ st += j+"x"+i+"="+i*j; st += "  "; } st += "<br>"; } %> <table width="400" height="200"