平台无关:XML是WebService中表示数据的基本格式,而XML是无关平台的。
WebService创建一根单独的线程,不占用主题程序线程,使WebService服务更加快捷。
在src目录下创建一个META-INF目录
在META-INF目录下创建xfire目录
在xfire目录下创建services.xml文件
services.xml配置如下:
<service>
<name>......</name>//指定当前服务的名称(自定义)
<namespace>....../(<name></name>标签里的服务名称)</namespace>//指定当前服务的名称空间
<serviceClass>
//接口
</serviceClass>
<implementationClass>
//接口实现类
</implementationClass>
</service>
web.xml配置如下:
/*
*....原有的servlet配置
*/
//XFireServlet配置
<servlet>
<servlet-name>XFireServlet</servlet-name>
<servlet-class>
org.codehaus.xfire.transport.http.XFireConfigurableServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/servlet/XFireServlet/*</url-pattern> //处理客户端访问有XFire处理路径
</servlet-mapping>
<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/services/*</url-pattern> //处理客户端访问有XFire处理路径
</servlet-mapping>
//ClassServlet代码
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.codehaus.xfire.XFire;
import org.codehaus.xfire.XFireFactory;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import entity.Student;
import serv.IClass;
public class ClassServlet extends HttpServlet {
private static final long serialVersionUID = 7843686826225848696L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取会话
HttpSession session = request.getSession();
// 班级ID
int classId = Integer.parseInt(request.getParameter("classId"));
//测试获取的数据
System.out.println(classId);
// 创建服务的元数据
Service serviceModel = new ObjectServiceFactory()
.create(IClass.class);
System.out.println("返回了服务的模型.");
// 创建服务的代理
XFire xfire = XFireFactory.newInstance().getXFire();
XFireProxyFactory factory = new XFireProxyFactory(xfire);
// 服务的地址Servlet名称与services.xml中的name对应
String serviceUrl = "http://localhost:8080/WebServiceTest/services/classSer";
IClass newClass = null;
try {
//返回接口实现类的对象
newClass = (IClass) factory.create(serviceModel, serviceUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// 调用服务
List<Student> list = null;
try {
list = newClass.getClassByClassId(classId);
} catch (Exception e) {
e.printStackTrace();
}
session.setAttribute("list", list);
request.getRequestDispatcher("show.jsp").forward(request,response);
}
}